Upgrade ccapi from 5.31.2 -> 5.45.1
This commit is contained in:
1 parent
a1b923c826
commit
f21c6594c0
98 files changed
+9664
-2200
No files matched your search
@@ -45,16 +45,33 @@ class ExecutionManagementService : public Service {
|
||||
// each subscription creates a unique websocket connection
|
||||
void subscribe(std::vector<Subscription>& subscriptionList) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
CCAPI_LOGGER_DEBUG("this->baseUrl = " + this->baseUrl);
|
||||
CCAPI_LOGGER_DEBUG("this->baseUrlWs = " + this->baseUrlWs);
|
||||
if (this->shouldContinue.load()) {
|
||||
for (auto& subscription : subscriptionList) {
|
||||
wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(),
|
||||
[that = shared_from_base<ExecutionManagementService>(), subscription]() mutable {
|
||||
auto now = UtilTime::now();
|
||||
subscription.setTimeSent(now);
|
||||
WsConnection wsConnection(that->baseUrl, "", {subscription});
|
||||
that->prepareConnect(wsConnection);
|
||||
});
|
||||
boost::asio::post(*this->serviceContextPtr->ioContextPtr, [that = shared_from_base<ExecutionManagementService>(), subscription]() mutable {
|
||||
auto now = UtilTime::now();
|
||||
subscription.setTimeSent(now);
|
||||
auto credential = subscription.getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = that->credentialDefault;
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
WsConnection wsConnection(that->baseUrlWs, "", {subscription}, credential);
|
||||
that->prepareConnect(wsConnection);
|
||||
#else
|
||||
std::shared_ptr<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);
|
||||
} catch (const beast::error_code& ec) {
|
||||
CCAPI_LOGGER_TRACE("fail");
|
||||
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "create stream", {subscription.getCorrelationId()});
|
||||
return;
|
||||
}
|
||||
std::shared_ptr<WsConnection> wsConnectionPtr(new WsConnection(that->baseUrlWs, "", {subscription}, credential, streamPtr));
|
||||
CCAPI_LOGGER_WARN("about to subscribe with new wsConnectionPtr " + toString(*wsConnectionPtr));
|
||||
that->prepareConnect(wsConnectionPtr);
|
||||
#endif
|
||||
});
|
||||
}
|
||||
}
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
@@ -112,7 +129,7 @@ class ExecutionManagementService : public Service {
|
||||
void processSuccessfulTextMessageRest(int statusCode, const Request& request, const std::string& textMessage, const TimePoint& timeReceived,
|
||||
Queue<Event>* eventQueuePtr) override {
|
||||
Event event;
|
||||
if (this->doesHttpBodyContainError(request, textMessage)) {
|
||||
if (this->doesHttpBodyContainError(textMessage)) {
|
||||
event.setType(Event::Type::RESPONSE);
|
||||
Message message;
|
||||
message.setType(Message::Type::RESPONSE_ERROR);
|
||||
@@ -162,6 +179,13 @@ class ExecutionManagementService : public Service {
|
||||
}
|
||||
}
|
||||
}
|
||||
virtual void convertRequestForWebsocketCustom(rj::Document& document, rj::Document::AllocatorType& allocator, const WsConnection& wsConnection,
|
||||
const Request& request, int wsRequestId, const TimePoint& now, const std::string& symbolId,
|
||||
const std::map<std::string, std::string>& credential) {
|
||||
auto errorMessage = "Websocket unimplemented operation " + Request::operationToString(request.getOperation()) + " for exchange " + request.getExchange();
|
||||
throw std::runtime_error(errorMessage);
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
virtual void logonToExchange(const WsConnection& wsConnection, const TimePoint& now, const std::map<std::string, std::string>& credential) {
|
||||
CCAPI_LOGGER_INFO("about to logon to exchange");
|
||||
CCAPI_LOGGER_INFO("exchange is " + this->exchangeName);
|
||||
@@ -179,9 +203,7 @@ class ExecutionManagementService : public Service {
|
||||
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
auto subscription = wsConnection.subscriptionList.at(0);
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
this->onTextMessage(wsConnection, subscription, textMessage, document, timeReceived);
|
||||
this->onTextMessage(wsConnection, subscription, textMessage, timeReceived);
|
||||
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived);
|
||||
}
|
||||
void onOpen(wspp::connection_hdl hdl) override {
|
||||
@@ -192,10 +214,7 @@ class ExecutionManagementService : public Service {
|
||||
auto correlationId = wsConnection.subscriptionList.at(0).getCorrelationId();
|
||||
this->wsConnectionByCorrelationIdMap.insert({correlationId, wsConnection});
|
||||
this->correlationIdByConnectionIdMap.insert({wsConnection.id, correlationId});
|
||||
auto credential = wsConnection.subscriptionList.at(0).getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = this->credentialDefault;
|
||||
}
|
||||
auto credential = wsConnection.credential;
|
||||
this->logonToExchange(wsConnection, now, credential);
|
||||
}
|
||||
void onClose(wspp::connection_hdl hdl) override {
|
||||
@@ -208,53 +227,53 @@ class ExecutionManagementService : public Service {
|
||||
this->wsRequestIdByConnectionIdMap.erase(wsConnection.id);
|
||||
Service::onClose(hdl);
|
||||
}
|
||||
void sendRequestByWebsocket(Request& request, const TimePoint& now) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
CCAPI_LOGGER_TRACE("now = " + toString(now));
|
||||
wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), [that = shared_from_base<ExecutionManagementService>(), request]() mutable {
|
||||
auto now = UtilTime::now();
|
||||
CCAPI_LOGGER_DEBUG("request = " + toString(request));
|
||||
CCAPI_LOGGER_TRACE("now = " + toString(now));
|
||||
request.setTimeSent(now);
|
||||
auto nowFixTimeStr = UtilTime::convertTimePointToFIXTime(now);
|
||||
auto& correlationId = request.getCorrelationId();
|
||||
auto it = that->wsConnectionByCorrelationIdMap.find(correlationId);
|
||||
if (it == that->wsConnectionByCorrelationIdMap.end()) {
|
||||
that->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "Websocket connection was not found", {correlationId});
|
||||
return;
|
||||
}
|
||||
auto& wsConnection = it->second;
|
||||
CCAPI_LOGGER_TRACE("wsConnection = " + toString(wsConnection));
|
||||
auto instrument = request.getInstrument();
|
||||
auto symbolId = instrument;
|
||||
CCAPI_LOGGER_TRACE("symbolId = " + symbolId);
|
||||
virtual void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) {}
|
||||
#else
|
||||
virtual void logonToExchange(std::shared_ptr<WsConnection> wsConnectionPtr, 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);
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
auto subscription = wsConnection.subscriptionList.at(0);
|
||||
std::vector<std::string> sendStringList = this->createSendStringListFromSubscription(wsConnection, subscription, now, credential);
|
||||
for (const auto& sendString : sendStringList) {
|
||||
CCAPI_LOGGER_INFO("sendString = " + sendString);
|
||||
ErrorCode ec;
|
||||
rj::Document document;
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
auto credential = request.getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = that->credentialDefault;
|
||||
}
|
||||
that->convertRequestForWebsocket(document, allocator, wsConnection, request, ++that->wsRequestIdByConnectionIdMap[wsConnection.id], now, symbolId,
|
||||
credential);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
CCAPI_LOGGER_TRACE("sendString = " + sendString);
|
||||
that->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
this->send(wsConnectionPtr, sendString, ec);
|
||||
if (ec) {
|
||||
that->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request");
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
});
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
}
|
||||
virtual void convertRequestForWebsocketCustom(rj::Document& document, rj::Document::AllocatorType& allocator, const WsConnection& wsConnection,
|
||||
const Request& request, int wsRequestId, const TimePoint& now, const std::string& symbolId,
|
||||
const std::map<std::string, std::string>& credential) {
|
||||
auto errorMessage = "Websocket unimplemented operation " + Request::operationToString(request.getOperation()) + " for exchange " + request.getExchange();
|
||||
throw std::runtime_error(errorMessage);
|
||||
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);
|
||||
}
|
||||
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
Service::onOpen(wsConnectionPtr);
|
||||
auto now = UtilTime::now();
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
auto correlationId = wsConnection.subscriptionList.at(0).getCorrelationId();
|
||||
this->wsConnectionByCorrelationIdMap.insert({correlationId, wsConnectionPtr});
|
||||
this->correlationIdByConnectionIdMap.insert({wsConnection.id, correlationId});
|
||||
auto credential = wsConnection.credential;
|
||||
this->logonToExchange(wsConnectionPtr, now, credential);
|
||||
}
|
||||
void onClose(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode ec) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
if (this->correlationIdByConnectionIdMap.find(wsConnection.id) != this->correlationIdByConnectionIdMap.end()) {
|
||||
this->wsConnectionByCorrelationIdMap.erase(this->correlationIdByConnectionIdMap.at(wsConnection.id));
|
||||
this->correlationIdByConnectionIdMap.erase(wsConnection.id);
|
||||
}
|
||||
this->wsRequestIdByConnectionIdMap.erase(wsConnection.id);
|
||||
Service::onClose(wsConnectionPtr, ec);
|
||||
}
|
||||
virtual void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessage,
|
||||
const TimePoint& timeReceived) {}
|
||||
#endif
|
||||
void convertRequestForRestGenericPrivateRequest(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();
|
||||
@@ -291,8 +310,56 @@ class ExecutionManagementService : public Service {
|
||||
int64_t nonce = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count() + requestIndex;
|
||||
return nonce;
|
||||
}
|
||||
virtual void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
const TimePoint& timeReceived) {}
|
||||
void sendRequestByWebsocket(Request& request, const TimePoint& now) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
CCAPI_LOGGER_TRACE("now = " + toString(now));
|
||||
boost::asio::post(*this->serviceContextPtr->ioContextPtr, [that = shared_from_base<ExecutionManagementService>(), request]() mutable {
|
||||
auto now = UtilTime::now();
|
||||
CCAPI_LOGGER_DEBUG("request = " + toString(request));
|
||||
CCAPI_LOGGER_TRACE("now = " + toString(now));
|
||||
request.setTimeSent(now);
|
||||
auto nowFixTimeStr = UtilTime::convertTimePointToFIXTime(now);
|
||||
auto& correlationId = request.getCorrelationId();
|
||||
auto it = that->wsConnectionByCorrelationIdMap.find(correlationId);
|
||||
if (it == that->wsConnectionByCorrelationIdMap.end()) {
|
||||
that->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "Websocket connection was not found", {correlationId});
|
||||
return;
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
auto& wsConnection = it->second;
|
||||
#else
|
||||
auto wsConnectionPtr = it->second;
|
||||
auto& wsConnection = *wsConnectionPtr;
|
||||
#endif
|
||||
CCAPI_LOGGER_TRACE("wsConnection = " + toString(wsConnection));
|
||||
auto instrument = request.getInstrument();
|
||||
auto symbolId = instrument;
|
||||
CCAPI_LOGGER_TRACE("symbolId = " + symbolId);
|
||||
ErrorCode ec;
|
||||
rj::Document document;
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
auto credential = request.getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = that->credentialDefault;
|
||||
}
|
||||
that->convertRequestForWebsocket(document, allocator, wsConnection, request, ++that->wsRequestIdByConnectionIdMap[wsConnection.id], now, symbolId,
|
||||
credential);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
CCAPI_LOGGER_TRACE("sendString = " + sendString);
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
that->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
#else
|
||||
that->send(wsConnectionPtr, sendString, ec);
|
||||
#endif
|
||||
if (ec) {
|
||||
that->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request");
|
||||
}
|
||||
});
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
virtual void convertRequestForRest(http::request<http::string_body>& req, const Request& request, const std::string& wsRequestId, const TimePoint& now,
|
||||
const std::string& symbolId, const std::map<std::string, std::string>& credential) {}
|
||||
virtual void convertRequestForWebsocket(rj::Document& document, rj::Document::AllocatorType& allocator, const WsConnection& wsConnection,
|
||||
@@ -318,7 +385,12 @@ class ExecutionManagementService : public Service {
|
||||
std::string getAccountBalancesTarget;
|
||||
std::string getAccountPositionsTarget;
|
||||
std::map<std::string, std::string> correlationIdByConnectionIdMap;
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
std::map<std::string, WsConnection> wsConnectionByCorrelationIdMap;
|
||||
#else
|
||||
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;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_ASCENDEX;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_ASCENDEX_API_KEY;
|
||||
this->apiSecretName = CCAPI_ASCENDEX_API_SECRET;
|
||||
this->apiAccountGroupName = CCAPI_ASCENDEX_API_ACCOUNT_GROUP;
|
||||
@@ -38,8 +47,8 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
wsConnection.status = WsConnection::Status::OPEN;
|
||||
}
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; }
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({ "op": "ping" })", wspp::frame::opcode::text, ec); }
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; }
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); }
|
||||
void signReqeustForRestGenericPrivateRequest(http::request<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 {
|
||||
@@ -350,7 +359,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
|
||||
credential = that->credentialDefault;
|
||||
}
|
||||
const auto& accountGroup = mapGetWithDefault(credential, that->apiAccountGroupName);
|
||||
WsConnection wsConnection(that->baseUrl + "/" + accountGroup + "/api/pro/v1/stream", "", {subscription});
|
||||
WsConnection wsConnection(that->baseUrlWs + "/" + accountGroup + "/api/pro/v1/stream", "", {subscription}, credential);
|
||||
that->prepareConnect(wsConnection);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -13,14 +13,23 @@ class ExecutionManagementServiceBinance : public ExecutionManagementServiceBinan
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BINANCE_API_KEY;
|
||||
this->apiSecretName = CCAPI_BINANCE_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -31,6 +40,15 @@ class ExecutionManagementServiceBinance : public ExecutionManagementServiceBinan
|
||||
this->cancelOpenOrdersTarget = "/api/v3/openOrders";
|
||||
this->listenKeyTarget = CCAPI_BINANCE_LISTEN_KEY_PATH;
|
||||
this->getAccountBalancesTarget = "/api/v3/account";
|
||||
this->createOrderMarginTarget = "/sapi/v1/margin/order";
|
||||
this->cancelOrderMarginTarget = "/sapi/v1/margin/order";
|
||||
this->getOrderMarginTarget = "/sapi/v1/margin/order";
|
||||
this->getOpenOrdersMarginTarget = "/sapi/v1/margin/openOrders";
|
||||
this->cancelOpenOrdersMarginTarget = "/sapi/v1/margin/openOrders";
|
||||
this->getAccountBalancesCrossMarginTarget = "/sapi/v1/margin/account";
|
||||
this->getAccountBalancesIsolatedMarginTarget = "/sapi/v1/margin/isolated/account";
|
||||
this->listenKeyCrossMarginTarget = CCAPI_BINANCE_LISTEN_KEY_CROSS_MARGIN_PATH;
|
||||
this->listenKeyIsolatedMarginTarget = CCAPI_BINANCE_LISTEN_KEY_ISOLATED_MARGIN_PATH;
|
||||
}
|
||||
virtual ~ExecutionManagementServiceBinance() {}
|
||||
};
|
||||
|
||||
+118
-23
@@ -1,5 +1,5 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_BASE_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_BASE_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#if defined(CCAPI_ENABLE_EXCHANGE_BINANCE_US) || defined(CCAPI_ENABLE_EXCHANGE_BINANCE) || defined(CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES) || \
|
||||
defined(CCAPI_ENABLE_EXCHANGE_BINANCE_COIN_FUTURES)
|
||||
@@ -92,7 +92,10 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
|
||||
}
|
||||
}
|
||||
this->signRequest(queryString, param, now, credential);
|
||||
req.target(std::string(this->createOrderTarget) + "?" + queryString);
|
||||
req.target((request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN
|
||||
? this->createOrderMarginTarget
|
||||
: this->createOrderTarget) +
|
||||
"?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_ORDER: {
|
||||
req.method(http::verb::delete_);
|
||||
@@ -105,7 +108,10 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
|
||||
});
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
this->signRequest(queryString, param, now, credential);
|
||||
req.target(this->cancelOrderTarget + "?" + queryString);
|
||||
req.target((request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN
|
||||
? this->cancelOrderMarginTarget
|
||||
: this->cancelOrderTarget) +
|
||||
"?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::GET_ORDER: {
|
||||
req.method(http::verb::get);
|
||||
@@ -118,7 +124,10 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
|
||||
});
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
this->signRequest(queryString, param, now, credential);
|
||||
req.target(this->getOrderTarget + "?" + queryString);
|
||||
req.target((request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN
|
||||
? this->getOrderMarginTarget
|
||||
: this->getOrderTarget) +
|
||||
"?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::GET_OPEN_ORDERS: {
|
||||
req.method(http::verb::get);
|
||||
@@ -128,7 +137,10 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
}
|
||||
this->signRequest(queryString, {}, now, credential);
|
||||
req.target(this->getOpenOrdersTarget + "?" + queryString);
|
||||
req.target((request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN
|
||||
? this->getOpenOrdersMarginTarget
|
||||
: this->getOpenOrdersTarget) +
|
||||
"?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_OPEN_ORDERS: {
|
||||
req.method(http::verb::delete_);
|
||||
@@ -136,14 +148,29 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
|
||||
this->appendParam(queryString, {});
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
this->signRequest(queryString, {}, now, credential);
|
||||
req.target(this->cancelOpenOrdersTarget + "?" + queryString);
|
||||
req.target((request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN
|
||||
? this->cancelOpenOrdersMarginTarget
|
||||
: this->cancelOpenOrdersTarget) +
|
||||
"?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_BALANCES: {
|
||||
req.method(http::verb::get);
|
||||
std::string queryString;
|
||||
this->appendParam(queryString, {});
|
||||
if (!symbolId.empty()) {
|
||||
queryString += "symbols=";
|
||||
queryString += Url::urlEncode(symbolId);
|
||||
queryString += "&";
|
||||
}
|
||||
this->signRequest(queryString, {}, now, credential);
|
||||
req.target(this->getAccountBalancesTarget + "?" + queryString);
|
||||
const auto& marginType = request.getMarginType();
|
||||
std::string target = this->getAccountBalancesTarget;
|
||||
if (marginType == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN) {
|
||||
target = this->getAccountBalancesCrossMarginTarget;
|
||||
} else if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) {
|
||||
target = this->getAccountBalancesIsolatedMarginTarget;
|
||||
}
|
||||
req.target(target + "?" + queryString);
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
@@ -182,16 +209,58 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
|
||||
const rj::Document& document) override {
|
||||
switch (request.getOperation()) {
|
||||
case Request::Operation::GET_ACCOUNT_BALANCES: {
|
||||
for (const auto& x : document[this->isDerivatives ? "assets" : "balances"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ASSET, x["asset"].GetString());
|
||||
if (this->isDerivatives) {
|
||||
const auto& marginType = request.getMarginType();
|
||||
if (this->isDerivatives) {
|
||||
for (const auto& x : document["assets"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ASSET, x["asset"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["availableBalance"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else {
|
||||
if (marginType == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN) {
|
||||
for (const auto& x : document["userAssets"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ASSET, x["asset"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(x["free"].GetString()).add(Decimal(x["locked"].GetString())).toString());
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["free"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_LIABILITY, Decimal(x["borrowed"].GetString()).add(Decimal(x["interest"].GetString())).toString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) {
|
||||
for (const auto& x : document["assets"].GetArray()) {
|
||||
std::string symbol = x["symbol"].GetString();
|
||||
{
|
||||
const auto& y = x["baseAsset"];
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_INSTRUMENT, symbol);
|
||||
element.insert(CCAPI_EM_ASSET, y["asset"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(y["free"].GetString()).add(Decimal(y["locked"].GetString())).toString());
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, y["free"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_LIABILITY, Decimal(y["borrowed"].GetString()).add(Decimal(y["interest"].GetString())).toString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
{
|
||||
const auto& y = x["quoteAsset"];
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_INSTRUMENT, symbol);
|
||||
element.insert(CCAPI_EM_ASSET, y["asset"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(y["free"].GetString()).add(Decimal(y["locked"].GetString())).toString());
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, y["free"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_LIABILITY, Decimal(y["borrowed"].GetString()).add(Decimal(y["interest"].GetString())).toString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(x["free"].GetString()).add(Decimal(x["locked"].GetString())).toString());
|
||||
for (const auto& x : document["balances"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ASSET, x["asset"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(x["free"].GetString()).add(Decimal(x["locked"].GetString())).toString());
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["free"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
}
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x[this->isDerivatives ? "availableBalance" : "free"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} break;
|
||||
default:
|
||||
@@ -207,7 +276,13 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
|
||||
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
|
||||
req.method(http::verb::post);
|
||||
std::string target = this->listenKeyTarget;
|
||||
if (this->listenKeyTarget == "/sapi/v1/userDataStream/isolated") {
|
||||
const auto& marginType = wsConnection.subscriptionList.at(0).getMarginType();
|
||||
if (marginType == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN) {
|
||||
target = this->listenKeyCrossMarginTarget;
|
||||
} else if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) {
|
||||
target = this->listenKeyIsolatedMarginTarget;
|
||||
}
|
||||
if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) {
|
||||
auto symbol = wsConnection.subscriptionList.at(0).getInstrument();
|
||||
target += "?" + symbol;
|
||||
}
|
||||
@@ -234,7 +309,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
|
||||
std::string listenKey = document["listenKey"].GetString();
|
||||
std::string url = that->baseUrl + "/" + listenKey;
|
||||
std::string url = that->baseUrlWs + "/" + listenKey;
|
||||
thisWsConnection.url = url;
|
||||
that->connect(thisWsConnection);
|
||||
that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({
|
||||
@@ -258,25 +333,34 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
|
||||
Message message;
|
||||
message.setTimeReceived(now);
|
||||
message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
message.setCorrelationIdList({wsConnection.subscriptionList.at(0).getCorrelationId()});
|
||||
event.setMessageList({message});
|
||||
this->eventHandler(event, nullptr);
|
||||
setPingListenKeyTimer(wsConnection);
|
||||
this->setPingListenKeyTimer(wsConnection);
|
||||
}
|
||||
void setPingListenKeyTimer(const WsConnection& wsConnection) {
|
||||
this->pingListenKeyTimerMapByConnectionIdMap[wsConnection.id] = this->serviceContextPtr->tlsClientPtr->set_timer(
|
||||
this->pingListenKeyIntervalSeconds * 1000, [wsConnection, that = shared_from_base<ExecutionManagementServiceBinanceBase>()](ErrorCode const& ec) {
|
||||
if (ec) return;
|
||||
if (ec) {
|
||||
return;
|
||||
}
|
||||
that->setPingListenKeyTimer(wsConnection);
|
||||
http::request<http::string_body> req;
|
||||
req.set(http::field::host, that->hostRest);
|
||||
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
|
||||
req.method(http::verb::put);
|
||||
std::string target = that->listenKeyTarget;
|
||||
const auto& marginType = wsConnection.subscriptionList.at(0).getMarginType();
|
||||
if (marginType == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN) {
|
||||
target = that->listenKeyCrossMarginTarget;
|
||||
} else if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) {
|
||||
target = that->listenKeyIsolatedMarginTarget;
|
||||
}
|
||||
if (!that->isDerivatives) {
|
||||
std::map<std::string, std::string> params;
|
||||
auto listenKey = that->extraPropertyByConnectionIdMap.at(wsConnection.id).at("listenKey");
|
||||
params.insert({"listenKey", listenKey});
|
||||
if (that->listenKeyTarget == "/sapi/v1/userDataStream/isolated") {
|
||||
if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) {
|
||||
auto symbol = wsConnection.subscriptionList.at(0).getInstrument();
|
||||
params.insert({"symbol", symbol});
|
||||
}
|
||||
@@ -313,8 +397,10 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
|
||||
}
|
||||
ExecutionManagementService::onClose(hdl);
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
@@ -394,7 +480,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
|
||||
auto it = data.FindMember("ap");
|
||||
if (it != data.MemberEnd() && !it->value.IsNull()) {
|
||||
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
|
||||
std::to_string(std::stod(it->value.GetString()) * std::stod(data["z"].GetString())));
|
||||
UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(data["z"].GetString())));
|
||||
}
|
||||
}
|
||||
std::vector<Element> elementList;
|
||||
@@ -411,8 +497,17 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
|
||||
std::string listenKeyTarget;
|
||||
int pingListenKeyIntervalSeconds;
|
||||
std::map<std::string, TimerPtr> pingListenKeyTimerMapByConnectionIdMap;
|
||||
std::string createOrderMarginTarget;
|
||||
std::string cancelOrderMarginTarget;
|
||||
std::string getOrderMarginTarget;
|
||||
std::string getOpenOrdersMarginTarget;
|
||||
std::string cancelOpenOrdersMarginTarget;
|
||||
std::string getAccountBalancesCrossMarginTarget;
|
||||
std::string getAccountBalancesIsolatedMarginTarget;
|
||||
std::string listenKeyCrossMarginTarget;
|
||||
std::string listenKeyIsolatedMarginTarget;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_BASE_H_
|
||||
+11
-2
@@ -10,14 +10,23 @@ class ExecutionManagementServiceBinanceCoinFutures : public ExecutionManagementS
|
||||
SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceBinanceDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BINANCE_COIN_FUTURES_API_KEY;
|
||||
this->apiSecretName = CCAPI_BINANCE_COIN_FUTURES_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -29,7 +38,7 @@ class ExecutionManagementServiceBinanceCoinFutures : public ExecutionManagementS
|
||||
this->isDerivatives = true;
|
||||
this->listenKeyTarget = CCAPI_BINANCE_COIN_FUTURES_LISTEN_KEY_PATH;
|
||||
this->getAccountBalancesTarget = "/dapi/v1/account";
|
||||
this->getAccountPositionsTarget = "/dapi/v1/account";
|
||||
this->getAccountPositionsTarget = "/dapi/v1/positionRisk";
|
||||
}
|
||||
virtual ~ExecutionManagementServiceBinanceCoinFutures() {}
|
||||
};
|
||||
|
||||
+2
-2
@@ -31,7 +31,7 @@ class ExecutionManagementServiceBinanceDerivativesBase : public ExecutionManagem
|
||||
const rj::Document& document) override {
|
||||
switch (request.getOperation()) {
|
||||
case Request::Operation::GET_ACCOUNT_POSITIONS: {
|
||||
for (const auto& x : document["positions"].GetArray()) {
|
||||
for (const auto& x : document.GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_SIDE, x["positionSide"].GetString());
|
||||
@@ -43,7 +43,7 @@ class ExecutionManagementServiceBinanceDerivativesBase : public ExecutionManagem
|
||||
positionAmt = x["maxQty"].GetString();
|
||||
}
|
||||
element.insert(CCAPI_EM_POSITION_QUANTITY, positionAmt);
|
||||
element.insert(CCAPI_EM_POSITION_COST, std::to_string(std::stod(x["entryPrice"].GetString()) * std::stod(positionAmt)));
|
||||
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["entryPrice"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceBinanceUs : public ExecutionManagementServiceBin
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_US;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BINANCE_US_API_KEY;
|
||||
this->apiSecretName = CCAPI_BINANCE_US_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
|
||||
+11
-2
@@ -10,14 +10,23 @@ class ExecutionManagementServiceBinanceUsdsFutures : public ExecutionManagementS
|
||||
SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceBinanceDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BINANCE_USDS_FUTURES_API_KEY;
|
||||
this->apiSecretName = CCAPI_BINANCE_USDS_FUTURES_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -29,7 +38,7 @@ class ExecutionManagementServiceBinanceUsdsFutures : public ExecutionManagementS
|
||||
this->isDerivatives = true;
|
||||
this->listenKeyTarget = CCAPI_BINANCE_USDS_FUTURES_LISTEN_KEY_PATH;
|
||||
this->getAccountBalancesTarget = "/fapi/v2/account";
|
||||
this->getAccountPositionsTarget = "/fapi/v2/account";
|
||||
this->getAccountPositionsTarget = "/fapi/v2/positionRisk";
|
||||
}
|
||||
virtual ~ExecutionManagementServiceBinanceUsdsFutures() {}
|
||||
};
|
||||
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BITFINEX;
|
||||
this->baseUrl = std::string(CCAPI_BITFINEX_PRIVATE_URL_WS_BASE) + "/ws/2";
|
||||
this->baseUrlWs = std::string(CCAPI_BITFINEX_PRIVATE_URL_WS_BASE) + "/ws/2";
|
||||
this->baseUrlRest = CCAPI_BITFINEX_PRIVATE_URL_REST_BASE;
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BITFINEX_API_KEY;
|
||||
this->apiSecretName = CCAPI_BITFINEX_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -227,10 +236,14 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
|
||||
}
|
||||
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
|
||||
const rj::Document& document) override {
|
||||
if (operation == Request::Operation::CREATE_ORDER || operation == Request::Operation::CANCEL_ORDER) {
|
||||
if (operation == Request::Operation::CREATE_ORDER) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, document[4][0]);
|
||||
elementList.emplace_back(std::move(element));
|
||||
} else if (operation == Request::Operation::CANCEL_ORDER) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, document[4]);
|
||||
elementList.emplace_back(std::move(element));
|
||||
} else if (operation == Request::Operation::GET_ORDER) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, document[0]);
|
||||
@@ -269,7 +282,7 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
|
||||
std::string availPos = x["availPos"].GetString();
|
||||
std::string positionQuantity = availPos.empty() ? x["pos"].GetString() : availPos;
|
||||
element.insert(CCAPI_EM_POSITION_QUANTITY, positionQuantity);
|
||||
element.insert(CCAPI_EM_POSITION_COST, std::to_string(std::stod(x["avgPx"].GetString()) * std::stod(positionQuantity)));
|
||||
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgPx"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["lever"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
@@ -340,8 +353,10 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_BITGET
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service_bitget_base.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitgetBase {
|
||||
public:
|
||||
ExecutionManagementServiceBitget(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET;
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/v1/stream";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BITGET_API_KEY;
|
||||
this->apiSecretName = CCAPI_BITGET_API_SECRET;
|
||||
this->apiPassphraseName = CCAPI_BITGET_API_PASSPHRASE;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
|
||||
this->createOrderTarget = "/api/spot/v1/trade/orders";
|
||||
this->cancelOrderTarget = "/api/spot/v1/trade/cancel-order";
|
||||
this->getOrderTarget = "/api/spot/v1/trade/orderInfo";
|
||||
this->getOpenOrdersTarget = "/api/spot/v1/trade/open-orders";
|
||||
this->getAccountBalancesTarget = "/api/spot/v1/account/assets";
|
||||
}
|
||||
virtual ~ExecutionManagementServiceBitget() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
private:
|
||||
#endif
|
||||
void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {
|
||||
{CCAPI_EM_ORDER_SIDE, "side"},
|
||||
{CCAPI_EM_ORDER_QUANTITY, "quantity"},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "clientOrderId"},
|
||||
{CCAPI_SYMBOL_ID, "symbol"},
|
||||
{CCAPI_EM_ORDER_ID, "orderId"},
|
||||
}) {
|
||||
for (const auto& kv : param) {
|
||||
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
auto value = kv.second;
|
||||
if (key == "side") {
|
||||
value = (value == CCAPI_EM_ORDER_SIDE_BUY || value == "buy") ? "buy" : "sell";
|
||||
}
|
||||
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
}
|
||||
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {
|
||||
{CCAPI_EM_ORDER_ID, "orderId"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "clientOrderId"},
|
||||
{CCAPI_SYMBOL_ID, "symbol"},
|
||||
}) {
|
||||
for (const auto& kv : param) {
|
||||
queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
queryString += "=";
|
||||
queryString += Url::urlEncode(kv.second);
|
||||
queryString += "&";
|
||||
}
|
||||
}
|
||||
void convertRequestForRest(http::request<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, request, now, symbolId, credential);
|
||||
Request::Operation operation = request.getOperation();
|
||||
switch (operation) {
|
||||
case Request::Operation::GENERIC_PRIVATE_REQUEST: {
|
||||
ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential);
|
||||
} break;
|
||||
case Request::Operation::CREATE_ORDER: {
|
||||
req.set("X-CHANNEL-API-CODE", CCAPI_BITGET_API_CHANNEL_API_CODE);
|
||||
req.method(http::verb::post);
|
||||
req.target(this->createOrderTarget);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (param.find("orderType") == param.end()) {
|
||||
document.AddMember("orderType", rj::Value("limit").Move(), allocator);
|
||||
}
|
||||
if (param.find("force") == param.end()) {
|
||||
document.AddMember("force", rj::Value("normal").Move(), allocator);
|
||||
}
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
}
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_ORDER: {
|
||||
req.method(http::verb::post);
|
||||
req.target(this->cancelOrderTarget);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
}
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ORDER: {
|
||||
req.method(http::verb::post);
|
||||
req.target(this->getOrderTarget);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
}
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::GET_OPEN_ORDERS: {
|
||||
req.method(http::verb::post);
|
||||
req.target(this->getOpenOrdersTarget);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
}
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_BALANCES: {
|
||||
req.method(http::verb::get);
|
||||
req.target(this->getAccountBalancesTarget);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
void extractOrderInfoFromRequest(std::vector<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 = {
|
||||
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOrderId", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("quantity", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("fillQuantity", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("fillTotalAmount", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}};
|
||||
if (operation != Request::Operation::CANCEL_ORDER) {
|
||||
const rj::Value& data = document["data"];
|
||||
if (data.IsObject()) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, data, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
} else {
|
||||
for (const auto& x : data.GetArray()) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void extractAccountInfoFromRequest(std::vector<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["data"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ASSET, x["coinName"].GetString());
|
||||
std::string available = x["available"].GetString();
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, available);
|
||||
std::string frozen = x["frozen"].GetString();
|
||||
std::string lock = x["lock"].GetString();
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, (Decimal(available).add(Decimal(frozen)).add(Decimal(lock))).toString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} break;
|
||||
default:
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
void extractOrderInfo(Element& element, const rj::Value& x,
|
||||
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
|
||||
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
{
|
||||
auto it1 = x.FindMember("accFillSz");
|
||||
auto it2 = x.FindMember("avgPx");
|
||||
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
|
||||
auto it1Str = std::string(it1->value.GetString());
|
||||
auto it2Str = std::string(it2->value.GetString());
|
||||
if (!it1Str.empty() && !it2Str.empty()) {
|
||||
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<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("login").Move(), allocator);
|
||||
rj::Value arg(rj::kObjectType);
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
|
||||
std::string ts = std::to_string(std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count());
|
||||
arg.AddMember("apiKey", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("passphrase", rj::Value(apiPassphrase.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("timestamp", rj::Value(ts.c_str(), allocator).Move(), allocator);
|
||||
std::string signData = ts + "GET" + "/user/verify";
|
||||
std::string sign = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, signData));
|
||||
arg.AddMember("sign", rj::Value(sign.c_str(), allocator).Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
args.PushBack(arg, allocator);
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
if (textMessage != "pong") {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
auto it = document.FindMember("event");
|
||||
std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : "";
|
||||
if (eventStr == "login") {
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
auto& allocator = document.GetAllocator();
|
||||
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
for (const auto& field : fieldSet) {
|
||||
std::string channel;
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
channel = "orders";
|
||||
}
|
||||
for (const auto& instrument : instrumentSet) {
|
||||
rj::Value arg(rj::kObjectType);
|
||||
arg.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("instId", rj::Value(instrument.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("instType", rj::Value("spbl").Move(), allocator);
|
||||
args.PushBack(arg, allocator);
|
||||
}
|
||||
}
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBufferSubscribe;
|
||||
rj::Writer<rj::StringBuffer> writerSubscribe(stringBufferSubscribe);
|
||||
document.Accept(writerSubscribe);
|
||||
std::string sendString = stringBufferSubscribe.GetString();
|
||||
ErrorCode ec;
|
||||
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
} else {
|
||||
Event event = this->createEvent(subscription, textMessage, document, eventStr, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const std::string& eventStr,
|
||||
const TimePoint& timeReceived) {
|
||||
Event event;
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
const auto& correlationId = subscription.getCorrelationId();
|
||||
message.setCorrelationIdList({correlationId});
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
if (eventStr.empty()) {
|
||||
const rj::Value& arg = document["arg"];
|
||||
std::string channel = std::string(arg["channel"].GetString());
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
std::string instrument = arg["instId"].GetString();
|
||||
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
if (channel == "orders") {
|
||||
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
const rj::Value& data = document["data"];
|
||||
for (const auto& x : data.GetArray()) {
|
||||
auto itTradeId = x.FindMember("tradeId");
|
||||
std::string tradeId = itTradeId != x.MemberEnd() ? itTradeId->value.GetString() : "";
|
||||
if (!tradeId.empty()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString()))));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
std::vector<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_IS_MAKER, std::string(x["execType"].GetString()) == "M" ? "1" : "0");
|
||||
element.insert(CCAPI_EM_ORDER_ID, std::string(x["ordId"].GetString()));
|
||||
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdId"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fillFee"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCcy"].GetString()));
|
||||
elementList.emplace_back(std::move(element));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
|
||||
const rj::Value& data = document["data"];
|
||||
for (const auto& x : data.GetArray()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString()))));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
const std::map<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_STATUS, std::make_pair("status", JsonDataType::STRING)},
|
||||
};
|
||||
Element info;
|
||||
this->extractOrderInfo(info, x, extractionFieldNameMap);
|
||||
info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
std::vector<Element> elementList;
|
||||
elementList.emplace_back(std::move(info));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (eventStr == "subscribe") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
Element element;
|
||||
element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (eventStr == "error") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
event.setMessageList(messageList);
|
||||
return event;
|
||||
}
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_H_
|
||||
@@ -0,0 +1,72 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_BASE_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_BASE_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#if defined(CCAPI_ENABLE_EXCHANGE_BITGET) || defined(CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES)
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceBitgetBase : public ExecutionManagementService {
|
||||
public:
|
||||
ExecutionManagementServiceBitgetBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
|
||||
virtual ~ExecutionManagementServiceBitgetBase() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
protected:
|
||||
#endif
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"00000\"")); }
|
||||
void signReqeustForRestGenericPrivateRequest(http::request<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 apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto preSignedText = req.base().at("ACCESS-TIMESTAMP").to_string();
|
||||
preSignedText += methodString;
|
||||
auto target = path;
|
||||
if (!queryString.empty()) {
|
||||
target += "?";
|
||||
target += queryString;
|
||||
}
|
||||
preSignedText += target;
|
||||
preSignedText += body;
|
||||
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText));
|
||||
if (!headerString.empty()) {
|
||||
headerString += "\r\n";
|
||||
}
|
||||
headerString += "ACCESS-SIGN:" + signature;
|
||||
}
|
||||
void signRequest(http::request<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("ACCESS-TIMESTAMP").to_string();
|
||||
preSignedText += std::string(req.method_string());
|
||||
preSignedText += req.target().to_string();
|
||||
preSignedText += body;
|
||||
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText));
|
||||
req.set("ACCESS-SIGN", signature);
|
||||
req.body() = body;
|
||||
req.prepare_payload();
|
||||
}
|
||||
void appendSymbolId(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
|
||||
rjValue.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
void appendSymbolId(std::string& queryString, const std::string& symbolId) {
|
||||
queryString += "symbol=";
|
||||
queryString += Url::urlEncode(symbolId);
|
||||
queryString += "&";
|
||||
}
|
||||
void prepareReq(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
|
||||
const std::map<std::string, std::string>& credential) {
|
||||
req.set(beast::http::field::content_type, "application/json");
|
||||
req.set("locale", "en-US");
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
req.set("ACCESS-KEY", apiKey);
|
||||
req.set("ACCESS-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
|
||||
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
|
||||
req.set("ACCESS-PASSPHRASE", apiPassphrase);
|
||||
}
|
||||
std::string apiPassphraseName;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_BASE_H_
|
||||
@@ -0,0 +1,455 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_FUTURES_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_FUTURES_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service_bitget_base.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServiceBitgetBase {
|
||||
public:
|
||||
ExecutionManagementServiceBitgetFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET_FUTURES;
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/mix/v1/stream";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BITGET_FUTURES_API_KEY;
|
||||
this->apiSecretName = CCAPI_BITGET_FUTURES_API_SECRET;
|
||||
this->apiPassphraseName = CCAPI_BITGET_FUTURES_API_PASSPHRASE;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
|
||||
this->createOrderTarget = "/api/mix/v1/order/placeOrder";
|
||||
this->cancelOrderTarget = "/api/mix/v1/order/cancel-order";
|
||||
this->getOrderTarget = "/api/mix/v1/order/detail";
|
||||
this->getOpenOrdersTarget = "/api/mix/v1/order/current";
|
||||
this->getAllOpenOrdersTarget = "/api/mix/v1/order/marginCoinCurrent";
|
||||
this->cancelOpenOrdersTarget = "/api/mix/v1/order/cancel-all-orders";
|
||||
this->getAccountBalancesTarget = "/api/mix/v1/account/accounts";
|
||||
this->getAccountPositionsTarget = "/api/mix/v1/position/singlePosition";
|
||||
this->getAccountAllPositionsTarget = "/api/mix/v1/position/allPosition";
|
||||
}
|
||||
virtual ~ExecutionManagementServiceBitgetFutures() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
private:
|
||||
#endif
|
||||
void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {
|
||||
{CCAPI_MARGIN_ASSET, "marginCoin"},
|
||||
{CCAPI_EM_ORDER_SIDE, "side"},
|
||||
{CCAPI_EM_ORDER_QUANTITY, "size"},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "clientOid"},
|
||||
{CCAPI_SYMBOL_ID, "symbol"},
|
||||
{CCAPI_EM_ORDER_ID, "orderId"},
|
||||
{CCAPI_INSTRUMENT_TYPE, "productType"},
|
||||
}) {
|
||||
for (const auto& kv : param) {
|
||||
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
auto value = kv.second;
|
||||
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
}
|
||||
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {
|
||||
{CCAPI_EM_ORDER_ID, "orderId"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "clientOrderId"},
|
||||
{CCAPI_SYMBOL_ID, "symbol"},
|
||||
{CCAPI_INSTRUMENT_TYPE, "productType"},
|
||||
}) {
|
||||
for (const auto& kv : param) {
|
||||
queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
queryString += "=";
|
||||
queryString += Url::urlEncode(kv.second);
|
||||
queryString += "&";
|
||||
}
|
||||
}
|
||||
void convertRequestForRest(http::request<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, request, now, symbolId, credential);
|
||||
Request::Operation operation = request.getOperation();
|
||||
switch (operation) {
|
||||
case Request::Operation::GENERIC_PRIVATE_REQUEST: {
|
||||
ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential);
|
||||
} break;
|
||||
case Request::Operation::CREATE_ORDER: {
|
||||
req.set("X-CHANNEL-API-CODE", CCAPI_BITGET_API_CHANNEL_API_CODE);
|
||||
req.method(http::verb::post);
|
||||
req.target(this->createOrderTarget);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (param.find("orderType") == param.end()) {
|
||||
document.AddMember("orderType", rj::Value("limit").Move(), allocator);
|
||||
}
|
||||
if (param.find("timeInForceValue") == param.end()) {
|
||||
document.AddMember("timeInForceValue", rj::Value("normal").Move(), allocator);
|
||||
}
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
}
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_ORDER: {
|
||||
req.method(http::verb::post);
|
||||
req.target(this->cancelOrderTarget);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
}
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ORDER: {
|
||||
req.method(http::verb::get);
|
||||
std::string queryString;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
}
|
||||
if (queryString.back() == '&') {
|
||||
queryString.pop_back();
|
||||
}
|
||||
req.target(this->getOrderTarget + "?" + queryString);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_OPEN_ORDERS: {
|
||||
req.method(http::verb::get);
|
||||
std::string queryString;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param);
|
||||
std::string path;
|
||||
if (symbolId.empty()) {
|
||||
path = this->getAllOpenOrdersTarget;
|
||||
} else {
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
path = this->getOpenOrdersTarget;
|
||||
}
|
||||
if (queryString.back() == '&') {
|
||||
queryString.pop_back();
|
||||
}
|
||||
req.target(path + "?" + queryString);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_OPEN_ORDERS: {
|
||||
req.method(http::verb::post);
|
||||
req.target(this->cancelOpenOrdersTarget);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
}
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_BALANCES: {
|
||||
req.method(http::verb::get);
|
||||
std::string queryString;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
}
|
||||
if (queryString.back() == '&') {
|
||||
queryString.pop_back();
|
||||
}
|
||||
req.target(this->getAccountBalancesTarget + "?" + queryString);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_POSITIONS: {
|
||||
req.method(http::verb::get);
|
||||
std::string queryString;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param);
|
||||
std::string path;
|
||||
if (symbolId.empty()) {
|
||||
path = this->getAccountAllPositionsTarget;
|
||||
} else {
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
path = this->getAccountPositionsTarget;
|
||||
}
|
||||
if (queryString.back() == '&') {
|
||||
queryString.pop_back();
|
||||
}
|
||||
req.target(path + "?" + queryString);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
void extractOrderInfoFromRequest(std::vector<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 = {
|
||||
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filledQty", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}};
|
||||
const rj::Value& data = document["data"];
|
||||
if (operation == Request::Operation::CREATE_ORDER || operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::GET_ORDER) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, data, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
} else if (operation == Request::Operation::GET_OPEN_ORDERS) {
|
||||
for (const auto& x : data.GetArray()) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
}
|
||||
}
|
||||
void extractAccountInfoFromRequest(std::vector<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["data"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ASSET, x["coinName"].GetString());
|
||||
std::string available = x["available"].GetString();
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, available);
|
||||
std::string frozen = x["frozen"].GetString();
|
||||
std::string lock = x["lock"].GetString();
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, (Decimal(available).add(Decimal(frozen)).add(Decimal(lock))).toString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_POSITIONS: {
|
||||
for (const auto& x : document["data"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
element.insert(CCAPI_MARGIN_ASSET, x["marginCoin"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_SIDE, x["holdSide"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_QUANTITY, x["total"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["averageOpenPrice"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} break;
|
||||
default:
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
void extractOrderInfo(Element& element, const rj::Value& x,
|
||||
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
|
||||
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
{
|
||||
auto it1 = x.FindMember("accFillSz");
|
||||
auto it2 = x.FindMember("avgPx");
|
||||
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
|
||||
auto it1Str = std::string(it1->value.GetString());
|
||||
auto it2Str = std::string(it2->value.GetString());
|
||||
if (!it1Str.empty() && !it2Str.empty()) {
|
||||
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<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("login").Move(), allocator);
|
||||
rj::Value arg(rj::kObjectType);
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
|
||||
std::string ts = std::to_string(std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count());
|
||||
arg.AddMember("apiKey", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("passphrase", rj::Value(apiPassphrase.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("timestamp", rj::Value(ts.c_str(), allocator).Move(), allocator);
|
||||
std::string signData = ts + "GET" + "/user/verify";
|
||||
std::string sign = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, signData));
|
||||
arg.AddMember("sign", rj::Value(sign.c_str(), allocator).Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
args.PushBack(arg, allocator);
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
if (textMessage != "pong") {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
auto it = document.FindMember("event");
|
||||
std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : "";
|
||||
if (eventStr == "login") {
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
auto& allocator = document.GetAllocator();
|
||||
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
for (const auto& field : fieldSet) {
|
||||
std::string channel;
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
channel = "orders";
|
||||
}
|
||||
for (const auto& instrument : instrumentSet) {
|
||||
rj::Value arg(rj::kObjectType);
|
||||
arg.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("instId", rj::Value(instrument.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("instType", rj::Value("spbl").Move(), allocator);
|
||||
args.PushBack(arg, allocator);
|
||||
}
|
||||
}
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBufferSubscribe;
|
||||
rj::Writer<rj::StringBuffer> writerSubscribe(stringBufferSubscribe);
|
||||
document.Accept(writerSubscribe);
|
||||
std::string sendString = stringBufferSubscribe.GetString();
|
||||
ErrorCode ec;
|
||||
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
} else {
|
||||
Event event = this->createEvent(subscription, textMessage, document, eventStr, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const std::string& eventStr,
|
||||
const TimePoint& timeReceived) {
|
||||
Event event;
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
const auto& correlationId = subscription.getCorrelationId();
|
||||
message.setCorrelationIdList({correlationId});
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
if (eventStr.empty()) {
|
||||
const rj::Value& arg = document["arg"];
|
||||
std::string channel = std::string(arg["channel"].GetString());
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
std::string instrument = arg["instId"].GetString();
|
||||
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
if (channel == "orders") {
|
||||
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
const rj::Value& data = document["data"];
|
||||
for (const auto& x : data.GetArray()) {
|
||||
auto itTradeId = x.FindMember("tradeId");
|
||||
std::string tradeId = itTradeId != x.MemberEnd() ? itTradeId->value.GetString() : "";
|
||||
if (!tradeId.empty()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString()))));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
std::vector<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_IS_MAKER, std::string(x["execType"].GetString()) == "M" ? "1" : "0");
|
||||
element.insert(CCAPI_EM_ORDER_ID, std::string(x["ordId"].GetString()));
|
||||
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdId"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fillFee"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCcy"].GetString()));
|
||||
elementList.emplace_back(std::move(element));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
|
||||
const rj::Value& data = document["data"];
|
||||
for (const auto& x : data.GetArray()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString()))));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
const std::map<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_STATUS, std::make_pair("status", JsonDataType::STRING)},
|
||||
};
|
||||
Element info;
|
||||
this->extractOrderInfo(info, x, extractionFieldNameMap);
|
||||
info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
std::vector<Element> elementList;
|
||||
elementList.emplace_back(std::move(info));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (eventStr == "subscribe") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
Element element;
|
||||
element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (eventStr == "error") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
event.setMessageList(messageList);
|
||||
return event;
|
||||
}
|
||||
std::string getAllOpenOrdersTarget, getAccountAllPositionsTarget;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITGET_FUTURES_H_
|
||||
@@ -0,0 +1,481 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITMART_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITMART_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_BITMART
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceBitmart : public ExecutionManagementService {
|
||||
public:
|
||||
ExecutionManagementServiceBitmart(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BITMART;
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/user?protocol=1.1";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BITMART_API_KEY;
|
||||
this->apiSecretName = CCAPI_BITMART_API_SECRET;
|
||||
this->apiMemoName = CCAPI_BITMART_API_MEMO;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiMemoName});
|
||||
this->createOrderTarget = "/spot/v2/submit_order";
|
||||
this->cancelOrderTarget = "/spot/v3/cancel_order";
|
||||
this->getOrderTarget = "/spot/v2/order_detail";
|
||||
this->getOpenOrdersTarget = "/spot/v3/orders";
|
||||
this->cancelOpenOrdersTarget = "/spot/v1/cancel_orders";
|
||||
this->getAccountBalancesTarget = "/spot/v1/wallet";
|
||||
this->needDecompressWebsocketMessage = true;
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
ErrorCode ec = this->inflater.init(false);
|
||||
#else
|
||||
ErrorCode ec = this->inflater.init();
|
||||
#endif
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_FATAL(ec.message());
|
||||
}
|
||||
}
|
||||
virtual ~ExecutionManagementServiceBitmart() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
private:
|
||||
#endif
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*1000")); }
|
||||
void signReqeustForRestGenericPrivateRequest(http::request<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 apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto preSignedText = req.base().at("X-BM-TIMESTAMP").to_string();
|
||||
preSignedText += "#";
|
||||
preSignedText += mapGetWithDefault(credential, this->apiMemoName);
|
||||
preSignedText += "#";
|
||||
std::string paramString;
|
||||
if (methodString == "GET" || methodString == "DELETE") {
|
||||
paramString = queryString;
|
||||
} else if (methodString == "POST" || methodString == "PUT") {
|
||||
paramString = body;
|
||||
}
|
||||
preSignedText += paramString;
|
||||
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
|
||||
if (!headerString.empty()) {
|
||||
headerString += "\r\n";
|
||||
}
|
||||
headerString += "X-BM-SIGN:" + signature;
|
||||
}
|
||||
void signRequest(http::request<http::string_body>& req, const std::string& paramString, const std::map<std::string, std::string>& credential) {
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto preSignedText = req.base().at("X-BM-TIMESTAMP").to_string();
|
||||
preSignedText += "#";
|
||||
preSignedText += mapGetWithDefault(credential, this->apiMemoName);
|
||||
preSignedText += "#";
|
||||
preSignedText += paramString;
|
||||
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
|
||||
req.set("X-BM-SIGN", signature);
|
||||
}
|
||||
void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {
|
||||
{CCAPI_EM_ORDER_SIDE, "side"},
|
||||
{CCAPI_EM_ORDER_QUANTITY, "size"},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "client_order_id"},
|
||||
{CCAPI_SYMBOL_ID, "symbol"},
|
||||
{CCAPI_EM_ORDER_ID, "order_id"},
|
||||
}) {
|
||||
for (const auto& kv : param) {
|
||||
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
auto value = kv.second;
|
||||
if (key == "side") {
|
||||
value = (value == CCAPI_EM_ORDER_SIDE_BUY || value == "buy") ? "buy" : "sell";
|
||||
}
|
||||
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
}
|
||||
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {
|
||||
{CCAPI_EM_ORDER_ID, "order_id"},
|
||||
{CCAPI_LIMIT, "N"},
|
||||
}) {
|
||||
for (const auto& kv : param) {
|
||||
queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
queryString += "=";
|
||||
queryString += Url::urlEncode(kv.second);
|
||||
queryString += "&";
|
||||
}
|
||||
}
|
||||
void appendSymbolId(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
|
||||
rjValue.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
void appendSymbolId(std::string& queryString, const std::string& symbolId) {
|
||||
queryString += "symbol=";
|
||||
queryString += Url::urlEncode(symbolId);
|
||||
queryString += "&";
|
||||
}
|
||||
void convertRequestForRest(http::request<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("X-BM-KEY", apiKey);
|
||||
req.set("X-BM-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
|
||||
Request::Operation operation = request.getOperation();
|
||||
switch (operation) {
|
||||
case Request::Operation::GENERIC_PRIVATE_REQUEST: {
|
||||
ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential);
|
||||
} break;
|
||||
case Request::Operation::CREATE_ORDER: {
|
||||
req.method(http::verb::post);
|
||||
req.target(this->createOrderTarget);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (param.find("type") == param.end()) {
|
||||
document.AddMember("type", rj::Value("limit").Move(), allocator);
|
||||
}
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
}
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
req.body() = body;
|
||||
req.prepare_payload();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_ORDER: {
|
||||
req.method(http::verb::post);
|
||||
req.target(this->cancelOrderTarget);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
}
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
req.body() = body;
|
||||
req.prepare_payload();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ORDER: {
|
||||
req.method(http::verb::get);
|
||||
std::string queryString;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param);
|
||||
if (queryString.back() == '&') {
|
||||
queryString.pop_back();
|
||||
}
|
||||
req.target(this->getOrderTarget + "?" + queryString);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_OPEN_ORDERS: {
|
||||
req.method(http::verb::get);
|
||||
std::string queryString;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
}
|
||||
queryString += "&status=9";
|
||||
if (queryString.back() == '&') {
|
||||
queryString.pop_back();
|
||||
}
|
||||
req.target(queryString.empty() ? this->getOpenOrdersTarget : this->getOpenOrdersTarget + "?" + queryString);
|
||||
this->signRequest(req, queryString, credential);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_OPEN_ORDERS: {
|
||||
req.method(http::verb::post);
|
||||
req.target(this->cancelOpenOrdersTarget);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
}
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
req.body() = body;
|
||||
req.prepare_payload();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_BALANCES: {
|
||||
req.method(http::verb::get);
|
||||
req.target(this->getAccountBalancesTarget);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
void extractOrderInfoFromRequest(std::vector<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 = {
|
||||
{CCAPI_EM_ORDER_ID, std::make_pair("order_id", JsonDataType::STRING)},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filled_size", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("filled_notional", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}};
|
||||
const rj::Value& data = document["data"];
|
||||
if (operation == Request::Operation::GET_OPEN_ORDERS) {
|
||||
for (const auto& x : data["orders"].GetArray()) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else if (operation == Request::Operation::CANCEL_OPEN_ORDERS) {
|
||||
} else {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, data, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
}
|
||||
void extractAccountInfoFromRequest(std::vector<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["data"]["wallet"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ASSET, x["id"].GetString());
|
||||
std::string available = x["available"].GetString();
|
||||
std::string frozen = x["frozen"].GetString();
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, available);
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, (Decimal(available).add(Decimal(frozen))).toString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} break;
|
||||
default:
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
std::vector<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("login").Move(), allocator);
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
auto timestamp = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count());
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
std::string preSignedText = timestamp + "#" + mapGetWithDefault(credential, this->apiMemoName) + "#bitmart.WebSocket";
|
||||
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
|
||||
rj::Value args(rj::kArrayType);
|
||||
args.PushBack(rj::Value(apiKey.c_str(), allocator).Move(), allocator);
|
||||
args.PushBack(rj::Value(timestamp.c_str(), allocator).Move(), allocator);
|
||||
args.PushBack(rj::Value(signature.c_str(), allocator).Move(), allocator);
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
if (textMessage != "pong") {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
auto it = document.FindMember("errorCode");
|
||||
std::string errorCode = it != document.MemberEnd() ? it->value.GetString() : "";
|
||||
Event event;
|
||||
const auto& correlationId = subscription.getCorrelationId();
|
||||
if (errorCode.empty()) {
|
||||
auto it = document.FindMember("event");
|
||||
std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : "";
|
||||
if (eventStr == "login") {
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
auto& allocator = document.GetAllocator();
|
||||
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
for (const auto& instrument : instrumentSet) {
|
||||
std::string arg = "spot/user/order:" + instrument;
|
||||
args.PushBack(rj::Value(arg.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBufferSubscribe;
|
||||
rj::Writer<rj::StringBuffer> writerSubscribe(stringBufferSubscribe);
|
||||
document.Accept(writerSubscribe);
|
||||
std::string sendString = stringBufferSubscribe.GetString();
|
||||
ErrorCode ec;
|
||||
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
// else {
|
||||
// this->serviceContextPtr->tlsClientPtr->set_timer(1000,
|
||||
// [wsConnection,correlationId,sendString,that=this](ErrorCode const& ec) {
|
||||
// auto timeReceived=UtilTime::now();
|
||||
// if (ec) {
|
||||
// that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
|
||||
// } else {
|
||||
// if (!that->subscriptionFailedByConnectionIdCorrelationIdMap[wsConnection.id][correlationId]){
|
||||
// Event event;
|
||||
// event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
// std::vector<Message> messageList;
|
||||
// Message message;
|
||||
// message.setTimeReceived(timeReceived);
|
||||
// message.setCorrelationIdList({correlationId});
|
||||
// message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
// Element element;
|
||||
// element.insert(CCAPI_INFO_MESSAGE, sendString);
|
||||
// message.setElementList({element});
|
||||
// messageList.emplace_back(std::move(message));
|
||||
// event.addMessages(messageList);
|
||||
// that->eventHandler(event, nullptr);
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
} else {
|
||||
event = this->createEvent(subscription, textMessage, document, eventStr, timeReceived);
|
||||
}
|
||||
} else {
|
||||
std::string eventStr = document["event"].GetString();
|
||||
if (eventStr.rfind("spot/user/order:", 0) == 0) {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
message.setCorrelationIdList({correlationId});
|
||||
messageList.emplace_back(std::move(message));
|
||||
event.setMessageList(messageList);
|
||||
// this->subscriptionFailedByConnectionIdCorrelationIdMap[wsConnection.id][correlationId] = true;
|
||||
}
|
||||
}
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const std::string& eventStr,
|
||||
const TimePoint& timeReceived) {
|
||||
Event event;
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
const auto& correlationId = subscription.getCorrelationId();
|
||||
message.setCorrelationIdList({correlationId});
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const rj::Value& data = document["data"];
|
||||
if (data.IsString() && std::string(data.GetString()).empty() || data.IsArray() && data.GetArray().Empty()) {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
Element element;
|
||||
element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else {
|
||||
std::string table = std::string(document["table"].GetString());
|
||||
if (table == "spot/user/order") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
for (const auto& x : data.GetArray()) {
|
||||
std::string instrument = x["symbol"].GetString();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
const auto& itDetailId = x.FindMember("detail_id");
|
||||
if (itDetailId != x.MemberEnd() && !itDetailId->value.IsNull()) {
|
||||
std::string tradeId = itDetailId->value.GetString();
|
||||
if (!tradeId.empty()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["last_fill_time"].GetString()))));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
std::vector<Element> elementList;
|
||||
Element element;
|
||||
element.insert(CCAPI_TRADE_ID, tradeId);
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["last_fill_price"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["last_fill_count"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
|
||||
element.insert(CCAPI_IS_MAKER, std::string(x["exec_type"].GetString()) == "M" ? "1" : "0");
|
||||
element.insert(CCAPI_EM_ORDER_ID, std::string(x["order_id"].GetString()));
|
||||
const auto& itClientOrderId = x.FindMember("client_order_id");
|
||||
if (itClientOrderId != x.MemberEnd() && !itClientOrderId->value.IsNull()) {
|
||||
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(itClientOrderId->value.GetString()));
|
||||
}
|
||||
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["dealFee"].GetString()));
|
||||
elementList.emplace_back(std::move(element));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["ms_t"].GetString()))));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
const std::map<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)},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filled_size", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("filled_notional", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)},
|
||||
};
|
||||
Element info;
|
||||
this->extractOrderInfo(info, x, extractionFieldNameMap);
|
||||
info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
std::vector<Element> elementList;
|
||||
elementList.emplace_back(std::move(info));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
event.setMessageList(messageList);
|
||||
return event;
|
||||
}
|
||||
// void onClose(wspp::connection_hdl hdl) override {
|
||||
// WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
// this->subscriptionFailedByConnectionIdCorrelationIdMap.erase(wsConnection.id);
|
||||
// ExecutionManagementService::onClose(hdl);
|
||||
// }
|
||||
std::string apiMemoName;
|
||||
// std::map<std::string, std::map<std::string, bool>> subscriptionFailedByConnectionIdCorrelationIdMap;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITMART_H_
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BITMEX;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/realtime";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/realtime";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BITMEX_API_KEY;
|
||||
this->apiSecretName = CCAPI_BITMEX_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -254,6 +263,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
|
||||
element.insert(CCAPI_EM_ASSET, x["currency"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_QUANTITY, x["currentQty"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_COST, x["openingCost"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgEntryPrice"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
@@ -301,9 +311,11 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
if (textMessage != "pong") {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(wsConnection.hdl, subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BITSTAMP;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BITSTAMP_API_KEY;
|
||||
this->apiSecretName = CCAPI_BITSTAMP_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -38,7 +47,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
|
||||
this->send(hdl, R"({"event": "bts:heartbeat"})", wspp::frame::opcode::text, ec);
|
||||
}
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override {
|
||||
bool doesHttpBodyContainError(const std::string& body) override {
|
||||
return body.find(R"("status": "error")") != std::string::npos || body.find(R"("status":"error")") != std::string::npos ||
|
||||
body.find(R"("error":)") != std::string::npos;
|
||||
}
|
||||
@@ -299,7 +308,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
|
||||
if (document.HasMember("token") && document.HasMember("user_id")) {
|
||||
std::string token = document["token"].GetString();
|
||||
std::string userId = document["user_id"].GetString();
|
||||
thisWsConnection.url = that->baseUrl;
|
||||
thisWsConnection.url = that->baseUrlWs;
|
||||
that->connect(thisWsConnection);
|
||||
that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({
|
||||
{"token", token},
|
||||
@@ -347,8 +356,10 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
|
||||
}
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
|
||||
@@ -1,162 +1,163 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_BASE_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_BASE_H_
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceBybit : public ExecutionManagementService {
|
||||
class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBase {
|
||||
public:
|
||||
ExecutionManagementServiceBybit(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
: ExecutionManagementServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/ws";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/private/v3";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BYBIT_API_KEY;
|
||||
this->apiSecretName = CCAPI_BYBIT_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
this->createOrderTarget = "/spot/v1/order";
|
||||
this->cancelOrderTarget = "/spot/v1/order/fast";
|
||||
this->getOrderTarget = "/spot/v1/order";
|
||||
this->getOpenOrdersTarget = "/spot/v1/open-orders";
|
||||
this->cancelOpenOrdersTarget = "/spot/v1/order/fast";
|
||||
this->getAccountBalancesTarget = "/spot/v1/account";
|
||||
this->createOrderTarget = "/spot/v3/private/order";
|
||||
this->cancelOrderTarget = "/spot/v3/private/cancel-order";
|
||||
this->getOrderTarget = "/spot/v3/private/order";
|
||||
this->getOpenOrdersTarget = "/spot/v3/private/open-orders";
|
||||
this->cancelOpenOrdersTarget = "/spot/v3/private/cancel-orders";
|
||||
this->getAccountBalancesTarget = "/spot/v3/private/account";
|
||||
}
|
||||
virtual ~ExecutionManagementServiceBybit() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
protected:
|
||||
#endif
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); }
|
||||
void signReqeustForRestGenericPrivateRequest(http::request<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 apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, queryString, true);
|
||||
queryString += "&signature=";
|
||||
queryString += signature;
|
||||
}
|
||||
void signRequest(std::string& queryString, const std::map<std::string, std::string>& param, const TimePoint& now,
|
||||
const std::map<std::string, std::string>& credential) {
|
||||
if (param.find("timestamp") == param.end()) {
|
||||
queryString += "timestamp=";
|
||||
queryString += std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count());
|
||||
queryString += "&";
|
||||
}
|
||||
if (queryString.back() == '&') {
|
||||
queryString.pop_back();
|
||||
}
|
||||
auto queryMap = Url::convertQueryStringToMap(queryString);
|
||||
auto queryString = Url::convertMapToQueryString(queryMap);
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, queryString, true);
|
||||
queryString += "&sign=";
|
||||
queryString += signature;
|
||||
}
|
||||
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {}) {
|
||||
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_CLIENT_ORDER_ID, "orderLinkId"},
|
||||
{CCAPI_EM_ORDER_ID, "orderId"},
|
||||
{CCAPI_LIMIT, "limit"},
|
||||
}) {
|
||||
for (const auto& kv : param) {
|
||||
queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
queryString += "=";
|
||||
queryString += Url::urlEncode(kv.second);
|
||||
queryString += "&";
|
||||
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
auto value = kv.second;
|
||||
if (key == "side") {
|
||||
value = value == CCAPI_EM_ORDER_SIDE_BUY ? "Buy" : "Sell";
|
||||
}
|
||||
if (value != "null") {
|
||||
if (key == "orderCategory") {
|
||||
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), std::stoi(value), allocator);
|
||||
} else {
|
||||
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void appendSymbolId(std::string& queryString, const std::string& symbolId) {
|
||||
queryString += "symbol=";
|
||||
queryString += Url::urlEncode(symbolId);
|
||||
queryString += "&";
|
||||
}
|
||||
void prepareReq(http::request<http::string_body>& req, const TimePoint& now, const std::map<std::string, std::string>& credential) {
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
req.set("api_key", apiKey);
|
||||
req.set("timestamp", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
|
||||
}
|
||||
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);
|
||||
this->prepareReq(req, now, credential);
|
||||
switch (request.getOperation()) {
|
||||
case Request::Operation::GENERIC_PRIVATE_REQUEST: {
|
||||
ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential);
|
||||
} break;
|
||||
case Request::Operation::CREATE_ORDER: {
|
||||
req.method(http::verb::post);
|
||||
std::string queryString;
|
||||
req.set(beast::http::field::content_type, "application/json");
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param,
|
||||
{
|
||||
{CCAPI_EM_ORDER_SIDE, "side"},
|
||||
{CCAPI_EM_ORDER_QUANTITY, "qty"},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"},
|
||||
});
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
if (param.find("type") == param.end()) {
|
||||
queryString += "type=LIMIT&";
|
||||
if (param.find("timeInForce") == param.end()) {
|
||||
queryString += "timeInForce=GTC&";
|
||||
}
|
||||
req.target(this->createOrderTarget);
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(document, allocator, param);
|
||||
if (param.find("orderType") == param.end()) {
|
||||
document.AddMember("orderType", rj::Value("LIMIT").Move(), allocator);
|
||||
}
|
||||
this->signRequest(queryString, param, now, credential);
|
||||
req.target(std::string(this->createOrderTarget));
|
||||
req.set(beast::http::field::content_type, "application/x-www-form-urlencoded; charset=utf-8");
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId, "symbol");
|
||||
}
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<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::delete_);
|
||||
std::string queryString;
|
||||
req.method(http::verb::post);
|
||||
req.set(beast::http::field::content_type, "application/json");
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param,
|
||||
{
|
||||
{CCAPI_EM_ORDER_ID, "orderId"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "origClientOrderId"},
|
||||
});
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
this->signRequest(queryString, param, now, credential);
|
||||
req.target(this->cancelOrderTarget + "?" + queryString);
|
||||
req.target(this->cancelOrderTarget);
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(document, allocator, param);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<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->appendParam(queryString, param,
|
||||
{
|
||||
{CCAPI_EM_ORDER_ID, "orderId"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "origClientOrderId"},
|
||||
});
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
this->signRequest(queryString, param, now, credential);
|
||||
this->appendParamToQueryString(queryString, param);
|
||||
req.target(this->getOrderTarget + "?" + queryString);
|
||||
this->signRequest(req, queryString, now, credential);
|
||||
} break;
|
||||
case Request::Operation::GET_OPEN_ORDERS: {
|
||||
req.method(http::verb::get);
|
||||
std::string queryString;
|
||||
this->appendParam(queryString, {});
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParamToQueryString(queryString, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
this->appendSymbolId(queryString, symbolId, "symbol");
|
||||
}
|
||||
this->signRequest(queryString, {}, now, credential);
|
||||
req.target(this->getOpenOrdersTarget + "?" + queryString);
|
||||
this->signRequest(req, queryString, now, credential);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_OPEN_ORDERS: {
|
||||
req.method(http::verb::delete_);
|
||||
std::string queryString;
|
||||
this->appendParam(queryString, {});
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
this->signRequest(queryString, {}, now, credential);
|
||||
req.target(this->cancelOpenOrdersTarget + "?" + queryString);
|
||||
req.method(http::verb::post);
|
||||
req.set(beast::http::field::content_type, "application/json");
|
||||
const std::map<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->appendParam(queryString, {});
|
||||
this->signRequest(queryString, {}, now, credential);
|
||||
req.target(this->getAccountBalancesTarget + "?" + queryString);
|
||||
this->appendParamToQueryString(queryString, {});
|
||||
req.target(this->getAccountBalancesTarget);
|
||||
this->signRequest(req, queryString, now, credential);
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
@@ -165,45 +166,37 @@ class ExecutionManagementServiceBybit : public ExecutionManagementService {
|
||||
void extractOrderInfoFromRequest(std::vector<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::INTEGER)},
|
||||
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("orderLinkId", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("origQty", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("executedQty", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair(this->isDerivatives ? "cumQuote" : "cummulativeQuoteQty", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("orderQty", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("orderPrice", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("execQty", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cummulativeQuoteQty", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
|
||||
};
|
||||
if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
|
||||
extractionFieldNameMap.insert({CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("origClientOrderId", JsonDataType::STRING)});
|
||||
} else {
|
||||
extractionFieldNameMap.insert({CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOrderId", JsonDataType::STRING)});
|
||||
}
|
||||
if (document.IsObject()) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, document, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
} else {
|
||||
for (const auto& x : document.GetArray()) {
|
||||
if (operation == Request::Operation::GET_OPEN_ORDERS) {
|
||||
for (const auto& x : document["result"]["list"].GetArray()) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else if (operation != Request::Operation::CANCEL_OPEN_ORDERS) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, document["result"], extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
}
|
||||
void extractAccountInfoFromRequest(std::vector<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[this->isDerivatives ? "assets" : "balances"].GetArray()) {
|
||||
for (const auto& x : document["result"]["balances"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ASSET, x["asset"].GetString());
|
||||
if (this->isDerivatives) {
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString());
|
||||
} else {
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(x["free"].GetString()).add(Decimal(x["locked"].GetString())).toString());
|
||||
}
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x[this->isDerivatives ? "availableBalance" : "free"].GetString());
|
||||
element.insert(CCAPI_EM_ASSET, x["coin"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["total"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["free"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} break;
|
||||
@@ -211,124 +204,8 @@ class ExecutionManagementServiceBybit : public ExecutionManagementService {
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
void prepareConnect(WsConnection& wsConnection) override {
|
||||
auto hostPort = this->extractHostFromUrl(this->baseUrlRest);
|
||||
std::string host = hostPort.first;
|
||||
std::string port = hostPort.second;
|
||||
http::request<http::string_body> req;
|
||||
req.set(http::field::host, host);
|
||||
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
|
||||
req.method(http::verb::post);
|
||||
std::string target = this->listenKeyTarget;
|
||||
if (this->listenKeyTarget == "/sapi/v1/userDataStream/isolated") {
|
||||
auto symbol = wsConnection.subscriptionList.at(0).getInstrument();
|
||||
target += "?" + symbol;
|
||||
}
|
||||
req.target(target);
|
||||
auto credential = wsConnection.subscriptionList.at(0).getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = this->credentialDefault;
|
||||
}
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
req.set("X-MBX-APIKEY", apiKey);
|
||||
this->sendRequest(
|
||||
req,
|
||||
[wsConnection, that = shared_from_base<ExecutionManagementServiceBybit>()](const beast::error_code& ec) {
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
that->onFail_(thisWsConnection);
|
||||
},
|
||||
[wsConnection, that = shared_from_base<ExecutionManagementServiceBybit>()](const http::response<http::string_body>& res) {
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
int statusCode = res.result_int();
|
||||
std::string body = res.body();
|
||||
if (statusCode / 100 == 2) {
|
||||
std::string urlWebsocketBase;
|
||||
try {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
|
||||
std::string listenKey = document["listenKey"].GetString();
|
||||
std::string url = that->baseUrl + "/" + listenKey;
|
||||
thisWsConnection.url = url;
|
||||
that->connect(thisWsConnection);
|
||||
that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({
|
||||
{"listenKey", listenKey},
|
||||
});
|
||||
return;
|
||||
} catch (const std::runtime_error& e) {
|
||||
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
}
|
||||
that->onFail_(thisWsConnection);
|
||||
},
|
||||
this->sessionOptions.httpRequestTimeoutMilliSeconds);
|
||||
}
|
||||
void onOpen(wspp::connection_hdl hdl) override {
|
||||
ExecutionManagementService::onOpen(hdl);
|
||||
auto now = UtilTime::now();
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
Event event;
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
Message message;
|
||||
message.setTimeReceived(now);
|
||||
message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
event.setMessageList({message});
|
||||
this->eventHandler(event, nullptr);
|
||||
this->pingListenKeyTimerMapByConnectionIdMap[wsConnection.id] = this->serviceContextPtr->tlsClientPtr->set_timer(
|
||||
this->pingListenKeyIntervalSeconds * 1000, [wsConnection, that = shared_from_base<ExecutionManagementServiceBybit>()](ErrorCode const& ec) {
|
||||
http::request<http::string_body> req;
|
||||
req.set(http::field::host, that->hostRest);
|
||||
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
|
||||
req.method(http::verb::put);
|
||||
std::string target = that->listenKeyTarget;
|
||||
if (!that->isDerivatives) {
|
||||
std::map<std::string, std::string> params;
|
||||
auto listenKey = that->extraPropertyByConnectionIdMap.at(wsConnection.id).at("listenKey");
|
||||
params.insert({"listenKey", listenKey});
|
||||
if (that->listenKeyTarget == "/sapi/v1/userDataStream/isolated") {
|
||||
auto symbol = wsConnection.subscriptionList.at(0).getInstrument();
|
||||
params.insert({"symbol", symbol});
|
||||
}
|
||||
target += "?";
|
||||
for (const auto& param : params) {
|
||||
target += param.first + "=" + Url::urlEncode(param.second);
|
||||
target += "&";
|
||||
}
|
||||
}
|
||||
req.target(target);
|
||||
auto credential = wsConnection.subscriptionList.at(0).getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = that->credentialDefault;
|
||||
}
|
||||
auto apiKey = mapGetWithDefault(credential, that->apiKeyName);
|
||||
req.set("X-MBX-APIKEY", apiKey);
|
||||
that->sendRequest(
|
||||
req,
|
||||
[wsConnection, that_2 = that->shared_from_base<ExecutionManagementServiceBybit>()](const beast::error_code& ec) {
|
||||
CCAPI_LOGGER_ERROR("ping listen key fail");
|
||||
that_2->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping listen key");
|
||||
},
|
||||
[wsConnection, that_2 = that->shared_from_base<ExecutionManagementServiceBybit>()](const http::response<http::string_body>& res) {
|
||||
CCAPI_LOGGER_DEBUG("ping listen key success");
|
||||
},
|
||||
that->sessionOptions.httpRequestTimeoutMilliSeconds);
|
||||
});
|
||||
}
|
||||
void onClose(wspp::connection_hdl hdl) override {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
if (this->pingListenKeyTimerMapByConnectionIdMap.find(wsConnection.id) != this->pingListenKeyTimerMapByConnectionIdMap.end()) {
|
||||
this->pingListenKeyTimerMapByConnectionIdMap.at(wsConnection.id)->cancel();
|
||||
this->pingListenKeyTimerMapByConnectionIdMap.erase(wsConnection.id);
|
||||
}
|
||||
ExecutionManagementService::onClose(hdl);
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
const TimePoint& timeReceived) override {
|
||||
Event event = this->createEvent(subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
}
|
||||
Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const TimePoint& timeReceived) {
|
||||
Event createEvent(wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
const TimePoint& timeReceived) override {
|
||||
Event event;
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
@@ -336,77 +213,121 @@ class ExecutionManagementServiceBybit : public ExecutionManagementService {
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
std::string type = document["e"].GetString();
|
||||
if (type == (this->isDerivatives ? "ORDER_TRADE_UPDATE" : "executionReport")) {
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
const rj::Value& data = this->isDerivatives ? document["o"] : document;
|
||||
std::string executionType = data["x"].GetString();
|
||||
std::string instrument = data["s"].GetString();
|
||||
if (instrumentSet.empty() || instrumentSet.find(UtilString::toUpper(instrument)) != instrumentSet.end() ||
|
||||
instrumentSet.find(UtilString::toLower(instrument)) != instrumentSet.end()) {
|
||||
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll((this->isDerivatives ? document : data)["E"].GetString()))));
|
||||
if (executionType == "TRADE" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
std::vector<Element> elementList;
|
||||
Element element;
|
||||
element.insert(CCAPI_TRADE_ID, std::string(data["t"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(data["L"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(data["l"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_SIDE, std::string(data["S"].GetString()) == "BUY" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
|
||||
element.insert(CCAPI_IS_MAKER, data["m"].GetBool() ? "1" : "0");
|
||||
element.insert(CCAPI_EM_ORDER_ID, std::string(data["i"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
{
|
||||
auto it = data.FindMember("n");
|
||||
if (it != data.MemberEnd() && !it->value.IsNull()) {
|
||||
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(it->value.GetString()));
|
||||
if (document.HasMember("topic")) {
|
||||
std::string topic = document["topic"].GetString();
|
||||
if (topic == "order") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
const rj::Value& data = document["data"];
|
||||
for (const auto& x : data.GetArray()) {
|
||||
std::string instrument = x["s"].GetString();
|
||||
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
auto time = TimePoint(std::chrono::milliseconds(std::stoll(x["E"].GetString())));
|
||||
auto itTradeId = x.FindMember("t");
|
||||
if (itTradeId != x.MemberEnd() && !itTradeId->value.IsNull() && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(time);
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
std::vector<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_ORDER_INSTRUMENT, instrument);
|
||||
{
|
||||
auto it = x.FindMember("n");
|
||||
if (it != x.MemberEnd() && !it->value.IsNull()) {
|
||||
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(it->value.GetString()));
|
||||
}
|
||||
}
|
||||
{
|
||||
auto it = x.FindMember("N");
|
||||
if (it != x.MemberEnd() && !it->value.IsNull()) {
|
||||
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(it->value.GetString()));
|
||||
}
|
||||
}
|
||||
elementList.emplace_back(std::move(element));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(time);
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
|
||||
{CCAPI_EM_ORDER_ID, std::make_pair("i", JsonDataType::INTEGER)},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("c", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_SIDE, std::make_pair("S", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("p", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("q", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("z", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("Z", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_STATUS, std::make_pair("X", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("s", JsonDataType::STRING)},
|
||||
};
|
||||
Element info;
|
||||
this->extractOrderInfo(info, x, extractionFieldNameMap);
|
||||
std::vector<Element> elementList;
|
||||
elementList.emplace_back(std::move(info));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
{
|
||||
auto it = data.FindMember("N");
|
||||
if (it != data.MemberEnd() && !it->value.IsNull()) {
|
||||
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(it->value.GetString()));
|
||||
}
|
||||
}
|
||||
elementList.emplace_back(std::move(element));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
|
||||
{CCAPI_EM_ORDER_ID, std::make_pair("i", JsonDataType::INTEGER)},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("c", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_SIDE, std::make_pair("S", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("p", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("q", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("z", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("Z", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_STATUS, std::make_pair("X", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("s", JsonDataType::STRING)},
|
||||
};
|
||||
Element info;
|
||||
this->extractOrderInfo(info, data, extractionFieldNameMap);
|
||||
auto it = data.FindMember("ap");
|
||||
if (it != data.MemberEnd() && !it->value.IsNull()) {
|
||||
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
|
||||
std::to_string(std::stod(it->value.GetString()) * std::stod(data["z"].GetString())));
|
||||
}
|
||||
std::vector<Element> elementList;
|
||||
elementList.emplace_back(std::move(info));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
} else if (document.HasMember("op")) {
|
||||
std::string op = document["op"].GetString();
|
||||
if (op == "auth") {
|
||||
bool success = document["success"].GetBool();
|
||||
if (success) {
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
args.PushBack(rj::Value("order").Move(), allocator);
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
ErrorCode ec;
|
||||
this->send(hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
}
|
||||
} else if (op == "subscribe") {
|
||||
bool success = document["success"].GetBool();
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
} else if (document.HasMember("ret_code")) {
|
||||
std::string ret_code = document["ret_code"].GetString();
|
||||
if (ret_code != "0") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
event.setMessageList(messageList);
|
||||
return event;
|
||||
}
|
||||
bool isDerivatives{};
|
||||
std::string listenKeyTarget;
|
||||
int pingListenKeyIntervalSeconds;
|
||||
std::map<std::string, TimerPtr> pingListenKeyTimerMapByConnectionIdMap;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_BASE_H_
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_
|
||||
@@ -0,0 +1,118 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#if defined(CCAPI_ENABLE_EXCHANGE_BYBIT) || defined(CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES)
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceBybitBase : public ExecutionManagementService {
|
||||
public:
|
||||
ExecutionManagementServiceBybitBase(std::function<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; }
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, 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 = {}) {
|
||||
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;
|
||||
}
|
||||
virtual Event createEvent(wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
const TimePoint& timeReceived) {
|
||||
return {};
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(wsConnection.hdl, subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
}
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_
|
||||
+379
@@ -0,0 +1,379 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_DERIVATIVES_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_DERIVATIVES_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceBybitDerivatives : public ExecutionManagementServiceBybitBase {
|
||||
public:
|
||||
ExecutionManagementServiceBybitDerivatives(std::function<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);
|
||||
}
|
||||
}
|
||||
Event createEvent(wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
const TimePoint& timeReceived) override {
|
||||
Event event;
|
||||
std::vector<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;
|
||||
this->send(hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
}
|
||||
} else if (type == "COMMAND_RESP") {
|
||||
bool success = document["success"].GetBool();
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
} else if (document.HasMember("ret_code")) {
|
||||
std::string ret_code = document["ret_code"].GetString();
|
||||
if (ret_code != "0") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
event.setMessageList(messageList);
|
||||
return event;
|
||||
}
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_DERIVATIVES_H_
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService {
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_COINBASE;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_COINBASE_API_KEY;
|
||||
this->apiSecretName = CCAPI_COINBASE_API_SECRET;
|
||||
this->apiPassphraseName = CCAPI_COINBASE_API_PASSPHRASE;
|
||||
@@ -284,8 +293,20 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService {
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
const TimePoint& timeReceived) override {
|
||||
void onTextMessage(
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage
|
||||
#else
|
||||
std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView
|
||||
#endif
|
||||
,
|
||||
const TimePoint& timeReceived) override {
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
std::string textMessage(textMessageView);
|
||||
#endif
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_CRYPTOCOM;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/user";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/user";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_CRYPTOCOM_API_KEY;
|
||||
this->apiSecretName = CCAPI_CRYPTOCOM_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -322,8 +331,10 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
|
||||
sendStringList.push_back(body);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(wsConnection, subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
@@ -452,14 +463,12 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
|
||||
}
|
||||
}
|
||||
} else if (method == "public/heartbeat") {
|
||||
if (itCode == document.MemberEnd()) {
|
||||
std::string id = document["id"].GetString();
|
||||
std::string msg = R"({"id":)" + id + R"(,"method":"public/respond-heartbeat"})";
|
||||
ErrorCode ec;
|
||||
this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request");
|
||||
}
|
||||
std::string id = document["id"].GetString();
|
||||
std::string msg = R"({"id":)" + id + R"(,"method":"public/respond-heartbeat"})";
|
||||
ErrorCode ec;
|
||||
this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request");
|
||||
}
|
||||
} else if (method == "public/auth") {
|
||||
if (itCode != document.MemberEnd()) {
|
||||
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_DERIBIT;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/api/v2";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/api/v2";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->clientIdName = CCAPI_DERIBIT_CLIENT_ID;
|
||||
this->clientSecretName = CCAPI_DERIBIT_CLIENT_SECRET;
|
||||
this->setupCredential({this->clientIdName, this->clientSecretName});
|
||||
@@ -263,8 +272,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
|
||||
Element element;
|
||||
element.insert(CCAPI_INSTRUMENT, x["instrument_name"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_COST,
|
||||
std::to_string(std::stod(x["average_price"].GetString()) * std::stod(x["size"].GetString()) / std::stod(x["leverage"].GetString())));
|
||||
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["average_price"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
@@ -314,8 +322,10 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(wsConnection, subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
|
||||
@@ -11,13 +11,23 @@ class ExecutionManagementServiceErisx : public ExecutionManagementService {
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_ERISX;
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_ERISX_API_KEY;
|
||||
this->apiSecretName = CCAPI_ERISX_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -33,7 +43,7 @@ class ExecutionManagementServiceErisx : public ExecutionManagementService {
|
||||
|
||||
private:
|
||||
#endif
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override {
|
||||
bool doesHttpBodyContainError(const std::string& body) override {
|
||||
return body.find("\"ordStatus\":\"REJECTED\"") != std::string::npos ||
|
||||
body.find("\"message\":\"Rejected with reason NO RESTING ORDERS\"") != std::string::npos;
|
||||
}
|
||||
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceFtx : public ExecutionManagementServiceFtxBase {
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_FTX;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_FTX_API_KEY;
|
||||
this->apiSecretName = CCAPI_FTX_API_SECRET;
|
||||
this->apiSubaccountName = CCAPI_FTX_API_SUBACCOUNT;
|
||||
|
||||
@@ -133,12 +133,18 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
|
||||
case Request::Operation::CANCEL_ORDER: {
|
||||
req.method(http::verb::delete_);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
auto shouldUseOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end();
|
||||
bool shouldUseOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end();
|
||||
std::string id = param.find(CCAPI_EM_ORDER_ID) != param.end() ? param.at(CCAPI_EM_ORDER_ID)
|
||||
: param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? param.at(CCAPI_EM_CLIENT_ORDER_ID)
|
||||
: "";
|
||||
req.target(shouldUseOrderId ? this->cancelOrderTarget + "/" + id : this->cancelOrderTarget + "/by_client_id/" + id);
|
||||
this->signRequest(req, "", credential);
|
||||
std::string body;
|
||||
if (!shouldUseOrderId && !symbolId.empty()) {
|
||||
body = R"({"market":")";
|
||||
body += symbolId;
|
||||
body += R"("})";
|
||||
}
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ORDER: {
|
||||
req.method(http::verb::get);
|
||||
@@ -312,8 +318,10 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
|
||||
}
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceFtxUs : public ExecutionManagementServiceFtxBase
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_FTX_US;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_FTX_US_API_KEY;
|
||||
this->apiSecretName = CCAPI_FTX_US_API_SECRET;
|
||||
this->apiSubaccountName = CCAPI_FTX_US_API_SUBACCOUNT;
|
||||
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceGateio : public ExecutionManagementServiceGateio
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v4/";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v4/";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_GATEIO_API_KEY;
|
||||
this->apiSecretName = CCAPI_GATEIO_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
|
||||
@@ -14,6 +14,12 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService {
|
||||
|
||||
protected:
|
||||
#endif
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
|
||||
auto now = UtilTime::now();
|
||||
this->send(hdl,
|
||||
"{\"time\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"channel\":\"" + (this->isDerivatives ? "futures" : "spot") + ".ping\"}",
|
||||
wspp::frame::opcode::text, ec);
|
||||
}
|
||||
void signReqeustForRestGenericPrivateRequest(http::request<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 {
|
||||
@@ -128,6 +134,7 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService {
|
||||
ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential);
|
||||
} break;
|
||||
case Request::Operation::CREATE_ORDER: {
|
||||
req.set("X-Gate-Channel-Id", CCAPI_GATEIO_API_CHANNEL_ID);
|
||||
req.method(http::verb::post);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Document document;
|
||||
@@ -257,6 +264,8 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ASSET, x["currency"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["available"].GetString());
|
||||
float total = std::stof(x["locked"].GetString()) + std::stof(x["available"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, std::to_string(total));
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} break;
|
||||
@@ -334,8 +343,10 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService {
|
||||
}
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
|
||||
+16
-3
@@ -10,14 +10,23 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem
|
||||
SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v4/ws/";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v4/ws/";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY;
|
||||
this->apiSecretName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -75,7 +84,7 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem
|
||||
}
|
||||
void subscribe(std::vector<Subscription>& subscriptionList) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
CCAPI_LOGGER_DEBUG("this->baseUrl = " + this->baseUrl);
|
||||
CCAPI_LOGGER_DEBUG("this->baseUrlWs = " + this->baseUrlWs);
|
||||
if (this->shouldContinue.load()) {
|
||||
for (auto& subscription : subscriptionList) {
|
||||
wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(),
|
||||
@@ -92,7 +101,11 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem
|
||||
} else if (UtilString::endsWith(symbolId, "_USDT")) {
|
||||
settle = "usdt";
|
||||
}
|
||||
WsConnection wsConnection(that->baseUrl + settle, "", {subscription});
|
||||
auto credential = subscription.getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = that->credentialDefault;
|
||||
}
|
||||
WsConnection wsConnection(that->baseUrlWs + settle, "", {subscription}, credential);
|
||||
that->prepareConnect(wsConnection);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_GEMINI;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v1/order/events";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v1/order/events";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_GEMINI_API_KEY;
|
||||
this->apiSecretName = CCAPI_GEMINI_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -294,8 +303,10 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
|
||||
wsConnection.headers.insert({"X-GEMINI-SIGNATURE", signature});
|
||||
this->connect(wsConnection);
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
|
||||
@@ -10,14 +10,23 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceHuobiBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v2";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v2";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_HUOBI_API_KEY;
|
||||
this->apiSecretName = CCAPI_HUOBI_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -36,7 +45,7 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
|
||||
|
||||
private:
|
||||
#endif
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find("err-code") != std::string::npos; }
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return body.find("err-code") != std::string::npos; }
|
||||
void appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
|
||||
ExecutionManagementServiceHuobiBase::appendSymbolId(document, allocator, symbolId, "symbol");
|
||||
}
|
||||
@@ -183,6 +192,10 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
|
||||
} else if (data.IsObject()) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, data, extractionFieldNameMap);
|
||||
if (operation == Request::Operation::GET_ORDER) {
|
||||
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::string(data["field-amount"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::string(data["field-cash-amount"].GetString()));
|
||||
}
|
||||
elementList.emplace_back(std::move(element));
|
||||
} else {
|
||||
for (const auto& x : data.GetArray()) {
|
||||
@@ -252,8 +265,10 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
std::string actionStr = document["action"].GetString();
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
@@ -275,9 +290,9 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
|
||||
auto& allocator = document.GetAllocator();
|
||||
document.AddMember("action", rj::Value("sub").Move(), allocator);
|
||||
std::string ch;
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
|
||||
if (field == CCAPI_EM_ORDER_UPDATE) {
|
||||
ch = "orders#" + symbol;
|
||||
} else if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
} else if (field == CCAPI_EM_PRIVATE_TRADE) {
|
||||
ch = "trade.clearing#" + symbol;
|
||||
}
|
||||
document.AddMember("ch", rj::Value(ch.c_str(), allocator).Move(), allocator);
|
||||
@@ -359,6 +374,11 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
|
||||
std::string dataEventType = data["eventType"].GetString();
|
||||
if (dataEventType == "trigger" || dataEventType == "deletion") {
|
||||
info.insert(CCAPI_EM_ORDER_SIDE, std::string(data["orderSide"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
|
||||
} else if (dataEventType == "trade") {
|
||||
info.insert(CCAPI_TRADE_ID, std::string(data["tradeId"].GetString()));
|
||||
info.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data["tradePrice"].GetString());
|
||||
info.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, data["tradeVolume"].GetString());
|
||||
info.insert(CCAPI_IS_MAKER, data["aggressor"].GetBool() ? "0" : "1");
|
||||
}
|
||||
std::vector<Element> elementList;
|
||||
elementList.emplace_back(std::move(info));
|
||||
|
||||
@@ -14,10 +14,6 @@ class ExecutionManagementServiceHuobiBase : public ExecutionManagementService {
|
||||
|
||||
protected:
|
||||
#endif
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
|
||||
auto now = UtilTime::now();
|
||||
this->send(hdl, "{\"ping\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + "}", wspp::frame::opcode::text, ec);
|
||||
}
|
||||
void createSignature(std::string& signature, std::string& queryString, const std::string& reqMethod, const std::string& host, const std::string& path,
|
||||
const std::map<std::string, std::string>& queryParamMap, const std::map<std::string, std::string>& credential) {
|
||||
std::string preSignedText;
|
||||
@@ -51,6 +47,12 @@ class ExecutionManagementServiceHuobiBase : public ExecutionManagementService {
|
||||
queryParamMap.insert(std::make_pair(y.at(0), y.at(1)));
|
||||
}
|
||||
}
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
queryParamMap.insert(std::make_pair("AccessKeyId", apiKey));
|
||||
queryParamMap.insert(std::make_pair("SignatureMethod", "HmacSHA256"));
|
||||
queryParamMap.insert(std::make_pair("SignatureVersion", "2"));
|
||||
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now, "%FT%T");
|
||||
queryParamMap.insert(std::make_pair("Timestamp", Url::urlEncode(timestamp)));
|
||||
std::string signature;
|
||||
this->createSignature(signature, queryString, methodString, this->hostRest, path, queryParamMap, credential);
|
||||
if (!queryString.empty()) {
|
||||
|
||||
+10
-1
@@ -10,14 +10,23 @@ class ExecutionManagementServiceHuobiCoinSwap : public ExecutionManagementServic
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceHuobiDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/swap-notification";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/swap-notification";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_HUOBI_COIN_SWAP_API_KEY;
|
||||
this->apiSecretName = CCAPI_HUOBI_COIN_SWAP_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
|
||||
+12
-4
@@ -23,7 +23,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
|
||||
|
||||
protected:
|
||||
#endif
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find("err_code") != std::string::npos; }
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return body.find("err_code") != std::string::npos; }
|
||||
void appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
|
||||
ExecutionManagementServiceHuobiBase::appendSymbolId(document, allocator, symbolId, "contract_code");
|
||||
}
|
||||
@@ -239,8 +239,10 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
std::string op = document["op"].GetString();
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
@@ -254,9 +256,9 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
|
||||
auto& allocator = document.GetAllocator();
|
||||
document.AddMember("op", rj::Value("sub").Move(), allocator);
|
||||
std::string topic;
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
|
||||
if (field == CCAPI_EM_ORDER_UPDATE) {
|
||||
topic = this->orderDataTopic + "." + instrument;
|
||||
} else if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
} else if (field == CCAPI_EM_PRIVATE_TRADE) {
|
||||
topic = this->matchOrderDataTopic + "." + instrument;
|
||||
}
|
||||
document.AddMember("topic", rj::Value(topic.c_str(), allocator).Move(), allocator);
|
||||
@@ -333,6 +335,12 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
|
||||
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
|
||||
}
|
||||
}
|
||||
for (const auto& x : document["trade"].GetArray()) {
|
||||
info.insert(CCAPI_TRADE_ID, std::string(x["trade_id"].GetString()));
|
||||
info.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, x["trade_price"].GetString());
|
||||
info.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, x["trade_volume"].GetString());
|
||||
info.insert(CCAPI_IS_MAKER, std::string(x["role"].GetString()) == "maker" ? "1" : "0");
|
||||
}
|
||||
std::vector<Element> elementList;
|
||||
elementList.emplace_back(std::move(info));
|
||||
message.setElementList(elementList);
|
||||
|
||||
+10
-1
@@ -10,14 +10,23 @@ class ExecutionManagementServiceHuobiUsdtSwap : public ExecutionManagementServic
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementServiceHuobiDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/linear-swap-notification";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/linear-swap-notification";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_HUOBI_USDT_SWAP_API_KEY;
|
||||
this->apiSecretName = CCAPI_HUOBI_USDT_SWAP_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
|
||||
@@ -11,14 +11,23 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN;
|
||||
this->baseUrl = CCAPI_KRAKEN_URL_WS_BASE_PRIVATE;
|
||||
this->baseUrlWs = CCAPI_KRAKEN_URL_WS_BASE_PRIVATE;
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_KRAKEN_API_KEY;
|
||||
this->apiSecretName = CCAPI_KRAKEN_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -41,7 +50,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
|
||||
auto now = UtilTime::now();
|
||||
this->send(hdl, "{\"reqid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec);
|
||||
}
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find(R"("error":[])") == std::string::npos; }
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("error":[])") == std::string::npos; }
|
||||
void signReqeustForRestGenericPrivateRequest(http::request<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 {
|
||||
@@ -294,7 +303,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();
|
||||
thisWsConnection.url = that->baseUrl;
|
||||
thisWsConnection.url = that->baseUrlWs;
|
||||
that->connect(thisWsConnection);
|
||||
that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({
|
||||
{"token", token},
|
||||
@@ -336,8 +345,10 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
|
||||
}
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
|
||||
+92
-66
@@ -11,14 +11,23 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v1";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v1";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_KRAKEN_FUTURES_API_KEY;
|
||||
this->apiSecretName = CCAPI_KRAKEN_FUTURES_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
@@ -42,7 +51,7 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
|
||||
|
||||
protected:
|
||||
#endif
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find(R"("result":"success")") == std::string::npos; }
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("result":"success")") == std::string::npos; }
|
||||
void signReqeustForRestGenericPrivateRequest(http::request<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 {
|
||||
@@ -240,8 +249,7 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_SIDE, x["side"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_COST,
|
||||
Decimal(UtilString::printDoubleScientific(std::stod(x["price"].GetString()) * std::stod(x["size"].GetString()))).toString());
|
||||
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["price"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} break;
|
||||
@@ -265,8 +273,10 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(wsConnection.hdl, subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
@@ -279,62 +289,64 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
|
||||
if (document.FindMember("event") == document.MemberEnd()) {
|
||||
if (document.FindMember("feed") != document.MemberEnd()) {
|
||||
std::string feed = document["feed"].GetString();
|
||||
std::string field;
|
||||
if (feed == "fills") {
|
||||
field = CCAPI_EM_PRIVATE_TRADE;
|
||||
} else if (feed == "open_orders") {
|
||||
field = CCAPI_EM_ORDER_UPDATE;
|
||||
}
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
if (fieldSet.find(field) != fieldSet.end()) {
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
if (field == CCAPI_EM_PRIVATE_TRADE) {
|
||||
for (const auto& x : document["fills"].GetArray()) {
|
||||
if (feed == "fills" || feed == "open_orders") {
|
||||
std::string field;
|
||||
if (feed == "fills") {
|
||||
field = CCAPI_EM_PRIVATE_TRADE;
|
||||
} else if (feed == "open_orders") {
|
||||
field = CCAPI_EM_ORDER_UPDATE;
|
||||
}
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
if (fieldSet.find(field) != fieldSet.end()) {
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
if (field == CCAPI_EM_PRIVATE_TRADE) {
|
||||
for (const auto& x : document["fills"].GetArray()) {
|
||||
std::string instrument = x["instrument"].GetString();
|
||||
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
Message message;
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString())));
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
std::vector<Element> elementList;
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, x["price"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, x["qty"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_SIDE, x["buy"].GetBool() ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
|
||||
element.insert(CCAPI_EM_ORDER_ID, std::string(x["order_id"].GetString()));
|
||||
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["cli_ord_id"].GetString()));
|
||||
element.insert(CCAPI_IS_MAKER, std::string(x["fill_type"].GetString()) == "maker" ? "1" : "0");
|
||||
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fee_paid"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fee_currency"].GetString()));
|
||||
elementList.emplace_back(std::move(element));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
} else if (field == CCAPI_EM_ORDER_UPDATE) {
|
||||
const rj::Value& x = document["order"];
|
||||
std::string instrument = x["instrument"].GetString();
|
||||
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
Message message;
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString())));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(x["last_update_time"].GetString())));
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
std::vector<Element> elementList;
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, x["price"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, x["qty"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_SIDE, x["buy"].GetBool() ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
|
||||
element.insert(CCAPI_EM_ORDER_ID, std::string(x["order_id"].GetString()));
|
||||
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["cli_ord_id"].GetString()));
|
||||
element.insert(CCAPI_IS_MAKER, std::string(x["fill_type"].GetString()) == "maker" ? "1" : "0");
|
||||
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fee_paid"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fee_currency"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_QUANTITY, x["qty"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, x["filled"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_LIMIT_PRICE, x["limit_price"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_ID, x["order_id"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["direction"].GetString()) == "0" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
|
||||
element.insert("is_cancel", document["is_cancel"].GetBool() ? "1" : "0");
|
||||
elementList.emplace_back(std::move(element));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
} else if (field == CCAPI_EM_ORDER_UPDATE) {
|
||||
const rj::Value& x = document["order"];
|
||||
std::string instrument = x["instrument"].GetString();
|
||||
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
Message message;
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(x["last_update_time"].GetString())));
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
std::vector<Element> elementList;
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
element.insert(CCAPI_EM_ORDER_QUANTITY, x["qty"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, x["filled"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_LIMIT_PRICE, x["limit_price"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_ID, x["order_id"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["direction"].GetString()) == "0" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
|
||||
element.insert("is_cancel", document["is_cancel"].GetBool() ? "1" : "0");
|
||||
elementList.emplace_back(std::move(element));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -352,25 +364,39 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
|
||||
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA512, UtilAlgorithm::base64Decode(apiSecret), challengeToSignSha256));
|
||||
std::vector<std::string> sendStringList;
|
||||
for (const auto& field : subscription.getFieldSet()) {
|
||||
std::string feed;
|
||||
if (field == CCAPI_EM_PRIVATE_TRADE) {
|
||||
feed = "fills";
|
||||
} else if (field == CCAPI_EM_ORDER_UPDATE) {
|
||||
feed = "open_orders";
|
||||
{
|
||||
std::string feed;
|
||||
if (field == CCAPI_EM_PRIVATE_TRADE) {
|
||||
feed = "fills";
|
||||
} else if (field == CCAPI_EM_ORDER_UPDATE) {
|
||||
feed = "open_orders";
|
||||
}
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
auto& allocator = document.GetAllocator();
|
||||
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
|
||||
document.AddMember("feed", rj::Value(feed.c_str(), allocator).Move(), allocator);
|
||||
document.AddMember("api_key", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
|
||||
document.AddMember("original_challenge", rj::Value(challengeToSign.c_str(), allocator).Move(), allocator);
|
||||
document.AddMember("signed_challenge", rj::Value(signature.c_str(), allocator).Move(), allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
}
|
||||
{
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
auto& allocator = document.GetAllocator();
|
||||
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
|
||||
document.AddMember("feed", rj::Value("heartbeat").Move(), allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
}
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
auto& allocator = document.GetAllocator();
|
||||
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
|
||||
document.AddMember("feed", rj::Value(feed.c_str(), allocator).Move(), allocator);
|
||||
document.AddMember("api_key", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
|
||||
document.AddMember("original_challenge", rj::Value(challengeToSign.c_str(), allocator).Move(), allocator);
|
||||
document.AddMember("signed_challenge", rj::Value(signature.c_str(), allocator).Move(), allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
}
|
||||
for (const auto& sendString : sendStringList) {
|
||||
ErrorCode ec;
|
||||
|
||||
@@ -2,15 +2,14 @@
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service_kucoin_base.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceKucoin : public ExecutionManagementService {
|
||||
class ExecutionManagementServiceKucoin : public ExecutionManagementServiceKucoinBase {
|
||||
public:
|
||||
ExecutionManagementServiceKucoin(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
: ExecutionManagementServiceKucoinBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
try {
|
||||
@@ -18,311 +17,34 @@ class ExecutionManagementServiceKucoin : public ExecutionManagementService {
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_KUCOIN_API_KEY;
|
||||
this->apiSecretName = CCAPI_KUCOIN_API_SECRET;
|
||||
this->apiPassphraseName = CCAPI_KUCOIN_API_PASSPHRASE;
|
||||
this->apiKeyVersionName = CCAPI_KUCOIN_API_KEY_VERSION;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName, this->apiKeyVersionName});
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
|
||||
this->createOrderTarget = "/api/v1/orders";
|
||||
this->cancelOrderTarget = "/api/v1/orders/<id>";
|
||||
this->getOrderTarget = "/api/v1/orders/<id>";
|
||||
this->getOrderByClientOrderIdTarget = "/api/v1/order/client-order/<id>";
|
||||
this->getOpenOrdersTarget = "/api/v1/orders";
|
||||
this->cancelOpenOrdersTarget = "/api/v1/orders";
|
||||
this->getAccountsTarget = "/api/v1/accounts";
|
||||
this->getAccountBalancesTarget = "/api/v1/accounts/<accountId>";
|
||||
this->topicTradeOrders = "/spotMarket/tradeOrders";
|
||||
this->createOrderMarginTarget = "/api/v1/margin/order";
|
||||
}
|
||||
virtual ~ExecutionManagementServiceKucoin() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
protected:
|
||||
#endif
|
||||
void onOpen(wspp::connection_hdl hdl) override {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
wsConnection.status = WsConnection::Status::OPEN;
|
||||
}
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override {
|
||||
return !std::regex_search(body, std::regex("\"code\":\\s*\"200000\""));
|
||||
}
|
||||
void prepareConnect(WsConnection& wsConnection) override {
|
||||
auto now = UtilTime::now();
|
||||
http::request<http::string_body> req;
|
||||
req.set(http::field::host, this->hostRest);
|
||||
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
|
||||
req.method(http::verb::post);
|
||||
req.target("/api/v1/bullet-private");
|
||||
auto credential = wsConnection.subscriptionList.at(0).getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = this->credentialDefault;
|
||||
}
|
||||
this->prepareReq(req, now, credential);
|
||||
this->signRequest(req, "", credential);
|
||||
this->sendRequest(
|
||||
req,
|
||||
[wsConnection, that = shared_from_base<ExecutionManagementServiceKucoin>()](const beast::error_code& ec) {
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
that->onFail_(thisWsConnection);
|
||||
},
|
||||
[wsConnection, that = shared_from_base<ExecutionManagementServiceKucoin>()](const http::response<http::string_body>& res) {
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
int statusCode = res.result_int();
|
||||
std::string body = res.body();
|
||||
if (statusCode / 100 == 2) {
|
||||
std::string urlWebsocketBase;
|
||||
try {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
|
||||
const rj::Value& instanceServer = document["data"]["instanceServers"][0];
|
||||
urlWebsocketBase += std::string(instanceServer["endpoint"].GetString());
|
||||
urlWebsocketBase += "?token=";
|
||||
urlWebsocketBase += std::string(document["data"]["token"].GetString());
|
||||
thisWsConnection.url = urlWebsocketBase;
|
||||
that->connect(thisWsConnection);
|
||||
that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({
|
||||
{"pingInterval", std::string(instanceServer["pingInterval"].GetString())},
|
||||
{"pingTimeout", std::string(instanceServer["pingTimeout"].GetString())},
|
||||
});
|
||||
return;
|
||||
} catch (const std::runtime_error& e) {
|
||||
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
}
|
||||
that->onFail_(thisWsConnection);
|
||||
},
|
||||
this->sessionOptions.httpRequestTimeoutMilliSeconds);
|
||||
}
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
|
||||
auto now = UtilTime::now();
|
||||
this->send(hdl, "{\"id\":\"" + std::to_string(UtilTime::getUnixTimestamp(now)) + "\",\"type\":\"ping\"}", wspp::frame::opcode::text, ec);
|
||||
}
|
||||
void signReqeustForRestGenericPrivateRequest(http::request<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 apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto preSignedText = req.base().at("KC-API-TIMESTAMP").to_string();
|
||||
preSignedText += methodString;
|
||||
auto target = path;
|
||||
if (!queryString.empty()) {
|
||||
target += queryString;
|
||||
}
|
||||
preSignedText += target;
|
||||
preSignedText += body;
|
||||
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText));
|
||||
if (!headerString.empty()) {
|
||||
headerString += "\r\n";
|
||||
}
|
||||
headerString += "KC-API-SIGN:" + signature;
|
||||
}
|
||||
void signRequest(http::request<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("KC-API-TIMESTAMP").to_string();
|
||||
preSignedText += std::string(req.method_string());
|
||||
preSignedText += req.target().to_string();
|
||||
preSignedText += body;
|
||||
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText));
|
||||
req.set("KC-API-SIGN", signature);
|
||||
req.body() = body;
|
||||
req.prepare_payload();
|
||||
}
|
||||
void signApiPassphrase(http::request<http::string_body>& req, const std::string& apiKeyVersion, const std::string& apiPassphrase,
|
||||
const std::string& apiSecret) {
|
||||
if (apiKeyVersion == "2") {
|
||||
req.set("KC-API-PASSPHRASE", UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, apiPassphrase)));
|
||||
} else {
|
||||
req.set("KC-API-PASSPHRASE", apiPassphrase);
|
||||
}
|
||||
}
|
||||
void appendParam(rj::Document& document, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {
|
||||
{CCAPI_EM_ORDER_SIDE, "side"},
|
||||
{CCAPI_EM_ORDER_QUANTITY, "size"},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "clientOid"},
|
||||
}) {
|
||||
for (const auto& kv : param) {
|
||||
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
auto value = kv.second;
|
||||
if (key == "side") {
|
||||
value = (value == CCAPI_EM_ORDER_SIDE_BUY || value == "buy") ? "buy" : "sell";
|
||||
}
|
||||
if (key == "cancelAfter") {
|
||||
document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(static_cast<int64_t>(std::stoll(value))), allocator);
|
||||
} else if (value == "true" || value == "false") {
|
||||
document.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator);
|
||||
} else {
|
||||
document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
}
|
||||
}
|
||||
void appendParam(std::string& queryString, const std::map<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(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
|
||||
document.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
void prepareReq(http::request<http::string_body>& req, const TimePoint& now, const std::map<std::string, std::string>& credential) {
|
||||
req.set(beast::http::field::content_type, "application/json");
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
req.set("KC-API-KEY", apiKey);
|
||||
req.set("KC-API-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
|
||||
auto apiKeyVersion = mapGetWithDefault(credential, this->apiKeyVersionName);
|
||||
req.set("KC-API-KEY-VERSION", apiKeyVersion);
|
||||
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
this->signApiPassphrase(req, apiKeyVersion, apiPassphrase, apiSecret);
|
||||
}
|
||||
void convertRequestForRest(http::request<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);
|
||||
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);
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_ORDER: {
|
||||
req.method(http::verb::delete_);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
bool useOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end();
|
||||
std::string id = useOrderId ? param.at(CCAPI_EM_ORDER_ID)
|
||||
: param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? "client-order/" + param.at(CCAPI_EM_CLIENT_ORDER_ID)
|
||||
: "";
|
||||
auto target =
|
||||
useOrderId ? std::regex_replace(this->cancelOrderTarget, std::regex("<id>"), id) : std::regex_replace("/api/v1/order/<id>", std::regex("<id>"), id);
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ORDER: {
|
||||
req.method(http::verb::get);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
bool useOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end();
|
||||
std::string id = useOrderId ? param.at(CCAPI_EM_ORDER_ID)
|
||||
: param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? "client-order/" + param.at(CCAPI_EM_CLIENT_ORDER_ID)
|
||||
: "";
|
||||
auto target =
|
||||
useOrderId ? std::regex_replace(this->getOrderTarget, std::regex("<id>"), id) : std::regex_replace("/api/v1/order/<id>", std::regex("<id>"), id);
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_OPEN_ORDERS: {
|
||||
req.method(http::verb::get);
|
||||
auto target = this->getOpenOrdersTarget;
|
||||
target += "?status=active";
|
||||
if (!symbolId.empty()) {
|
||||
target += "&symbol=";
|
||||
target += symbolId;
|
||||
}
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_OPEN_ORDERS: {
|
||||
req.method(http::verb::delete_);
|
||||
auto target = this->cancelOpenOrdersTarget;
|
||||
if (!symbolId.empty()) {
|
||||
target += "?symbol=";
|
||||
target += symbolId;
|
||||
}
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNTS: {
|
||||
req.method(http::verb::get);
|
||||
std::string target = this->getAccountsTarget;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
if (!param.empty()) {
|
||||
std::string queryString;
|
||||
this->appendParam(queryString, param,
|
||||
{
|
||||
{CCAPI_EM_ASSET, "currency"},
|
||||
{CCAPI_EM_ACCOUNT_TYPE, "type"},
|
||||
});
|
||||
target += "?" + queryString;
|
||||
}
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_BALANCES: {
|
||||
req.method(http::verb::get);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
auto target = this->getAccountBalancesTarget;
|
||||
auto accountId = param.find(CCAPI_EM_ACCOUNT_ID) != param.end() ? param.at(CCAPI_EM_ACCOUNT_ID) : "";
|
||||
this->substituteParam(target, {
|
||||
{"<accountId>", accountId},
|
||||
});
|
||||
req.target(target);
|
||||
this->signRequest(req, "", 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 {
|
||||
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)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}};
|
||||
const rj::Value& data = document["data"];
|
||||
if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
|
||||
if (data.FindMember("cancelledOrderIds") != data.MemberEnd()) {
|
||||
for (const auto& x : data["cancelledOrderIds"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ORDER_ID, x.GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ORDER_ID, data["cancelledOrderId"].GetString());
|
||||
element.insert(CCAPI_EM_CLIENT_ORDER_ID, data["clientOid"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else if (operation == Request::Operation::CREATE_ORDER) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ORDER_ID, data["orderId"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
} else if (operation == Request::Operation::GET_OPEN_ORDERS) {
|
||||
for (const auto& x : data["items"].GetArray()) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else if (operation == Request::Operation::GET_ORDER) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, data, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
}
|
||||
void extractOrderInfo(Element& element, const rj::Value& x,
|
||||
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
|
||||
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
{
|
||||
auto it = x.FindMember("isActive");
|
||||
if (it != x.MemberEnd()) {
|
||||
element.insert("isActive", it->value.GetBool() ? "true" : "false");
|
||||
}
|
||||
}
|
||||
}
|
||||
void extractAccountInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
|
||||
const rj::Document& document) override {
|
||||
const auto& data = document["data"];
|
||||
@@ -349,133 +71,6 @@ class ExecutionManagementServiceKucoin : public ExecutionManagementService {
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
|
||||
const std::map<std::string, std::string>& credential) override {
|
||||
std::string topic;
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
topic = "/spotMarket/tradeOrders";
|
||||
}
|
||||
std::vector<std::string> sendStringList;
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
static int nextRequestId = 1;
|
||||
std::string requestId = std::to_string(nextRequestId);
|
||||
nextRequestId += 1;
|
||||
document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator);
|
||||
document.AddMember("type", rj::Value("subscribe").Move(), allocator);
|
||||
document.AddMember("privateChannel", true, allocator);
|
||||
document.AddMember("response", true, allocator);
|
||||
document.AddMember("topic", rj::Value(topic.c_str(), allocator).Move(), allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
auto subscription = wsConnection.subscriptionList.at(0);
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(wsConnection, hdl, subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
}
|
||||
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
|
||||
const rj::Document& document, const TimePoint& timeReceived) {
|
||||
Event event;
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
std::string type = document["type"].GetString();
|
||||
if (type == "message") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
std::string topic = document["topic"].GetString();
|
||||
if (topic == "/spotMarket/tradeOrders") {
|
||||
const rj::Value& data = document["data"];
|
||||
std::string instrument = data["symbol"].GetString();
|
||||
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
std::string ts = std::string(data["ts"].GetString());
|
||||
message.setTime(UtilTime::makeTimePoint({std::stoll(ts.substr(0, ts.length() - 9)), std::stoll(ts.substr(ts.length() - 9))}));
|
||||
std::string dataType = data["type"].GetString();
|
||||
if (dataType == "match" && (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end() || fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end())) {
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
std::vector<Element> elementList;
|
||||
Element element;
|
||||
element.insert(CCAPI_TRADE_ID, data["tradeId"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data["matchPrice"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, data["matchSize"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_SIDE, std::string(data["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
|
||||
element.insert(CCAPI_IS_MAKER, std::string(data["liquidity"].GetString()) == "taker" ? "0" : "1");
|
||||
element.insert(CCAPI_EM_ORDER_ID, data["orderId"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
elementList.emplace_back(std::move(element));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
std::map<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("price", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filledSize", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("remainSize", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
|
||||
};
|
||||
extractionFieldNameMap.insert({CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)});
|
||||
Element info;
|
||||
this->extractOrderInfo(info, data, extractionFieldNameMap);
|
||||
std::vector<Element> elementList;
|
||||
elementList.emplace_back(std::move(info));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (type == "ack") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
Element element;
|
||||
element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (type == "error") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (type == "welcome") {
|
||||
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
|
||||
std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingInterval"));
|
||||
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
|
||||
std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingTimeout"));
|
||||
if (this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <=
|
||||
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) {
|
||||
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
|
||||
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1;
|
||||
}
|
||||
ExecutionManagementService::onOpen(hdl);
|
||||
} else if (type == "pong") {
|
||||
auto now = UtilTime::now();
|
||||
this->lastPongTpByMethodByConnectionIdMap[wsConnection.id][PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = now;
|
||||
}
|
||||
event.setMessageList(messageList);
|
||||
return event;
|
||||
}
|
||||
std::string apiPassphraseName;
|
||||
std::string apiKeyVersionName;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_BASE_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_BASE_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#if defined(CCAPI_ENABLE_EXCHANGE_KUCOIN) || defined(CCAPI_ENABLE_EXCHANGE_KUCOIN_FUTURES)
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
|
||||
public:
|
||||
ExecutionManagementServiceKucoinBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
|
||||
virtual ~ExecutionManagementServiceKucoinBase() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
protected:
|
||||
#endif
|
||||
void onOpen(wspp::connection_hdl hdl) override {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
wsConnection.status = WsConnection::Status::OPEN;
|
||||
}
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"200000\"")); }
|
||||
void prepareConnect(WsConnection& wsConnection) override {
|
||||
auto now = UtilTime::now();
|
||||
http::request<http::string_body> req;
|
||||
req.set(http::field::host, this->hostRest);
|
||||
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
|
||||
req.method(http::verb::post);
|
||||
req.target("/api/v1/bullet-private");
|
||||
auto credential = wsConnection.subscriptionList.at(0).getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = this->credentialDefault;
|
||||
}
|
||||
this->prepareReq(req, now, credential);
|
||||
this->signRequest(req, "", credential);
|
||||
this->sendRequest(
|
||||
req,
|
||||
[wsConnection, that = shared_from_base<ExecutionManagementServiceKucoinBase>()](const beast::error_code& ec) {
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
that->onFail_(thisWsConnection);
|
||||
},
|
||||
[wsConnection, that = shared_from_base<ExecutionManagementServiceKucoinBase>()](const http::response<http::string_body>& res) {
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
int statusCode = res.result_int();
|
||||
std::string body = res.body();
|
||||
if (statusCode / 100 == 2) {
|
||||
std::string urlWebsocketBase;
|
||||
try {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
|
||||
const rj::Value& instanceServer = document["data"]["instanceServers"][0];
|
||||
urlWebsocketBase += std::string(instanceServer["endpoint"].GetString());
|
||||
urlWebsocketBase += "?token=";
|
||||
urlWebsocketBase += std::string(document["data"]["token"].GetString());
|
||||
thisWsConnection.url = urlWebsocketBase;
|
||||
that->connect(thisWsConnection);
|
||||
that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({
|
||||
{"pingInterval", std::string(instanceServer["pingInterval"].GetString())},
|
||||
{"pingTimeout", std::string(instanceServer["pingTimeout"].GetString())},
|
||||
});
|
||||
return;
|
||||
} catch (const std::runtime_error& e) {
|
||||
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
}
|
||||
that->onFail_(thisWsConnection);
|
||||
},
|
||||
this->sessionOptions.httpRequestTimeoutMilliSeconds);
|
||||
}
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
|
||||
auto now = UtilTime::now();
|
||||
this->send(hdl, "{\"id\":\"" + std::to_string(UtilTime::getUnixTimestamp(now)) + "\",\"type\":\"ping\"}", wspp::frame::opcode::text, ec);
|
||||
}
|
||||
void signReqeustForRestGenericPrivateRequest(http::request<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 apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto preSignedText = req.base().at("KC-API-TIMESTAMP").to_string();
|
||||
preSignedText += methodString;
|
||||
auto target = path;
|
||||
if (!queryString.empty()) {
|
||||
target += queryString;
|
||||
}
|
||||
preSignedText += target;
|
||||
preSignedText += body;
|
||||
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText));
|
||||
if (!headerString.empty()) {
|
||||
headerString += "\r\n";
|
||||
}
|
||||
headerString += "KC-API-SIGN:" + signature;
|
||||
}
|
||||
void signRequestPartner(http::request<http::string_body>& req, const std::string& body, const std::map<std::string, std::string>& credential) {
|
||||
req.set("KC-API-PARTNER", CCAPI_KUCOIN_API_PARTNER_PLATFORM_ID);
|
||||
auto preSignedText = req.base().at("KC-API-TIMESTAMP").to_string();
|
||||
preSignedText += CCAPI_KUCOIN_API_PARTNER_PLATFORM_ID;
|
||||
preSignedText += req.base().at("KC-API-KEY").to_string();
|
||||
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, CCAPI_KUCOIN_API_PARTNER_PRIVATE_KEY, preSignedText));
|
||||
req.set("KC-API-PARTNER-SIGN", signature);
|
||||
}
|
||||
void signRequest(http::request<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("KC-API-TIMESTAMP").to_string();
|
||||
preSignedText += std::string(req.method_string());
|
||||
preSignedText += req.target().to_string();
|
||||
preSignedText += body;
|
||||
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText));
|
||||
req.set("KC-API-SIGN", signature);
|
||||
req.body() = body;
|
||||
req.prepare_payload();
|
||||
}
|
||||
void signApiPassphrase(http::request<http::string_body>& req, const std::string& apiPassphrase, const std::string& apiSecret) {
|
||||
req.set("KC-API-PASSPHRASE", UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, apiPassphrase)));
|
||||
}
|
||||
void appendParam(rj::Document& document, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {
|
||||
{CCAPI_EM_ORDER_SIDE, "side"},
|
||||
{CCAPI_EM_ORDER_QUANTITY, "size"},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "clientOid"},
|
||||
{CCAPI_EM_ORDER_LEVERAGE, "leverage"},
|
||||
}) {
|
||||
for (const auto& kv : param) {
|
||||
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
auto value = kv.second;
|
||||
if (key == "side") {
|
||||
value = (value == CCAPI_EM_ORDER_SIDE_BUY || value == "buy") ? "buy" : "sell";
|
||||
}
|
||||
if (key == "cancelAfter") {
|
||||
document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(static_cast<int64_t>(std::stoll(value))), allocator);
|
||||
} else if (value == "true" || value == "false") {
|
||||
document.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator);
|
||||
} else {
|
||||
document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
}
|
||||
}
|
||||
void appendParam(std::string& queryString, const std::map<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(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
|
||||
document.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
void prepareReq(http::request<http::string_body>& req, const TimePoint& now, const std::map<std::string, std::string>& credential) {
|
||||
req.set(beast::http::field::content_type, "application/json");
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
req.set("KC-API-KEY", apiKey);
|
||||
req.set("KC-API-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
|
||||
// auto apiKeyVersion = mapGetWithDefault(credential, this->apiKeyVersionName);
|
||||
req.set("KC-API-KEY-VERSION", "2");
|
||||
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
this->signApiPassphrase(req, apiPassphrase, apiSecret);
|
||||
}
|
||||
void convertRequestForRest(http::request<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);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
req.target(request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN
|
||||
? this->createOrderMarginTarget
|
||||
: this->createOrderTarget);
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(document, allocator, param);
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
this->signRequestPartner(req, body, credential);
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_ORDER: {
|
||||
req.method(http::verb::delete_);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
bool useOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end();
|
||||
std::string id = useOrderId ? param.at(CCAPI_EM_ORDER_ID)
|
||||
: param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? "client-order/" + param.at(CCAPI_EM_CLIENT_ORDER_ID)
|
||||
: "";
|
||||
auto target =
|
||||
useOrderId ? std::regex_replace(this->cancelOrderTarget, std::regex("<id>"), id) : std::regex_replace("/api/v1/order/<id>", std::regex("<id>"), id);
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ORDER: {
|
||||
req.method(http::verb::get);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
bool useOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end();
|
||||
std::string id = useOrderId ? param.at(CCAPI_EM_ORDER_ID)
|
||||
: param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? param.at(CCAPI_EM_CLIENT_ORDER_ID)
|
||||
: "";
|
||||
auto target = std::regex_replace(useOrderId ? this->getOrderTarget : this->getOrderByClientOrderIdTarget, std::regex("<id>"), Url::urlEncode(id));
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_OPEN_ORDERS: {
|
||||
req.method(http::verb::get);
|
||||
auto target = this->getOpenOrdersTarget;
|
||||
target += "?status=active";
|
||||
target += std::string("&tradeType=") + (request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN ? "MARGIN_TRADE"
|
||||
: request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN ? "MARGIN_ISOLATED_TRADE"
|
||||
: "TRADE");
|
||||
if (!symbolId.empty()) {
|
||||
target += "&symbol=";
|
||||
target += symbolId;
|
||||
}
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_OPEN_ORDERS: {
|
||||
req.method(http::verb::delete_);
|
||||
auto target = this->cancelOpenOrdersTarget;
|
||||
target += std::string("?tradeType=") + (request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN ? "MARGIN_TRADE"
|
||||
: request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN ? "MARGIN_ISOLATED_TRADE"
|
||||
: "TRADE");
|
||||
if (!symbolId.empty()) {
|
||||
target += "&symbol=";
|
||||
target += symbolId;
|
||||
}
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNTS: {
|
||||
req.method(http::verb::get);
|
||||
std::string target = this->getAccountsTarget;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
if (!param.empty()) {
|
||||
std::string queryString;
|
||||
this->appendParam(queryString, param,
|
||||
{
|
||||
{CCAPI_EM_ASSET, "currency"},
|
||||
{CCAPI_EM_ACCOUNT_TYPE, "type"},
|
||||
});
|
||||
target += "?" + queryString;
|
||||
}
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_BALANCES: {
|
||||
req.method(http::verb::get);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
auto target = this->getAccountBalancesTarget;
|
||||
if (this->isDerivatives) {
|
||||
if (!param.empty()) {
|
||||
std::string queryString;
|
||||
this->appendParam(queryString, param,
|
||||
{
|
||||
{CCAPI_EM_ASSET, "currency"},
|
||||
});
|
||||
target += "?" + queryString;
|
||||
}
|
||||
} else {
|
||||
auto accountId = param.find(CCAPI_EM_ACCOUNT_ID) != param.end() ? param.at(CCAPI_EM_ACCOUNT_ID) : "";
|
||||
this->substituteParam(target, {
|
||||
{"<accountId>", accountId},
|
||||
});
|
||||
}
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_POSITIONS: {
|
||||
req.method(http::verb::get);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
req.target(this->getAccountPositionsTarget);
|
||||
this->signRequest(req, "", 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 {
|
||||
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)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("dealSize", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("dealFunds", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}};
|
||||
const rj::Value& data = document["data"];
|
||||
if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
|
||||
if (data.FindMember("cancelledOrderIds") != data.MemberEnd()) {
|
||||
for (const auto& x : data["cancelledOrderIds"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ORDER_ID, x.GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ORDER_ID, data["cancelledOrderId"].GetString());
|
||||
element.insert(CCAPI_EM_CLIENT_ORDER_ID, data["clientOid"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else if (operation == Request::Operation::CREATE_ORDER) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ORDER_ID, data["orderId"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
} else if (operation == Request::Operation::GET_OPEN_ORDERS) {
|
||||
for (const auto& x : data["items"].GetArray()) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else if (operation == Request::Operation::GET_ORDER) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, data, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
}
|
||||
void extractOrderInfo(Element& element, const rj::Value& x,
|
||||
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
|
||||
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
{
|
||||
auto it = x.FindMember("isActive");
|
||||
if (it != x.MemberEnd()) {
|
||||
element.insert("isActive", it->value.GetBool() ? "true" : "false");
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
|
||||
const std::map<std::string, std::string>& credential) override {
|
||||
std::string topic;
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
topic = this->topicTradeOrders;
|
||||
}
|
||||
std::vector<std::string> sendStringList;
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
static int nextRequestId = 1;
|
||||
std::string requestId = std::to_string(nextRequestId);
|
||||
nextRequestId += 1;
|
||||
document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator);
|
||||
document.AddMember("type", rj::Value("subscribe").Move(), allocator);
|
||||
document.AddMember("privateChannel", true, allocator);
|
||||
document.AddMember("response", true, allocator);
|
||||
document.AddMember("topic", rj::Value(topic.c_str(), allocator).Move(), allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
auto subscription = wsConnection.subscriptionList.at(0);
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(wsConnection, hdl, subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
}
|
||||
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
|
||||
const rj::Document& document, const TimePoint& timeReceived) {
|
||||
Event event;
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
std::string type = document["type"].GetString();
|
||||
if (type == "message") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
std::string topic = document["topic"].GetString();
|
||||
if (topic == this->topicTradeOrders) {
|
||||
const rj::Value& data = document["data"];
|
||||
std::string instrument = data["symbol"].GetString();
|
||||
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
std::string ts = std::string(data["ts"].GetString());
|
||||
auto time = UtilTime::makeTimePoint({std::stoll(ts.substr(0, ts.length() - 9)), std::stoll(ts.substr(ts.length() - 9))});
|
||||
std::string dataType = data["type"].GetString();
|
||||
if (dataType == "match" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(time);
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
std::vector<Element> elementList;
|
||||
Element element;
|
||||
element.insert(CCAPI_TRADE_ID, data["tradeId"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data["matchPrice"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, data["matchSize"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_SIDE, std::string(data["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
|
||||
element.insert(CCAPI_IS_MAKER, std::string(data["liquidity"].GetString()) == "taker" ? "0" : "1");
|
||||
element.insert(CCAPI_EM_ORDER_ID, data["orderId"].GetString());
|
||||
element.insert(CCAPI_EM_CLIENT_ORDER_ID, data["clientOid"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
elementList.emplace_back(std::move(element));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(time);
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
std::map<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("price", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filledSize", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("remainSize", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
|
||||
};
|
||||
extractionFieldNameMap.insert({CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)});
|
||||
Element info;
|
||||
this->extractOrderInfo(info, data, extractionFieldNameMap);
|
||||
std::vector<Element> elementList;
|
||||
elementList.emplace_back(std::move(info));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (type == "ack") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
Element element;
|
||||
element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (type == "error") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (type == "welcome") {
|
||||
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
|
||||
std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingInterval"));
|
||||
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
|
||||
std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingTimeout"));
|
||||
if (this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <=
|
||||
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) {
|
||||
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
|
||||
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1;
|
||||
}
|
||||
ExecutionManagementService::onOpen(hdl);
|
||||
} else if (type == "pong") {
|
||||
auto now = UtilTime::now();
|
||||
this->lastPongTpByMethodByConnectionIdMap[wsConnection.id][PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = now;
|
||||
}
|
||||
event.setMessageList(messageList);
|
||||
return event;
|
||||
}
|
||||
std::string apiPassphraseName;
|
||||
bool isDerivatives{};
|
||||
std::string topicTradeOrders;
|
||||
std::string createOrderMarginTarget;
|
||||
std::string getOrderByClientOrderIdTarget;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_BASE_H_
|
||||
+38
-438
@@ -2,18 +2,14 @@
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_FUTURES_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN_FUTURES
|
||||
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
|
||||
#include "openssl/evp.h"
|
||||
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service_kucoin_base.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceKucoinFutures : public ExecutionManagementService {
|
||||
class ExecutionManagementServiceKucoinFutures : public ExecutionManagementServiceKucoinBase {
|
||||
public:
|
||||
ExecutionManagementServiceKucoinFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
: ExecutionManagementServiceKucoinBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
try {
|
||||
@@ -21,459 +17,63 @@ class ExecutionManagementServiceKucoinFutures : public ExecutionManagementServic
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_KUCOIN_FUTURES_API_KEY;
|
||||
this->apiSecretName = CCAPI_KUCOIN_FUTURES_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
std::string prefix("/api/v1");
|
||||
this->createOrderTarget = prefix + "/orders";
|
||||
this->cancelOrderTarget = prefix + "/orders/client-order/<id>";
|
||||
this->getOpenOrdersTarget = prefix + "/orders";
|
||||
this->cancelOpenOrdersTarget = prefix + "/orders";
|
||||
this->getAccountsTarget = prefix + "/account-overview";
|
||||
this->getAccountPositionsTarget = prefix + "/positions";
|
||||
this->apiPassphraseName = CCAPI_KUCOIN_FUTURES_API_PASSPHRASE;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
|
||||
this->createOrderTarget = "/api/v1/orders";
|
||||
this->cancelOrderTarget = "/api/v1/orders/<id>";
|
||||
this->getOrderTarget = "/api/v1/orders/<id>";
|
||||
this->getOrderByClientOrderIdTarget = "/api/v1/orders/byClientOid?clientOid=<id>";
|
||||
this->getOpenOrdersTarget = "/api/v1/orders";
|
||||
this->cancelOpenOrdersTarget = "/api/v1/orders";
|
||||
this->getAccountBalancesTarget = "/api/v1/account-overview";
|
||||
this->getAccountPositionsTarget = "/api/v1/positions";
|
||||
this->topicTradeOrders = "/contractMarket/tradeOrders";
|
||||
this->isDerivatives = true;
|
||||
}
|
||||
virtual ~ExecutionManagementServiceKrakenFutures() {}
|
||||
|
||||
virtual ~ExecutionManagementServiceKucoinFutures() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
protected:
|
||||
#endif
|
||||
|
||||
void onOpen(wspp::connection_hdl hdl) override {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
wsConnection.status = WsConnection::Status::OPEN;
|
||||
}
|
||||
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override {
|
||||
return !std::regex_search(body, std::regex("\"code\":\\s*\"200000\""));
|
||||
}
|
||||
|
||||
void prepareConnect(WsConnection& wsConnection) override {
|
||||
auto now = UtilTime::now();
|
||||
http::request<http::string_body> req;
|
||||
req.set(http::field::host, this->hostRest);
|
||||
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
|
||||
req.method(http::verb::post);
|
||||
req.target("/api/v1/bullet-private");
|
||||
auto credential = wsConnection.subscriptionList.at(0).getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = this->credentialDefault;
|
||||
}
|
||||
this->prepareReq(req, now, credential);
|
||||
this->signRequest(req, "", credential);
|
||||
this->sendRequest(
|
||||
req,
|
||||
[wsConnection, that = shared_from_base<ExecutionManagementServiceKucoin>()](const beast::error_code& ec) {
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
that->onFail_(thisWsConnection);
|
||||
},
|
||||
[wsConnection, that = shared_from_base<ExecutionManagementServiceKucoin>()](const http::response<http::string_body>& res) {
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
int statusCode = res.result_int();
|
||||
std::string body = res.body();
|
||||
if (statusCode / 100 == 2) {
|
||||
std::string urlWebsocketBase;
|
||||
try {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
|
||||
const rj::Value& instanceServer = document["data"]["instanceServers"][0];
|
||||
urlWebsocketBase += std::string(instanceServer["endpoint"].GetString());
|
||||
urlWebsocketBase += "?token=";
|
||||
urlWebsocketBase += std::string(document["data"]["token"].GetString());
|
||||
thisWsConnection.url = urlWebsocketBase;
|
||||
that->connect(thisWsConnection);
|
||||
that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({
|
||||
{"pingInterval", std::string(instanceServer["pingInterval"].GetString())},
|
||||
{"pingTimeout", std::string(instanceServer["pingTimeout"].GetString())},
|
||||
});
|
||||
return;
|
||||
} catch (const std::runtime_error& e) {
|
||||
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
}
|
||||
that->onFail_(thisWsConnection);
|
||||
},
|
||||
this->sessionOptions.httpRequestTimeoutMilliSeconds);
|
||||
}
|
||||
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
|
||||
auto now = UtilTime::now();
|
||||
this->send(hdl, "{\"id\":\"" + std::to_string(UtilTime::getUnixTimestamp(now)) + "\",\"type\":\"ping\"}", wspp::frame::opcode::text, ec);
|
||||
}
|
||||
|
||||
void signReqeustForRestGenericPrivateRequest(http::request<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 apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto preSignedText = req.base().at("KC-API-TIMESTAMP").to_string();
|
||||
preSignedText += methodString;
|
||||
auto target = path;
|
||||
if (!queryString.empty()) {
|
||||
target += queryString;
|
||||
}
|
||||
preSignedText += target;
|
||||
preSignedText += body;
|
||||
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText));
|
||||
if (!headerString.empty()) {
|
||||
headerString += "\r\n";
|
||||
}
|
||||
headerString += "KC-API-SIGN:" + signature;
|
||||
}
|
||||
|
||||
void signRequest(http::request<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("KC-API-TIMESTAMP").to_string();
|
||||
preSignedText += std::string(req.method_string());
|
||||
preSignedText += req.target().to_string();
|
||||
preSignedText += body;
|
||||
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText));
|
||||
req.set("KC-API-SIGN", signature);
|
||||
req.body() = body;
|
||||
req.prepare_payload();
|
||||
}
|
||||
void signApiPassphrase(http::request<http::string_body>& req, const std::string& apiKeyVersion, const std::string& apiPassphrase,
|
||||
const std::string& apiSecret) {
|
||||
if (apiKeyVersion == "2") {
|
||||
req.set("KC-API-PASSPHRASE", UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, apiPassphrase)));
|
||||
} else {
|
||||
req.set("KC-API-PASSPHRASE", apiPassphrase);
|
||||
}
|
||||
}
|
||||
|
||||
void appendParam(rj::Document& document, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {
|
||||
{CCAPI_EM_ORDER_SIDE, "side"},
|
||||
{CCAPI_EM_ORDER_QUANTITY, "size"},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "clientOid"},
|
||||
}) {
|
||||
for (const auto& kv : param) {
|
||||
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
auto value = kv.second;
|
||||
if (key == "side") {
|
||||
value = (value == CCAPI_EM_ORDER_SIDE_BUY || value == "buy") ? "buy" : "sell";
|
||||
}
|
||||
if (key == "cancelAfter") {
|
||||
document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(static_cast<int64_t>(std::stoll(value))), allocator);
|
||||
} else if (value == "true" || value == "false") {
|
||||
document.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator);
|
||||
} else {
|
||||
document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void appendParam(std::string& queryString, const std::map<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(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
|
||||
document.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
|
||||
void prepareReq(http::request<http::string_body>& req, const TimePoint& now, const std::map<std::string, std::string>& credential) {
|
||||
req.set(beast::http::field::content_type, "application/json");
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
req.set("KC-API-KEY", apiKey);
|
||||
req.set("KC-API-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
|
||||
auto apiKeyVersion = mapGetWithDefault(credential, this->apiKeyVersionName);
|
||||
req.set("KC-API-KEY-VERSION", apiKeyVersion);
|
||||
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
this->signApiPassphrase(req, apiKeyVersion, apiPassphrase, apiSecret);
|
||||
}
|
||||
|
||||
void convertRequestForRest(http::request<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);
|
||||
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);
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_ORDER: {
|
||||
req.method(http::verb::delete_);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
bool useOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end();
|
||||
std::string id = useOrderId ? param.at(CCAPI_EM_ORDER_ID)
|
||||
: param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? "client-order/" + param.at(CCAPI_EM_CLIENT_ORDER_ID)
|
||||
: "";
|
||||
auto target = useOrderId ? std::regex_replace(this->cancelOrderTarget, std::regex("<id>"), id)
|
||||
: std::regex_replace("/api/v1/orders/<id>", std::regex("<id>"), id);
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ORDER: {
|
||||
req.method(http::verb::get);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
bool useOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end();
|
||||
std::string id = useOrderId ? param.at(CCAPI_EM_ORDER_ID)
|
||||
: param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? "client-order/" + param.at(CCAPI_EM_CLIENT_ORDER_ID)
|
||||
: "";
|
||||
auto target =
|
||||
useOrderId ? std::regex_replace(this->getOrderTarget, std::regex("<id>"), id) : std::regex_replace("/api/v1/orders/<id>", std::regex("<id>"), id);
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_OPEN_ORDERS: {
|
||||
req.method(http::verb::get);
|
||||
auto target = this->getOpenOrdersTarget;
|
||||
target += "?status=active";
|
||||
if (!symbolId.empty()) {
|
||||
target += "&symbol=";
|
||||
target += symbolId;
|
||||
}
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_OPEN_ORDERS: {
|
||||
req.method(http::verb::delete_);
|
||||
auto target = this->cancelOpenOrdersTarget;
|
||||
if (!symbolId.empty()) {
|
||||
target += "?symbol=";
|
||||
target += symbolId;
|
||||
}
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_BALANCES: {
|
||||
req.method(http::verb::get);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
auto target = this->getAccountsTarget;
|
||||
auto accountId = param.find(CCAPI_EM_ACCOUNT_ID) != param.end() ? param.at(CCAPI_EM_ACCOUNT_ID) : "";
|
||||
req.target(target);
|
||||
this->signRequest(req, "", credential);
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
|
||||
void extractOrderInfoFromRequest(std::vector<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 = {
|
||||
{CCAPI_EM_ORDER_ID, std::make_pair("id", JsonDataType::STRING)},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}};
|
||||
const rj::Value& data = document["data"];
|
||||
if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
|
||||
if (data.FindMember("cancelledOrderIds") != data.MemberEnd()) {
|
||||
for (const auto& x : data["cancelledOrderIds"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ORDER_ID, x.GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ORDER_ID, data["cancelledOrderId"].GetString());
|
||||
element.insert(CCAPI_EM_CLIENT_ORDER_ID, data["clientOid"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else if (operation == Request::Operation::CREATE_ORDER) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ORDER_ID, data["orderId"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
} else if (operation == Request::Operation::GET_OPEN_ORDERS) {
|
||||
for (const auto& x : data["items"].GetArray()) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} else if (operation == Request::Operation::GET_ORDER) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, data, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
}
|
||||
void extractOrderInfo(Element& element, const rj::Value& x,
|
||||
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
|
||||
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
{
|
||||
auto it = x.FindMember("isActive");
|
||||
if (it != x.MemberEnd()) {
|
||||
element.insert("isActive", it->value.GetBool() ? "true" : "false");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void extractAccountInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
|
||||
const rj::Document& document) override {
|
||||
const auto& data = document["data"];
|
||||
switch (request.getOperation()) {
|
||||
case Request::Operation::GET_ACCOUNTS: {
|
||||
for (const auto& x : data.GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ASSET, x["currency"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["marginBalance"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["availableBalance"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_BALANCES: {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ASSET, data["currency"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, data["marginBalance"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, data["accountEquity"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, data["availableBalance"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_POSITIONS: {
|
||||
for (const auto& x : data.GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
element.insert(CCAPI_SETTLE_ASSET, x["settleCurrency"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_QUANTITY, x["currentQty"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_COST, x["posCost"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgEntryPrice"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["realLeverage"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} break;
|
||||
default:
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
|
||||
const std::map<std::string, std::string>& credential) override {
|
||||
std::string topic;
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
topic = "/contractMarket/tradeOrders";
|
||||
}
|
||||
std::vector<std::string> sendStringList;
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
static int nextRequestId = 1;
|
||||
std::string requestId = std::to_string(nextRequestId);
|
||||
nextRequestId += 1;
|
||||
document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator);
|
||||
document.AddMember("type", rj::Value("subscribe").Move(), allocator);
|
||||
document.AddMember("privateChannel", true, allocator);
|
||||
document.AddMember("response", true, allocator);
|
||||
document.AddMember("topic", rj::Value(topic.c_str(), allocator).Move(), allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
|
||||
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
auto subscription = wsConnection.subscriptionList.at(0);
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(wsConnection, hdl, subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
}
|
||||
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
|
||||
const rj::Document& document, const TimePoint& timeReceived) {
|
||||
Event event;
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
std::string type = document["type"].GetString();
|
||||
if (type == "message") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
std::string topic = document["topic"].GetString();
|
||||
if (topic == "/contractMarket/tradeOrders") {
|
||||
const rj::Value& data = document["data"];
|
||||
std::string instrument = data["symbol"].GetString();
|
||||
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
std::string ts = std::string(data["ts"].GetString());
|
||||
message.setTime(UtilTime::makeTimePoint({std::stoll(ts.substr(0, ts.length() - 9)), std::stoll(ts.substr(ts.length() - 9))}));
|
||||
std::string dataType = data["type"].GetString();
|
||||
if (dataType == "match" && (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end() || fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end())) {
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
std::vector<Element> elementList;
|
||||
Element element;
|
||||
element.insert(CCAPI_TRADE_ID, data["tradeId"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data["matchPrice"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, data["matchSize"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_SIDE, std::string(data["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
|
||||
element.insert(CCAPI_IS_MAKER, std::string(data["liquidity"].GetString()) == "taker" ? "0" : "1");
|
||||
element.insert(CCAPI_EM_ORDER_ID, data["orderId"].GetString());
|
||||
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
elementList.emplace_back(std::move(element));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
std::map<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("price", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filledSize", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("remainSize", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
|
||||
};
|
||||
extractionFieldNameMap.insert({CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)});
|
||||
Element info;
|
||||
this->extractOrderInfo(info, data, extractionFieldNameMap);
|
||||
std::vector<Element> elementList;
|
||||
elementList.emplace_back(std::move(info));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (type == "ack") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
Element element;
|
||||
element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (type == "error") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (type == "welcome") {
|
||||
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
|
||||
std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingInterval"));
|
||||
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
|
||||
std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingTimeout"));
|
||||
if (this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <=
|
||||
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) {
|
||||
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
|
||||
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1;
|
||||
}
|
||||
ExecutionManagementService::onOpen(hdl);
|
||||
} else if (type == "pong") {
|
||||
auto now = UtilTime::now();
|
||||
this->lastPongTpByMethodByConnectionIdMap[wsConnection.id][PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = now;
|
||||
}
|
||||
event.setMessageList(messageList);
|
||||
return event;
|
||||
}
|
||||
std::string apiPassphraseName;
|
||||
std::string apiKeyVersionName;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_H_
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_FUTURES_H_
|
||||
@@ -0,0 +1,444 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_MEXC_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_MEXC_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_MEXC
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceMexc : public ExecutionManagementService {
|
||||
public:
|
||||
ExecutionManagementServiceMexc(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->pingListenKeyIntervalSeconds = 600;
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_MEXC;
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_MEXC_API_KEY;
|
||||
this->apiSecretName = CCAPI_MEXC_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
this->createOrderTarget = CCAPI_MEXC_CREATE_ORDER_PATH;
|
||||
this->cancelOrderTarget = "/api/v3/order";
|
||||
this->getOrderTarget = "/api/v3/order";
|
||||
this->getOpenOrdersTarget = "/api/v3/openOrders";
|
||||
this->cancelOpenOrdersTarget = "/api/v3/openOrders";
|
||||
this->listenKeyTarget = CCAPI_MEXC_LISTEN_KEY_PATH;
|
||||
this->getAccountBalancesTarget = "/api/v3/account";
|
||||
}
|
||||
virtual ~ExecutionManagementServiceMexc() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
protected:
|
||||
#endif
|
||||
// bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; }
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"method":"PING"})", wspp::frame::opcode::text, ec); }
|
||||
void signReqeustForRestGenericPrivateRequest(http::request<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 {
|
||||
if (queryString.find("timestamp=") == std::string::npos) {
|
||||
if (!queryString.empty()) {
|
||||
queryString += "&";
|
||||
}
|
||||
queryString += "timestamp=";
|
||||
queryString += std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count());
|
||||
}
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, queryString, true);
|
||||
queryString += "&signature=";
|
||||
queryString += signature;
|
||||
}
|
||||
void signRequest(std::string& queryString, const std::map<std::string, std::string>& param, const TimePoint& now,
|
||||
const std::map<std::string, std::string>& credential) {
|
||||
if (param.find("timestamp") == param.end()) {
|
||||
queryString += "timestamp=";
|
||||
queryString += std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count());
|
||||
queryString += "&";
|
||||
}
|
||||
if (queryString.back() == '&') {
|
||||
queryString.pop_back();
|
||||
}
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, queryString, true);
|
||||
queryString += "&signature=";
|
||||
queryString += signature;
|
||||
}
|
||||
void appendParam(std::string& queryString, const std::map<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 prepareReq(http::request<http::string_body>& req, const std::map<std::string, std::string>& credential) {
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
req.set("X-MEXC-APIKEY", apiKey);
|
||||
}
|
||||
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::GENERIC_PRIVATE_REQUEST: {
|
||||
ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential);
|
||||
} break;
|
||||
case Request::Operation::CREATE_ORDER: {
|
||||
req.set("source", CCAPI_MEXC_API_SOURCE);
|
||||
req.method(http::verb::post);
|
||||
std::string queryString;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param,
|
||||
{
|
||||
{CCAPI_EM_ORDER_SIDE, "side"},
|
||||
{CCAPI_EM_ORDER_QUANTITY, "quantity"},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "newClientOrderId"},
|
||||
});
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
if (param.find("type") == param.end()) {
|
||||
queryString += "type=LIMIT&";
|
||||
}
|
||||
this->signRequest(queryString, param, now, credential);
|
||||
req.target(std::string(this->createOrderTarget) + "?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_ORDER: {
|
||||
req.method(http::verb::delete_);
|
||||
std::string queryString;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param,
|
||||
{
|
||||
{CCAPI_EM_ORDER_ID, "orderId"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "origClientOrderId"},
|
||||
});
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
this->signRequest(queryString, param, now, credential);
|
||||
req.target(this->cancelOrderTarget + "?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::GET_ORDER: {
|
||||
req.method(http::verb::get);
|
||||
std::string queryString;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param,
|
||||
{
|
||||
{CCAPI_EM_ORDER_ID, "orderId"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "origClientOrderId"},
|
||||
});
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
this->signRequest(queryString, param, now, credential);
|
||||
req.target(this->getOrderTarget + "?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::GET_OPEN_ORDERS: {
|
||||
req.method(http::verb::get);
|
||||
std::string queryString;
|
||||
this->appendParam(queryString, {});
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
}
|
||||
this->signRequest(queryString, {}, now, credential);
|
||||
req.target(this->getOpenOrdersTarget + "?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::CANCEL_OPEN_ORDERS: {
|
||||
req.method(http::verb::delete_);
|
||||
std::string queryString;
|
||||
this->appendParam(queryString, {});
|
||||
this->appendSymbolId(queryString, symbolId);
|
||||
this->signRequest(queryString, {}, now, credential);
|
||||
req.target(this->cancelOpenOrdersTarget + "?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::GET_ACCOUNT_BALANCES: {
|
||||
req.method(http::verb::get);
|
||||
std::string queryString;
|
||||
this->appendParam(queryString, {});
|
||||
this->signRequest(queryString, {}, now, credential);
|
||||
req.target(this->getAccountBalancesTarget + "?" + queryString);
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
void extractOrderInfoFromRequest(std::vector<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::INTEGER)},
|
||||
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("origQty", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("executedQty", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cummulativeQuoteQty", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
|
||||
};
|
||||
if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
|
||||
extractionFieldNameMap.insert({CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("origClientOrderId", JsonDataType::STRING)});
|
||||
} else {
|
||||
extractionFieldNameMap.insert({CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOrderId", JsonDataType::STRING)});
|
||||
}
|
||||
if (document.IsObject()) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, document, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
} else {
|
||||
for (const auto& x : document.GetArray()) {
|
||||
Element element;
|
||||
this->extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
}
|
||||
}
|
||||
void extractAccountInfoFromRequest(std::vector<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["balances"].GetArray()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_EM_ASSET, x["asset"].GetString());
|
||||
element.insert(CCAPI_EM_QUANTITY_TOTAL, Decimal(x["free"].GetString()).add(Decimal(x["locked"].GetString())).toString());
|
||||
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["free"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
} break;
|
||||
default:
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
void prepareConnect(WsConnection& wsConnection) override {
|
||||
auto now = UtilTime::now();
|
||||
auto hostPort = this->extractHostFromUrl(this->baseUrlRest);
|
||||
std::string host = hostPort.first;
|
||||
std::string port = hostPort.second;
|
||||
http::request<http::string_body> req;
|
||||
req.set(http::field::host, host);
|
||||
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
|
||||
req.method(http::verb::post);
|
||||
auto credential = wsConnection.subscriptionList.at(0).getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = this->credentialDefault;
|
||||
}
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
req.set("X-MEXC-APIKEY", apiKey);
|
||||
std::string queryString;
|
||||
this->signRequest(queryString, {}, now, credential);
|
||||
req.target(this->listenKeyTarget + "?" + queryString);
|
||||
this->sendRequest(
|
||||
req,
|
||||
[wsConnection, that = shared_from_base<ExecutionManagementServiceMexc>()](const beast::error_code& ec) {
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
that->onFail_(thisWsConnection);
|
||||
},
|
||||
[wsConnection, that = shared_from_base<ExecutionManagementServiceMexc>()](const http::response<http::string_body>& res) {
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
int statusCode = res.result_int();
|
||||
std::string body = res.body();
|
||||
if (statusCode / 100 == 2) {
|
||||
std::string urlWebsocketBase;
|
||||
try {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
|
||||
std::string listenKey = document["listenKey"].GetString();
|
||||
std::string url = that->baseUrlWs + "?listenKey=" + listenKey;
|
||||
thisWsConnection.url = url;
|
||||
that->connect(thisWsConnection);
|
||||
that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({
|
||||
{"listenKey", listenKey},
|
||||
});
|
||||
return;
|
||||
} catch (const std::runtime_error& e) {
|
||||
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
}
|
||||
that->onFail_(thisWsConnection);
|
||||
},
|
||||
this->sessionOptions.httpRequestTimeoutMilliSeconds);
|
||||
}
|
||||
void onOpen(wspp::connection_hdl hdl) override {
|
||||
ExecutionManagementService::onOpen(hdl);
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
this->setPingListenKeyTimer(wsConnection);
|
||||
}
|
||||
std::vector<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("method", rj::Value("SUBSCRIPTION").Move(), allocator);
|
||||
rj::Value params(rj::kArrayType);
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
for (const auto& field : subscription.getFieldSet()) {
|
||||
std::string channelId;
|
||||
if (field == CCAPI_EM_ORDER_UPDATE) {
|
||||
channelId = "spot@private.orders.v3.api";
|
||||
} else if (field == CCAPI_EM_PRIVATE_TRADE) {
|
||||
channelId = "spot@private.deals.v3.api";
|
||||
}
|
||||
params.PushBack(rj::Value(channelId.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
document.AddMember("params", params, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void setPingListenKeyTimer(const WsConnection& wsConnection) {
|
||||
this->pingListenKeyTimerMapByConnectionIdMap[wsConnection.id] = this->serviceContextPtr->tlsClientPtr->set_timer(
|
||||
this->pingListenKeyIntervalSeconds * 1000, [wsConnection, that = shared_from_base<ExecutionManagementServiceMexc>()](ErrorCode const& ec) {
|
||||
if (ec) {
|
||||
return;
|
||||
}
|
||||
auto now = UtilTime::now();
|
||||
that->setPingListenKeyTimer(wsConnection);
|
||||
http::request<http::string_body> req;
|
||||
req.set(http::field::host, that->hostRest);
|
||||
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
|
||||
req.method(http::verb::put);
|
||||
std::string queryString;
|
||||
std::map<std::string, std::string> params;
|
||||
auto listenKey = that->extraPropertyByConnectionIdMap.at(wsConnection.id).at("listenKey");
|
||||
params.insert({"listenKey", listenKey});
|
||||
for (const auto& param : params) {
|
||||
queryString += param.first + "=" + Url::urlEncode(param.second);
|
||||
queryString += "&";
|
||||
}
|
||||
auto credential = wsConnection.subscriptionList.at(0).getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = that->credentialDefault;
|
||||
}
|
||||
auto apiKey = mapGetWithDefault(credential, that->apiKeyName);
|
||||
req.set("X-MEXC-APIKEY", apiKey);
|
||||
that->signRequest(queryString, {}, now, credential);
|
||||
req.target(that->listenKeyTarget + "?" + queryString);
|
||||
that->sendRequest(
|
||||
req,
|
||||
[wsConnection, that_2 = that->shared_from_base<ExecutionManagementServiceMexc>()](const beast::error_code& ec) {
|
||||
CCAPI_LOGGER_ERROR("ping listen key fail");
|
||||
that_2->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping listen key");
|
||||
},
|
||||
[wsConnection, that_2 = that->shared_from_base<ExecutionManagementServiceMexc>()](const http::response<http::string_body>& res) {
|
||||
CCAPI_LOGGER_DEBUG("ping listen key success");
|
||||
},
|
||||
that->sessionOptions.httpRequestTimeoutMilliSeconds);
|
||||
});
|
||||
}
|
||||
void onClose(wspp::connection_hdl hdl) override {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
if (this->pingListenKeyTimerMapByConnectionIdMap.find(wsConnection.id) != this->pingListenKeyTimerMapByConnectionIdMap.end()) {
|
||||
this->pingListenKeyTimerMapByConnectionIdMap.at(wsConnection.id)->cancel();
|
||||
this->pingListenKeyTimerMapByConnectionIdMap.erase(wsConnection.id);
|
||||
}
|
||||
ExecutionManagementService::onClose(hdl);
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
Event event = this->createEvent(subscription, textMessage, document, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
}
|
||||
Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const TimePoint& timeReceived) {
|
||||
Event event;
|
||||
std::vector<Message> messageList;
|
||||
if (document.IsObject() && document.HasMember("code") && std::string(document["code"].GetString()) == "0") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::string msg = document["msg"].GetString();
|
||||
if (msg != "PONG") {
|
||||
bool success = msg != "no subscription success";
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
} else {
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
std::string c = std::string(document["c"].GetString());
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
const rj::Value& d = document["d"];
|
||||
std::string instrument = document["s"].GetString();
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
if (c == "spot@private.deals.v3.api" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(d["T"].GetString()))));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
std::vector<Element> elementList;
|
||||
Element element;
|
||||
element.insert(CCAPI_TRADE_ID, std::string(d["t"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(d["p"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(d["v"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_SIDE, std::string(d["S"].GetString()) == "1" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
|
||||
element.insert(CCAPI_IS_MAKER, std::string(d["m"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_ID, std::string(d["i"].GetString()));
|
||||
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
{
|
||||
auto it = d.FindMember("c");
|
||||
if (it != d.MemberEnd() && !it->value.IsNull()) {
|
||||
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(it->value.GetString()));
|
||||
}
|
||||
}
|
||||
elementList.emplace_back(std::move(element));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (c == "spot@private.orders.v3.api" && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
|
||||
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(document["t"].GetString()))));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
const std::map<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_LIMIT_PRICE, std::make_pair("p", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("v", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cv", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("ca", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_AVERAGE_FILLED_PRICE, std::make_pair("ap", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("V", JsonDataType::STRING)},
|
||||
{CCAPI_EM_ORDER_STATUS, std::make_pair("s", JsonDataType::STRING)},
|
||||
};
|
||||
Element info;
|
||||
info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
info.insert(CCAPI_EM_ORDER_SIDE, std::string(d["S"].GetString()) == "1" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
|
||||
this->extractOrderInfo(info, d, extractionFieldNameMap);
|
||||
std::vector<Element> elementList;
|
||||
elementList.emplace_back(std::move(info));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
event.setMessageList(messageList);
|
||||
return event;
|
||||
}
|
||||
std::string listenKeyTarget;
|
||||
int pingListenKeyIntervalSeconds;
|
||||
std::map<std::string, TimerPtr> pingListenKeyTimerMapByConnectionIdMap;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_MEXC_H_
|
||||
@@ -0,0 +1,531 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_MEXC_FUTURES_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_MEXC_FUTURES_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_MEXC_FUTURES
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceMexcFutures : public ExecutionManagementService {
|
||||
public:
|
||||
ExecutionManagementServiceMexcFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_MEXC_FUTURES;
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_MEXC_FUTURES_API_KEY;
|
||||
this->apiSecretName = CCAPI_MEXC_FUTURES_API_SECRET;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName});
|
||||
this->createOrderTarget = "/api/v1/private/order/submit";
|
||||
this->cancelOrderTarget = "/api/v1/private/order/cancel";
|
||||
this->cancelOrderWithExternalOidTarget = "/api/v1/private/order/cancel_with_external";
|
||||
this->getOrderTarget = "/api/v1/private/order/get/{order_id}";
|
||||
this->getOrderWithExternalOidTarget = "/api/v1/private/order/external/{symbol}/{external_oid}";
|
||||
this->getOpenOrdersTarget = "/api/v1/private/order/list/open_orders/{symbol}";
|
||||
this->cancelOpenOrdersTarget = "/api/v1/private/order/cancel_all";
|
||||
this->getAccountBalancesTarget = "/api/v1/private/account/assets";
|
||||
this->getAccountPositionsTarget = "/api/v1/private/position/open_positions";
|
||||
}
|
||||
virtual ~ExecutionManagementServiceMexcFutures() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
private:
|
||||
#endif
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"method":"ping"})", wspp::frame::opcode::text, ec); }
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); }
|
||||
void createSignature(std::string& signature, std::string& queryString, const std::string& reqMethod, const std::string& host, const std::string& path,
|
||||
const std::map<std::string, std::string>& queryParamMap, const std::map<std::string, std::string>& credential) {
|
||||
std::string preSignedText;
|
||||
preSignedText += reqMethod;
|
||||
preSignedText += "\n";
|
||||
preSignedText += host;
|
||||
preSignedText += "\n";
|
||||
preSignedText += path;
|
||||
preSignedText += "\n";
|
||||
int i = 0;
|
||||
for (const auto& kv : queryParamMap) {
|
||||
queryString += kv.first;
|
||||
queryString += "=";
|
||||
queryString += kv.second;
|
||||
if (i < queryParamMap.size() - 1) {
|
||||
queryString += "&";
|
||||
}
|
||||
i++;
|
||||
}
|
||||
preSignedText += queryString;
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText));
|
||||
}
|
||||
void signReqeustForRestGenericPrivateRequest(http::request<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 {
|
||||
std::map<std::string, std::string> queryParamMap;
|
||||
if (!queryString.empty()) {
|
||||
for (const auto& x : UtilString::split(queryString, "&")) {
|
||||
auto y = UtilString::split(x, "=");
|
||||
queryParamMap.insert(std::make_pair(y.at(0), y.at(1)));
|
||||
}
|
||||
}
|
||||
std::string signature;
|
||||
this->createSignature(signature, queryString, methodString, this->hostRest, path, queryParamMap, credential);
|
||||
if (!queryString.empty()) {
|
||||
queryString += "&";
|
||||
}
|
||||
queryString += "Signature=";
|
||||
queryString += Url::urlEncode(signature);
|
||||
}
|
||||
void signRequest(http::request<http::string_body>& req, const std::string& path, const std::map<std::string, std::string>& queryParamMap,
|
||||
const std::map<std::string, std::string>& credential) {
|
||||
std::string signature;
|
||||
std::string queryString;
|
||||
this->createSignature(signature, queryString, std::string(req.method_string()), this->hostRest, path, queryParamMap, credential);
|
||||
queryString += "&Signature=";
|
||||
queryString += Url::urlEncode(signature);
|
||||
req.target(path + "?" + queryString);
|
||||
}
|
||||
void signRequest(http::request<http::string_body>& req, const std::string& paramString, const std::map<std::string, std::string>& credential) {
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto preSignedText = apiKey;
|
||||
preSignedText += req.base().at("Request-Time").to_string();
|
||||
preSignedText += paramString;
|
||||
CCAPI_LOGGER_TRACE("preSignedText = " + preSignedText);
|
||||
CCAPI_LOGGER_TRACE("apiSecret = " + apiSecret);
|
||||
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
|
||||
req.set("Signature", signature);
|
||||
}
|
||||
void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {
|
||||
{CCAPI_EM_ORDER_SIDE, "side"},
|
||||
{CCAPI_EM_ORDER_QUANTITY, "vol"},
|
||||
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
|
||||
{CCAPI_EM_CLIENT_ORDER_ID, "externalOid"},
|
||||
{CCAPI_SYMBOL_ID, "symbol"},
|
||||
{CCAPI_EM_ORDER_ID, "orderId"},
|
||||
{CCAPI_EM_ORDER_LEVERAGE, "leverage"},
|
||||
}) {
|
||||
for (const auto& kv : param) {
|
||||
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
|
||||
auto value = kv.second;
|
||||
if (key == CCAPI_EM_ORDER_SIDE || key == CCAPI_EM_ORDER_QUANTITY || key == CCAPI_EM_ORDER_LEVERAGE || key == "vol" || key == "vol" || key == "vol" ||
|
||||
key == "leverage" || key == "side" || key == "type" || key == "openType" || key == "positionId" || key == "positionMode") {
|
||||
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), std::stoll(value), allocator);
|
||||
} else if (key == "reduceOnly") {
|
||||
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator);
|
||||
} else {
|
||||
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
}
|
||||
}
|
||||
void appendParam(std::string& queryString, const std::map<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(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
|
||||
rjValue.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
void appendSymbolId(std::string& queryString, const std::string& symbolId) {
|
||||
queryString += "symbol=";
|
||||
queryString += Url::urlEncode(symbolId);
|
||||
queryString += "&";
|
||||
}
|
||||
void convertRequestForRest(http::request<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("ApiKey", apiKey);
|
||||
std::string timeStr = UtilTime::getISOTimestamp(now);
|
||||
req.set("Request-Time", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
|
||||
Request::Operation operation = request.getOperation();
|
||||
switch (operation) {
|
||||
case Request::Operation::GENERIC_PRIVATE_REQUEST: {
|
||||
ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential);
|
||||
} break;
|
||||
case Request::Operation::CREATE_ORDER: {
|
||||
req.method(http::verb::post);
|
||||
req.target(this->createOrderTarget);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (param.find("type") == param.end()) {
|
||||
document.AddMember("type", rj::Value("1").Move(), allocator);
|
||||
}
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
}
|
||||
const auto& marginType = request.getMarginType();
|
||||
if (marginType == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN) {
|
||||
document.AddMember("openType", 2, allocator);
|
||||
} else if (marginType == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN) {
|
||||
document.AddMember("openType", 1, allocator);
|
||||
}
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
auto body = stringBuffer.GetString();
|
||||
req.body() = body;
|
||||
req.prepare_payload();
|
||||
this->signRequest(req, body, credential);
|
||||
} break;
|
||||
// case Request::Operation::CANCEL_ORDER: {
|
||||
// req.method(http::verb::post);
|
||||
// req.target(this->cancelOrderTarget);
|
||||
// const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
// rj::Document document;
|
||||
// document.SetObject();
|
||||
// rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
// this->appendParam(operation, document, allocator, param);
|
||||
// if (!symbolId.empty()) {
|
||||
// this->appendSymbolId(document, allocator, symbolId);
|
||||
// }
|
||||
// rj::StringBuffer stringBuffer;
|
||||
// rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
// document.Accept(writer);
|
||||
// auto body = stringBuffer.GetString();
|
||||
// this->signRequest(req, body, credential);
|
||||
// } break;
|
||||
// case Request::Operation::GET_ORDER: {
|
||||
// req.method(http::verb::get);
|
||||
// std::string queryString;
|
||||
// const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
// this->appendParam(queryString, param,
|
||||
// {
|
||||
// {CCAPI_EM_ORDER_ID, "ordId"},
|
||||
// {CCAPI_EM_CLIENT_ORDER_ID, "clOrdId"},
|
||||
// {CCAPI_SYMBOL_ID, "symbol"},
|
||||
// });
|
||||
// if (!symbolId.empty()) {
|
||||
// this->appendSymbolId(queryString, symbolId);
|
||||
// }
|
||||
// if (queryString.back() == '&') {
|
||||
// queryString.pop_back();
|
||||
// }
|
||||
// req.target(this->getOrderTarget + "?" + queryString);
|
||||
// this->signRequest(req, "", credential);
|
||||
// } break;
|
||||
// case Request::Operation::GET_OPEN_ORDERS: {
|
||||
// req.method(http::verb::get);
|
||||
// std::string queryString;
|
||||
// const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
// this->appendParam(queryString, param,
|
||||
// {
|
||||
// {CCAPI_EM_ORDER_TYPE, "ordType"},
|
||||
// {CCAPI_SYMBOL_ID, "symbol"},
|
||||
// });
|
||||
// if (!symbolId.empty()) {
|
||||
// this->appendSymbolId(queryString, symbolId);
|
||||
// }
|
||||
// if (queryString.back() == '&') {
|
||||
// queryString.pop_back();
|
||||
// }
|
||||
// req.target(queryString.empty() ? this->getOpenOrdersTarget : this->getOpenOrdersTarget + "?" + queryString);
|
||||
// this->signRequest(req, "", credential);
|
||||
// } break;
|
||||
// case Request::Operation::GET_ACCOUNT_BALANCES: {
|
||||
// req.method(http::verb::get);
|
||||
// req.target(this->getAccountBalancesTarget);
|
||||
// this->signRequest(req, "", credential);
|
||||
// } break;
|
||||
// case Request::Operation::GET_ACCOUNT_POSITIONS: {
|
||||
// req.method(http::verb::get);
|
||||
// req.target(this->getAccountPositionsTarget);
|
||||
// this->signRequest(req, "", credential);
|
||||
// } break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
void extractOrderInfoFromRequest(std::vector<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 = {
|
||||
// {CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)},
|
||||
// {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)},
|
||||
// {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
|
||||
// {CCAPI_EM_ORDER_QUANTITY, std::make_pair("sz", JsonDataType::STRING)},
|
||||
// {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("px", JsonDataType::STRING)},
|
||||
// {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accFillSz", JsonDataType::STRING)},
|
||||
// {CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)},
|
||||
// {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}};
|
||||
// const rj::Value& data = document["data"];
|
||||
// if (data.IsObject()) {
|
||||
// Element element;
|
||||
// this->extractOrderInfo(element, data, extractionFieldNameMap);
|
||||
// elementList.emplace_back(std::move(element));
|
||||
// } else {
|
||||
// for (const auto& x : data.GetArray()) {
|
||||
// Element element;
|
||||
// this->extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
// elementList.emplace_back(std::move(element));
|
||||
// }
|
||||
// }
|
||||
}
|
||||
void extractAccountInfoFromRequest(std::vector<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["data"][0]["details"].GetArray()) {
|
||||
// Element element;
|
||||
// element.insert(CCAPI_EM_ASSET, x["ccy"].GetString());
|
||||
// std::string availEq = x["availEq"].GetString();
|
||||
// element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, availEq.empty() ? x["availBal"].GetString() : availEq);
|
||||
// element.insert(CCAPI_EM_QUANTITY_TOTAL, x["eq"].GetString());
|
||||
// elementList.emplace_back(std::move(element));
|
||||
// }
|
||||
// } break;
|
||||
// case Request::Operation::GET_ACCOUNT_POSITIONS: {
|
||||
// for (const auto& x : document["data"].GetArray()) {
|
||||
// Element element;
|
||||
// element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
// element.insert(CCAPI_EM_POSITION_SIDE, x["posSide"].GetString());
|
||||
// std::string availPos = x["availPos"].GetString();
|
||||
// std::string positionQuantity = availPos.empty() ? x["pos"].GetString() : availPos;
|
||||
// element.insert(CCAPI_EM_POSITION_QUANTITY, positionQuantity);
|
||||
// element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgPx"].GetString());
|
||||
// element.insert(CCAPI_EM_POSITION_LEVERAGE, x["lever"].GetString());
|
||||
// elementList.emplace_back(std::move(element));
|
||||
// }
|
||||
// } break;
|
||||
// default:
|
||||
// CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
// }
|
||||
}
|
||||
void extractOrderInfo(Element& element, const rj::Value& x,
|
||||
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
|
||||
// ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
|
||||
// {
|
||||
// auto it1 = x.FindMember("accFillSz");
|
||||
// auto it2 = x.FindMember("avgPx");
|
||||
// if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
|
||||
// auto it1Str = std::string(it1->value.GetString());
|
||||
// auto it2Str = std::string(it2->value.GetString());
|
||||
// if (!it1Str.empty() && !it2Str.empty()) {
|
||||
// element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
std::vector<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("login").Move(), allocator);
|
||||
// rj::Value arg(rj::kObjectType);
|
||||
// auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
// auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
// auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
|
||||
// std::string ts = std::to_string(std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count());
|
||||
// arg.AddMember("apiKey", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
|
||||
// arg.AddMember("passphrase", rj::Value(apiPassphrase.c_str(), allocator).Move(), allocator);
|
||||
// arg.AddMember("timestamp", rj::Value(ts.c_str(), allocator).Move(), allocator);
|
||||
// std::string signData = ts + "GET" + "/users/self/verify";
|
||||
// std::string sign = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, signData));
|
||||
// arg.AddMember("sign", rj::Value(sign.c_str(), allocator).Move(), allocator);
|
||||
// rj::Value args(rj::kArrayType);
|
||||
// args.PushBack(arg, allocator);
|
||||
// document.AddMember("args", args, allocator);
|
||||
// rj::StringBuffer stringBuffer;
|
||||
// rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
// document.Accept(writer);
|
||||
// std::string sendString = stringBuffer.GetString();
|
||||
// sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
|
||||
const TimePoint& timeReceived) override {
|
||||
// if (textMessage != "pong") {
|
||||
// rj::Document document;
|
||||
// document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
// auto it = document.FindMember("event");
|
||||
// std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : "";
|
||||
// if (eventStr == "login") {
|
||||
// rj::Document document;
|
||||
// document.SetObject();
|
||||
// auto& allocator = document.GetAllocator();
|
||||
// document.AddMember("op", rj::Value("subscribe").Move(), allocator);
|
||||
// rj::Value args(rj::kArrayType);
|
||||
// const auto& fieldSet = subscription.getFieldSet();
|
||||
// const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
// for (const auto& field : fieldSet) {
|
||||
// std::string channel;
|
||||
// if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
// channel = "orders";
|
||||
// }
|
||||
// for (const auto& instrument : instrumentSet) {
|
||||
// rj::Value arg(rj::kObjectType);
|
||||
// arg.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator);
|
||||
// arg.AddMember("symbol", rj::Value(instrument.c_str(), allocator).Move(), allocator);
|
||||
// arg.AddMember("instType", rj::Value("ANY").Move(), allocator);
|
||||
// args.PushBack(arg, allocator);
|
||||
// }
|
||||
// }
|
||||
// document.AddMember("args", args, allocator);
|
||||
// rj::StringBuffer stringBufferSubscribe;
|
||||
// rj::Writer<rj::StringBuffer> writerSubscribe(stringBufferSubscribe);
|
||||
// document.Accept(writerSubscribe);
|
||||
// std::string sendString = stringBufferSubscribe.GetString();
|
||||
// ErrorCode ec;
|
||||
// this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
// if (ec) {
|
||||
// this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
// }
|
||||
// } else {
|
||||
// Event event = this->createEvent(subscription, textMessage, document, eventStr, timeReceived);
|
||||
// if (!event.getMessageList().empty()) {
|
||||
// this->eventHandler(event, nullptr);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const std::string& eventStr,
|
||||
const TimePoint& timeReceived) {
|
||||
Event event;
|
||||
// std::vector<Message> messageList;
|
||||
// Message message;
|
||||
// message.setTimeReceived(timeReceived);
|
||||
// const auto& correlationId = subscription.getCorrelationId();
|
||||
// message.setCorrelationIdList({correlationId});
|
||||
// const auto& fieldSet = subscription.getFieldSet();
|
||||
// const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
// if (eventStr.empty()) {
|
||||
// auto it = document.FindMember("op");
|
||||
// std::string op = it != document.MemberEnd() ? it->value.GetString() : "";
|
||||
// if (op == "order" || op == "cancel-order") {
|
||||
// event.setType(Event::Type::RESPONSE);
|
||||
// std::string code = document["code"].GetString();
|
||||
// if (code != "0") {
|
||||
// message.setType(Message::Type::RESPONSE_ERROR);
|
||||
// Element element;
|
||||
// element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
// message.setElementList({element});
|
||||
// message.setSecondaryCorrelationIdMap({
|
||||
// {correlationId, document["id"].GetString()},
|
||||
// });
|
||||
// messageList.emplace_back(std::move(message));
|
||||
// } else {
|
||||
// std::vector<Element> elementList;
|
||||
// if (op == "order") {
|
||||
// message.setType(Message::Type::CREATE_ORDER);
|
||||
// } else if (op == "cancel-order") {
|
||||
// message.setType(Message::Type::CANCEL_ORDER);
|
||||
// }
|
||||
// this->extractOrderInfoFromRequest(elementList, document);
|
||||
// message.setElementList(elementList);
|
||||
// message.setSecondaryCorrelationIdMap({
|
||||
// {correlationId, document["id"].GetString()},
|
||||
// });
|
||||
// messageList.emplace_back(std::move(message));
|
||||
// }
|
||||
// } else {
|
||||
// const rj::Value& arg = document["arg"];
|
||||
// const rj::Value& data = document["data"];
|
||||
// std::string channel = std::string(arg["channel"].GetString());
|
||||
// event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
// std::string instrument = arg["symbol"].GetString();
|
||||
// if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
// if (channel == "orders") {
|
||||
// if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
// for (const auto& x : data.GetArray()) {
|
||||
// std::string tradeId = x["tradeId"].GetString();
|
||||
// if (!tradeId.empty()) {
|
||||
// Message message;
|
||||
// message.setTimeReceived(timeReceived);
|
||||
// message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
// message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString()))));
|
||||
// message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
// std::vector<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()) {
|
||||
// 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_STATUS, std::make_pair("state", JsonDataType::STRING)},
|
||||
// };
|
||||
// Element info;
|
||||
// this->extractOrderInfo(info, x, extractionFieldNameMap);
|
||||
// info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
// std::vector<Element> elementList;
|
||||
// elementList.emplace_back(std::move(info));
|
||||
// message.setElementList(elementList);
|
||||
// messageList.emplace_back(std::move(message));
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// } else if (eventStr == "subscribe") {
|
||||
// event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
// message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
// Element element;
|
||||
// element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
// message.setElementList({element});
|
||||
// messageList.emplace_back(std::move(message));
|
||||
// } else if (eventStr == "error") {
|
||||
// event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
// message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
// Element element;
|
||||
// element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
// message.setElementList({element});
|
||||
// messageList.emplace_back(std::move(message));
|
||||
// }
|
||||
// event.setMessageList(messageList);
|
||||
return event;
|
||||
}
|
||||
std::string cancelOrderWithExternalOidTarget, getOrderWithExternalOidTarget;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_MEXC_FUTURES_H_
|
||||
+143
-96
@@ -1,27 +1,36 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKEX_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKEX_H_
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKX_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKX_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_OKEX
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_OKX
|
||||
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
|
||||
namespace ccapi {
|
||||
class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
class ExecutionManagementServiceOkx : public ExecutionManagementService {
|
||||
public:
|
||||
ExecutionManagementServiceOkex(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
ExecutionManagementServiceOkx(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
ServiceContextPtr serviceContextPtr)
|
||||
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_OKEX;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + CCAPI_OKEX_PRIVATE_WS_PATH;
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_OKX;
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + CCAPI_OKX_PRIVATE_WS_PATH;
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
this->apiKeyName = CCAPI_OKEX_API_KEY;
|
||||
this->apiSecretName = CCAPI_OKEX_API_SECRET;
|
||||
this->apiPassphraseName = CCAPI_OKEX_API_PASSPHRASE;
|
||||
this->apiXSimulatedTradingName = CCAPI_OKEX_API_X_SIMULATED_TRADING;
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_OKX_API_KEY;
|
||||
this->apiSecretName = CCAPI_OKX_API_SECRET;
|
||||
this->apiPassphraseName = CCAPI_OKX_API_PASSPHRASE;
|
||||
this->apiXSimulatedTradingName = CCAPI_OKX_API_X_SIMULATED_TRADING;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName, this->apiXSimulatedTradingName});
|
||||
this->createOrderTarget = "/api/v5/trade/order";
|
||||
this->cancelOrderTarget = "/api/v5/trade/cancel-order";
|
||||
@@ -30,13 +39,17 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
this->getAccountBalancesTarget = "/api/v5/account/balance";
|
||||
this->getAccountPositionsTarget = "/api/v5/account/positions";
|
||||
}
|
||||
virtual ~ExecutionManagementServiceOkex() {}
|
||||
virtual ~ExecutionManagementServiceOkx() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
private:
|
||||
#endif
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); }
|
||||
#else
|
||||
void pingOnApplicationLevel(std::shared_ptr<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 {
|
||||
@@ -66,7 +79,7 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
req.body() = body;
|
||||
req.prepare_payload();
|
||||
}
|
||||
void appendParam(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
|
||||
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"},
|
||||
{CCAPI_EM_ORDER_QUANTITY, "sz"},
|
||||
@@ -83,6 +96,9 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
}
|
||||
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
|
||||
}
|
||||
if (operation == Request::Operation::CREATE_ORDER && param.find("tag") == param.end()) {
|
||||
rjValue.AddMember("tag", CCAPI_OKX_API_BROKER_CODE, allocator);
|
||||
}
|
||||
}
|
||||
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param,
|
||||
const std::map<std::string, std::string> standardizationMap = {}) {
|
||||
@@ -114,7 +130,8 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
if (apiXSimulatedTrading == "1") {
|
||||
req.set("x-simulated-trading", "1");
|
||||
}
|
||||
switch (request.getOperation()) {
|
||||
Request::Operation operation = request.getOperation();
|
||||
switch (operation) {
|
||||
case Request::Operation::GENERIC_PRIVATE_REQUEST: {
|
||||
ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential);
|
||||
} break;
|
||||
@@ -125,7 +142,7 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(document, allocator, param);
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (param.find("tdMode") == param.end()) {
|
||||
document.AddMember("tdMode", rj::Value("cash").Move(), allocator);
|
||||
}
|
||||
@@ -148,7 +165,7 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
this->appendParam(document, allocator, param);
|
||||
this->appendParam(operation, document, allocator, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(document, allocator, symbolId);
|
||||
}
|
||||
@@ -213,14 +230,17 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
int wsRequestId, const TimePoint& now, const std::string& symbolId,
|
||||
const std::map<std::string, std::string>& credential) override {
|
||||
document.SetObject();
|
||||
document.AddMember("id", rj::Value(std::to_string(wsRequestId).c_str(), allocator).Move(), allocator);
|
||||
switch (request.getOperation()) {
|
||||
const auto& secondaryCorrelationId = request.getSecondaryCorrelationId();
|
||||
document.AddMember("id", rj::Value((secondaryCorrelationId.empty() ? std::to_string(wsRequestId) : secondaryCorrelationId).c_str(), allocator).Move(),
|
||||
allocator);
|
||||
Request::Operation operation = request.getOperation();
|
||||
switch (operation) {
|
||||
case Request::Operation::CREATE_ORDER: {
|
||||
document.AddMember("op", rj::Value("order").Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Value arg(rj::kObjectType);
|
||||
this->appendParam(arg, allocator, param);
|
||||
this->appendParam(operation, arg, allocator, param);
|
||||
if (param.find("tdMode") == param.end()) {
|
||||
arg.AddMember("tdMode", rj::Value("cash").Move(), allocator);
|
||||
}
|
||||
@@ -238,7 +258,7 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
rj::Value args(rj::kArrayType);
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
rj::Value arg(rj::kObjectType);
|
||||
this->appendParam(arg, allocator, param);
|
||||
this->appendParam(operation, arg, allocator, param);
|
||||
if (!symbolId.empty()) {
|
||||
this->appendSymbolId(arg, allocator, symbolId);
|
||||
}
|
||||
@@ -297,7 +317,7 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
std::string availPos = x["availPos"].GetString();
|
||||
std::string positionQuantity = availPos.empty() ? x["pos"].GetString() : availPos;
|
||||
element.insert(CCAPI_EM_POSITION_QUANTITY, positionQuantity);
|
||||
element.insert(CCAPI_EM_POSITION_COST, std::to_string(std::stod(x["avgPx"].GetString()) * std::stod(positionQuantity)));
|
||||
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgPx"].GetString());
|
||||
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["lever"].GetString());
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
@@ -316,7 +336,7 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
auto it1Str = std::string(it1->value.GetString());
|
||||
auto it2Str = std::string(it2->value.GetString());
|
||||
if (!it1Str.empty() && !it2Str.empty()) {
|
||||
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::to_string(std::stod(it1Str) * std::stod(it2Str)));
|
||||
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -349,19 +369,31 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
|
||||
const TimePoint& timeReceived) override {
|
||||
auto it = document.FindMember("event");
|
||||
std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : "";
|
||||
if (eventStr == "login") {
|
||||
void onTextMessage(
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage
|
||||
#else
|
||||
std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView
|
||||
#endif
|
||||
,
|
||||
const TimePoint& timeReceived) override {
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
std::string textMessage(textMessageView);
|
||||
#endif
|
||||
if (textMessage != "pong") {
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
auto& allocator = document.GetAllocator();
|
||||
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
for (const auto& field : fieldSet) {
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
auto it = document.FindMember("event");
|
||||
std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : "";
|
||||
if (eventStr == "login") {
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
auto& allocator = document.GetAllocator();
|
||||
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
std::string channel;
|
||||
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
channel = "orders";
|
||||
@@ -373,21 +405,25 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
arg.AddMember("instType", rj::Value("ANY").Move(), allocator);
|
||||
args.PushBack(arg, allocator);
|
||||
}
|
||||
}
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBufferSubscribe;
|
||||
rj::Writer<rj::StringBuffer> writerSubscribe(stringBufferSubscribe);
|
||||
document.Accept(writerSubscribe);
|
||||
std::string sendString = stringBufferSubscribe.GetString();
|
||||
ErrorCode ec;
|
||||
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
} else {
|
||||
Event event = this->createEvent(subscription, textMessage, document, eventStr, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBufferSubscribe;
|
||||
rj::Writer<rj::StringBuffer> writerSubscribe(stringBufferSubscribe);
|
||||
document.Accept(writerSubscribe);
|
||||
std::string sendString = stringBufferSubscribe.GetString();
|
||||
ErrorCode ec;
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
#else
|
||||
this->send(wsConnectionPtr, sendString, ec);
|
||||
#endif
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
} else {
|
||||
Event event = this->createEvent(subscription, textMessage, document, eventStr, timeReceived);
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -397,7 +433,8 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
const auto& correlationId = subscription.getCorrelationId();
|
||||
message.setCorrelationIdList({correlationId});
|
||||
const auto& fieldSet = subscription.getFieldSet();
|
||||
const auto& instrumentSet = subscription.getInstrumentSet();
|
||||
if (eventStr.empty()) {
|
||||
@@ -411,6 +448,9 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
message.setSecondaryCorrelationIdMap({
|
||||
{correlationId, document["id"].GetString()},
|
||||
});
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else {
|
||||
std::vector<Element> elementList;
|
||||
@@ -421,6 +461,9 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
}
|
||||
this->extractOrderInfoFromRequest(elementList, document);
|
||||
message.setElementList(elementList);
|
||||
message.setSecondaryCorrelationIdMap({
|
||||
{correlationId, document["id"].GetString()},
|
||||
});
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
} else {
|
||||
@@ -430,57 +473,61 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
std::string instrument = arg["instId"].GetString();
|
||||
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
|
||||
if (channel == "orders" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
for (const auto& x : data.GetArray()) {
|
||||
std::string tradeId = x["tradeId"].GetString();
|
||||
if (!tradeId.empty()) {
|
||||
if (channel == "orders") {
|
||||
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
|
||||
for (const auto& x : data.GetArray()) {
|
||||
std::string tradeId = x["tradeId"].GetString();
|
||||
if (!tradeId.empty()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString()))));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
std::vector<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()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString()))));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString()))));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
const std::map<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);
|
||||
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));
|
||||
elementList.emplace_back(std::move(info));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
} else if (channel == "orders" && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
|
||||
for (const auto& x : data.GetArray()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({subscription.getCorrelationId()});
|
||||
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString()))));
|
||||
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
|
||||
const std::map<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_STATUS, std::make_pair("state", JsonDataType::STRING)},
|
||||
};
|
||||
Element info;
|
||||
this->extractOrderInfo(info, x, extractionFieldNameMap);
|
||||
info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
|
||||
std::vector<Element> elementList;
|
||||
elementList.emplace_back(std::move(info));
|
||||
message.setElementList(elementList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -508,4 +555,4 @@ class ExecutionManagementServiceOkex : public ExecutionManagementService {
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKEX_H_
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKX_H_
|
||||
Whitespace-only changes.
@@ -6,6 +6,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "ccapi_cpp/ccapi_hmac.h"
|
||||
#include "ccapi_cpp/ccapi_logger.h"
|
||||
#include "ccapi_cpp/ccapi_util_private.h"
|
||||
#include "ccapi_cpp/service/ccapi_service.h"
|
||||
@@ -35,17 +36,23 @@ class MarketDataService : public Service {
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const auto& x : this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap) {
|
||||
for (const auto& y : x.second) {
|
||||
y.second->cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
// subscriptions are grouped and each group creates a unique websocket connection
|
||||
void subscribe(std::vector<Subscription>& subscriptionList) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
CCAPI_LOGGER_DEBUG("this->baseUrl = " + this->baseUrl);
|
||||
CCAPI_LOGGER_DEBUG("this->baseUrlWs = " + this->baseUrlWs);
|
||||
if (this->shouldContinue.load()) {
|
||||
for (auto& x : this->groupSubscriptionListByInstrumentGroup(subscriptionList)) {
|
||||
auto instrumentGroup = x.first;
|
||||
auto subscriptionListGivenInstrumentGroup = x.second;
|
||||
wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), [that = shared_from_base<MarketDataService>(), instrumentGroup,
|
||||
subscriptionListGivenInstrumentGroup]() mutable {
|
||||
boost::asio::post(*this->serviceContextPtr->ioContextPtr, [that = shared_from_base<MarketDataService>(), instrumentGroup,
|
||||
subscriptionListGivenInstrumentGroup]() mutable {
|
||||
auto now = UtilTime::now();
|
||||
for (auto& subscription : subscriptionListGivenInstrumentGroup) {
|
||||
subscription.setTimeSent(now);
|
||||
@@ -70,7 +77,11 @@ class MarketDataService : public Service {
|
||||
that->subscribeToExchange(wsConnection);
|
||||
} else {
|
||||
auto url = UtilString::split(instrumentGroup, "|").at(0);
|
||||
WsConnection wsConnection(url, instrumentGroup, subscriptionListGivenInstrumentGroup);
|
||||
auto credential = subscriptionListGivenInstrumentGroup.at(0).getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = that->credentialDefault;
|
||||
}
|
||||
WsConnection wsConnection(url, instrumentGroup, subscriptionListGivenInstrumentGroup, credential);
|
||||
that->prepareConnect(wsConnection);
|
||||
}
|
||||
});
|
||||
@@ -78,12 +89,79 @@ class MarketDataService : public Service {
|
||||
}
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
#else
|
||||
// subscriptions are grouped and each group creates a unique websocket connection
|
||||
void subscribe(std::vector<Subscription>& subscriptionList) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
CCAPI_LOGGER_DEBUG("this->baseUrlWs = " + this->baseUrlWs);
|
||||
if (this->shouldContinue.load()) {
|
||||
for (auto& x : this->groupSubscriptionListByInstrumentGroup(subscriptionList)) {
|
||||
auto instrumentGroup = x.first;
|
||||
auto subscriptionListGivenInstrumentGroup = x.second;
|
||||
boost::asio::post(*this->serviceContextPtr->ioContextPtr, [that = shared_from_base<MarketDataService>(), instrumentGroup,
|
||||
subscriptionListGivenInstrumentGroup]() mutable {
|
||||
auto now = UtilTime::now();
|
||||
for (auto& subscription : subscriptionListGivenInstrumentGroup) {
|
||||
subscription.setTimeSent(now);
|
||||
}
|
||||
std::map<std::string, std::vector<std::string>> wsConnectionIdListByInstrumentGroupMap = invertMapMulti(that->instrumentGroupByWsConnectionIdMap);
|
||||
if (wsConnectionIdListByInstrumentGroupMap.find(instrumentGroup) != wsConnectionIdListByInstrumentGroupMap.end() &&
|
||||
that->subscriptionStatusByInstrumentGroupInstrumentMap.find(instrumentGroup) != that->subscriptionStatusByInstrumentGroupInstrumentMap.end()) {
|
||||
auto wsConnectionId = wsConnectionIdListByInstrumentGroupMap.at(instrumentGroup).at(0);
|
||||
auto wsConnectionPtr = that->wsConnectionByIdMap.at(wsConnectionId);
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
for (const auto& subscription : subscriptionListGivenInstrumentGroup) {
|
||||
auto instrument = subscription.getInstrument();
|
||||
if (that->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup].find(instrument) !=
|
||||
that->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup].end()) {
|
||||
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, "already subscribed: " + toString(subscription));
|
||||
return;
|
||||
}
|
||||
wsConnection.subscriptionList.push_back(subscription);
|
||||
that->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup][instrument] = Subscription::Status::SUBSCRIBING;
|
||||
that->prepareSubscription(wsConnection, subscription);
|
||||
}
|
||||
CCAPI_LOGGER_INFO("about to subscribe to exchange");
|
||||
that->subscribeToExchange(wsConnectionPtr);
|
||||
} else {
|
||||
auto url = UtilString::split(instrumentGroup, "|").at(0);
|
||||
auto credential = subscriptionListGivenInstrumentGroup.at(0).getCredential();
|
||||
if (credential.empty()) {
|
||||
credential = that->credentialDefault;
|
||||
}
|
||||
std::shared_ptr<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);
|
||||
} 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(),
|
||||
[](Subscription subscription) { return subscription.getCorrelationId(); });
|
||||
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "create stream", correlationIdList);
|
||||
return;
|
||||
}
|
||||
std::shared_ptr<WsConnection> wsConnectionPtr(new WsConnection(url, instrumentGroup, subscriptionListGivenInstrumentGroup, credential, streamPtr));
|
||||
CCAPI_LOGGER_WARN("about to subscribe with new wsConnectionPtr " + toString(*wsConnectionPtr));
|
||||
that->prepareConnect(wsConnectionPtr);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
#endif
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
protected:
|
||||
#endif
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
typedef wspp::lib::error_code ErrorCode;
|
||||
typedef wspp::lib::function<void(ErrorCode const&)> TimerHandler;
|
||||
#else
|
||||
typedef boost::system::error_code ErrorCode;
|
||||
#endif
|
||||
std::map<std::string, std::vector<Subscription>> groupSubscriptionListByInstrumentGroup(const std::vector<Subscription>& subscriptionList) {
|
||||
std::map<std::string, std::vector<Subscription>> groups;
|
||||
for (const auto& subscription : subscriptionList) {
|
||||
@@ -93,7 +171,7 @@ class MarketDataService : public Service {
|
||||
return groups;
|
||||
}
|
||||
virtual std::string getInstrumentGroup(const Subscription& subscription) {
|
||||
return this->baseUrl + "|" + subscription.getField() + "|" + subscription.getSerializedOptions();
|
||||
return this->baseUrlWs + "|" + subscription.getField() + "|" + subscription.getSerializedOptions() + "|" + subscription.getSerializedCredential();
|
||||
}
|
||||
void prepareSubscription(const WsConnection& wsConnection, const Subscription& subscription) {
|
||||
auto instrument = subscription.getInstrument();
|
||||
@@ -107,7 +185,7 @@ class MarketDataService : public Service {
|
||||
std::string channelId = this->sessionConfigs.getExchangeFieldWebsocketChannelMap().at(this->exchangeName).at(field);
|
||||
CCAPI_LOGGER_TRACE("channelId = " + channelId);
|
||||
CCAPI_LOGGER_TRACE("this->exchangeName = " + this->exchangeName);
|
||||
this->prepareSubscriptionDetail(channelId, symbolId, field, wsConnection, optionMap);
|
||||
this->prepareSubscriptionDetail(channelId, symbolId, field, wsConnection, subscription, optionMap);
|
||||
CCAPI_LOGGER_TRACE("channelId = " + channelId);
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].push_back(subscription.getCorrelationId());
|
||||
this->subscriptionListByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].push_back(subscription);
|
||||
@@ -118,6 +196,7 @@ class MarketDataService : public Service {
|
||||
CCAPI_LOGGER_TRACE("this->correlationIdListByConnectionIdChannelSymbolIdMap = " + toString(this->correlationIdListByConnectionIdChannelIdSymbolIdMap));
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
void processMarketDataMessageList(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
|
||||
Event& event, std::vector<MarketDataMessage>& marketDataMessageList) {
|
||||
CCAPI_LOGGER_TRACE("marketDataMessageList = " + toString(marketDataMessageList));
|
||||
@@ -198,7 +277,8 @@ class MarketDataService : public Service {
|
||||
correlationIdList, isSolicited);
|
||||
}
|
||||
} else {
|
||||
CCAPI_LOGGER_WARN("websocket event type is unknown!");
|
||||
CCAPI_LOGGER_WARN("websocket event type is unknown for " + toString(marketDataMessage));
|
||||
CCAPI_LOGGER_WARN("textMessage is " + textMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -231,7 +311,395 @@ class MarketDataService : public Service {
|
||||
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived);
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
void updateOrderBook(std::map<Decimal, std::string>& snapshot, Decimal& price, std::string& size, bool sizeMayHaveTrailingZero = false) {
|
||||
virtual void onIncorrectStatesFound(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
|
||||
const std::string& exchangeSubscriptionId, std::string const& reason) {
|
||||
std::string errorMessage = "incorrect states found: connection = " + toString(wsConnection) + ", textMessage = " + textMessage +
|
||||
", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", exchangeSubscriptionId = " + exchangeSubscriptionId +
|
||||
", reason = " + reason;
|
||||
CCAPI_LOGGER_ERROR(errorMessage);
|
||||
ErrorCode ec;
|
||||
this->close(wsConnection, hdl, websocketpp::close::status::normal, "incorrect states found: " + reason, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, "shutdown");
|
||||
}
|
||||
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false;
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, errorMessage);
|
||||
}
|
||||
void connect(WsConnection& wsConnection) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
Service::connect(wsConnection);
|
||||
this->instrumentGroupByWsConnectionIdMap.insert(std::pair<std::string, std::string>(wsConnection.id, wsConnection.group));
|
||||
CCAPI_LOGGER_DEBUG("this->instrumentGroupByWsConnectionIdMap = " + toString(this->instrumentGroupByWsConnectionIdMap));
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
void onOpen(wspp::connection_hdl hdl) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
auto now = UtilTime::now();
|
||||
Service::onOpen(hdl);
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
auto credential = wsConnection.credential;
|
||||
if (!credential.empty()) {
|
||||
this->logonToExchange(wsConnection, now, credential);
|
||||
} else {
|
||||
this->startSubscribe(wsConnection);
|
||||
}
|
||||
}
|
||||
void onFail_(WsConnection& wsConnection) override {
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
Service::onFail_(wsConnection);
|
||||
this->instrumentGroupByWsConnectionIdMap.erase(thisWsConnection.id);
|
||||
}
|
||||
void clearStates(WsConnection& wsConnection) override {
|
||||
Service::clearStates(wsConnection);
|
||||
this->fieldByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->optionMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->subscriptionListByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id);
|
||||
this->snapshotBidByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->snapshotAskByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->previousConflateSnapshotBidByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->previousConflateSnapshotAskByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->processedInitialTradeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->previousConflateTimeMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
if (this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.end()) {
|
||||
for (const auto& x : this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
|
||||
for (const auto& y : x.second) {
|
||||
y.second->cancel();
|
||||
}
|
||||
}
|
||||
this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
}
|
||||
this->openByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->highByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->lowByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->closeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->orderBookChecksumByConnectionIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.erase(wsConnection.id);
|
||||
if (this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.find(wsConnection.id) !=
|
||||
this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.end()) {
|
||||
for (const auto& x : this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id)) {
|
||||
x.second->cancel();
|
||||
}
|
||||
this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id);
|
||||
}
|
||||
this->orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id);
|
||||
}
|
||||
void onClose(wspp::connection_hdl hdl) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
|
||||
this->exchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
|
||||
this->instrumentGroupByWsConnectionIdMap.erase(wsConnection.id);
|
||||
this->correlationIdByConnectionIdMap.erase(wsConnection.id);
|
||||
Service::onClose(hdl);
|
||||
}
|
||||
virtual void subscribeToExchange(const WsConnection& wsConnection) {
|
||||
CCAPI_LOGGER_INFO("exchange is " + this->exchangeName);
|
||||
std::vector<std::string> sendStringList;
|
||||
if (this->correlationIdByConnectionIdMap.find(wsConnection.id) == this->correlationIdByConnectionIdMap.end()) {
|
||||
sendStringList = this->createSendStringList(wsConnection);
|
||||
} else {
|
||||
auto subscription = wsConnection.subscriptionList.at(0);
|
||||
sendStringList = std::vector<std::string>(1, subscription.getRawOptions());
|
||||
}
|
||||
for (const auto& sendString : sendStringList) {
|
||||
CCAPI_LOGGER_INFO("sendString = " + sendString);
|
||||
ErrorCode ec;
|
||||
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
}
|
||||
}
|
||||
void startSubscribe(WsConnection& wsConnection) {
|
||||
auto instrumentGroup = wsConnection.group;
|
||||
for (const auto& subscription : wsConnection.subscriptionList) {
|
||||
auto instrument = subscription.getInstrument();
|
||||
this->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup][instrument] = Subscription::Status::SUBSCRIBING;
|
||||
if (subscription.getRawOptions().empty()) {
|
||||
this->prepareSubscription(wsConnection, subscription);
|
||||
} else {
|
||||
this->correlationIdByConnectionIdMap.insert({wsConnection.id, subscription.getCorrelationId()});
|
||||
}
|
||||
}
|
||||
CCAPI_LOGGER_INFO("about to subscribe to exchange");
|
||||
this->subscribeToExchange(wsConnection);
|
||||
}
|
||||
virtual void logonToExchange(const WsConnection& wsConnection, const TimePoint& now, const std::map<std::string, std::string>& credential) {
|
||||
CCAPI_LOGGER_INFO("about to logon to exchange");
|
||||
CCAPI_LOGGER_INFO("exchange is " + this->exchangeName);
|
||||
auto subscriptionList = wsConnection.subscriptionList;
|
||||
std::vector<std::string> sendStringList = this->createSendStringListFromSubscriptionList(wsConnection, subscriptionList, now, credential);
|
||||
for (const auto& sendString : sendStringList) {
|
||||
CCAPI_LOGGER_INFO("sendString = " + sendString);
|
||||
ErrorCode ec;
|
||||
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
void processMarketDataMessageList(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessage, const TimePoint& timeReceived,
|
||||
Event& event, std::vector<MarketDataMessage>& marketDataMessageList) {
|
||||
CCAPI_LOGGER_TRACE("marketDataMessageList = " + toString(marketDataMessageList));
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
for (auto& marketDataMessage : marketDataMessageList) {
|
||||
if (marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH ||
|
||||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE ||
|
||||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE) {
|
||||
if (this->sessionOptions.warnLateEventMaxMilliSeconds > 0 &&
|
||||
std::chrono::duration_cast<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));
|
||||
std::string& channelId =
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
|
||||
std::string& symbolId =
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID);
|
||||
auto& field = this->fieldByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
|
||||
CCAPI_LOGGER_TRACE("this->optionMapByConnectionIdChannelIdSymbolIdMap = " + toString(this->optionMapByConnectionIdChannelIdSymbolIdMap));
|
||||
CCAPI_LOGGER_TRACE("wsConnection = " + toString(wsConnection));
|
||||
CCAPI_LOGGER_TRACE("channelId = " + toString(channelId));
|
||||
CCAPI_LOGGER_TRACE("symbolId = " + toString(symbolId));
|
||||
auto& optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
|
||||
CCAPI_LOGGER_TRACE("optionMap = " + toString(optionMap));
|
||||
auto& correlationIdList = this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
|
||||
CCAPI_LOGGER_TRACE("correlationIdList = " + toString(correlationIdList));
|
||||
if (marketDataMessage.data.find(MarketDataMessage::DataType::BID) != marketDataMessage.data.end() ||
|
||||
marketDataMessage.data.find(MarketDataMessage::DataType::ASK) != marketDataMessage.data.end()) {
|
||||
std::map<Decimal, std::string>& snapshotBid = this->snapshotBidByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
|
||||
std::map<Decimal, std::string>& snapshotAsk = this->snapshotAskByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
|
||||
if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] &&
|
||||
marketDataMessage.recapType == MarketDataMessage::RecapType::NONE) {
|
||||
this->processOrderBookUpdate(wsConnection, channelId, symbolId, event, marketDataMessage.tp, timeReceived, marketDataMessage.data, field, optionMap,
|
||||
correlationIdList, snapshotBid, snapshotAsk);
|
||||
if (this->sessionOptions.enableCheckOrderBookChecksum &&
|
||||
this->orderBookChecksumByConnectionIdSymbolIdMap.find(wsConnection.id) != this->orderBookChecksumByConnectionIdSymbolIdMap.end() &&
|
||||
this->orderBookChecksumByConnectionIdSymbolIdMap.at(wsConnection.id).find(symbolId) !=
|
||||
this->orderBookChecksumByConnectionIdSymbolIdMap.at(wsConnection.id).end()) {
|
||||
bool shouldProcessRemainingMessage = true;
|
||||
std::string receivedOrderBookChecksumStr = this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId];
|
||||
if (!this->checkOrderBookChecksum(snapshotBid, snapshotAsk, receivedOrderBookChecksumStr, shouldProcessRemainingMessage)) {
|
||||
CCAPI_LOGGER_ERROR("snapshotBid = " + toString(snapshotBid));
|
||||
CCAPI_LOGGER_ERROR("snapshotAsk = " + toString(snapshotAsk));
|
||||
this->onIncorrectStatesFound(wsConnectionPtr, textMessage, timeReceived, exchangeSubscriptionId, "order book incorrect checksum found");
|
||||
}
|
||||
if (!shouldProcessRemainingMessage) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (this->sessionOptions.enableCheckOrderBookCrossed) {
|
||||
bool shouldProcessRemainingMessage = true;
|
||||
if (!this->checkOrderBookCrossed(snapshotBid, snapshotAsk, shouldProcessRemainingMessage)) {
|
||||
CCAPI_LOGGER_ERROR("lastNToString(snapshotBid, 1) = " + lastNToString(snapshotBid, 1));
|
||||
CCAPI_LOGGER_ERROR("firstNToString(snapshotAsk, 1) = " + firstNToString(snapshotAsk, 1));
|
||||
this->onIncorrectStatesFound(wsConnectionPtr, textMessage, timeReceived, exchangeSubscriptionId, "order book crossed market found");
|
||||
}
|
||||
if (!shouldProcessRemainingMessage) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else if (marketDataMessage.recapType == MarketDataMessage::RecapType::SOLICITED) {
|
||||
this->processOrderBookInitial(wsConnection, channelId, symbolId, event, marketDataMessage.tp, timeReceived, marketDataMessage.data, field,
|
||||
optionMap, correlationIdList, snapshotBid, snapshotAsk);
|
||||
}
|
||||
CCAPI_LOGGER_TRACE("snapshotBid.size() = " + toString(snapshotBid.size()));
|
||||
CCAPI_LOGGER_TRACE("snapshotAsk.size() = " + toString(snapshotAsk.size()));
|
||||
}
|
||||
if (marketDataMessage.data.find(MarketDataMessage::DataType::TRADE) != marketDataMessage.data.end() ||
|
||||
marketDataMessage.data.find(MarketDataMessage::DataType::AGG_TRADE) != marketDataMessage.data.end()) {
|
||||
bool isSolicited = marketDataMessage.recapType == MarketDataMessage::RecapType::SOLICITED;
|
||||
this->processTrade(wsConnection, channelId, symbolId, event, marketDataMessage.tp, timeReceived, marketDataMessage.data, field, optionMap,
|
||||
correlationIdList, isSolicited);
|
||||
}
|
||||
} else {
|
||||
CCAPI_LOGGER_WARN("websocket event type is unknown for " + toString(marketDataMessage));
|
||||
CCAPI_LOGGER_WARN("textMessage is " + std::string(textMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessage, const TimePoint& timeReceived) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
if (this->correlationIdByConnectionIdMap.find(wsConnectionPtr->id) == this->correlationIdByConnectionIdMap.end()) {
|
||||
Event event;
|
||||
std::vector<MarketDataMessage> marketDataMessageList;
|
||||
this->processTextMessage(wsConnectionPtr, textMessage, timeReceived, event, marketDataMessageList);
|
||||
if (!marketDataMessageList.empty()) {
|
||||
this->processMarketDataMessageList(wsConnectionPtr, textMessage, timeReceived, event, marketDataMessageList);
|
||||
}
|
||||
if (!event.getMessageList().empty()) {
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
} else {
|
||||
Event event;
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
Message message;
|
||||
message.setType(Message::Type::GENERIC_PUBLIC_SUBSCRIPTION);
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList({this->correlationIdByConnectionIdMap.at(wsConnectionPtr->id)});
|
||||
Element element;
|
||||
element.insert(CCAPI_WEBSOCKET_MESSAGE_PAYLOAD, std::string(textMessage));
|
||||
message.setElementList({element});
|
||||
event.setMessageList({message});
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, wsConnectionPtr, timeReceived);
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
virtual void onIncorrectStatesFound(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessage, const TimePoint& timeReceived,
|
||||
const std::string& exchangeSubscriptionId, std::string const& reason) {
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
std::string errorMessage = "incorrect states found: connection = " + toString(wsConnection) + ", textMessage = " + std::string(textMessage) +
|
||||
", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", exchangeSubscriptionId = " + exchangeSubscriptionId +
|
||||
", reason = " + reason;
|
||||
CCAPI_LOGGER_ERROR(errorMessage);
|
||||
ErrorCode ec;
|
||||
this->close(wsConnectionPtr, beast::websocket::close_code::normal,
|
||||
beast::websocket::close_reason(beast::websocket::close_code::normal, "incorrect states found: " + reason), ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, "shutdown");
|
||||
}
|
||||
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false;
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, errorMessage);
|
||||
}
|
||||
void connect(std::shared_ptr<WsConnection> wsConnectionPtr) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
Service::connect(wsConnectionPtr);
|
||||
this->instrumentGroupByWsConnectionIdMap.insert(std::pair<std::string, std::string>(wsConnectionPtr->id, wsConnectionPtr->group));
|
||||
CCAPI_LOGGER_DEBUG("this->instrumentGroupByWsConnectionIdMap = " + toString(this->instrumentGroupByWsConnectionIdMap));
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
auto now = UtilTime::now();
|
||||
Service::onOpen(wsConnectionPtr);
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
auto credential = wsConnection.credential;
|
||||
if (!credential.empty()) {
|
||||
this->logonToExchange(wsConnectionPtr, now, credential);
|
||||
} else {
|
||||
this->startSubscribe(wsConnectionPtr);
|
||||
}
|
||||
}
|
||||
void onFail_(std::shared_ptr<WsConnection> wsConnectionPtr) override {
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
Service::onFail_(wsConnectionPtr);
|
||||
this->instrumentGroupByWsConnectionIdMap.erase(thisWsConnection.id);
|
||||
}
|
||||
void clearStates(std::shared_ptr<WsConnection> wsConnectionPtr) override {
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
Service::clearStates(wsConnectionPtr);
|
||||
this->fieldByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->optionMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->subscriptionListByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id);
|
||||
this->snapshotBidByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->snapshotAskByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->previousConflateSnapshotBidByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->previousConflateSnapshotAskByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->processedInitialTradeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->previousConflateTimeMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
if (this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.end()) {
|
||||
for (const auto& x : this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
|
||||
for (const auto& y : x.second) {
|
||||
y.second->cancel();
|
||||
}
|
||||
}
|
||||
this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
}
|
||||
this->openByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->highByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->lowByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->closeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->orderBookChecksumByConnectionIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.erase(wsConnection.id);
|
||||
if (this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.find(wsConnection.id) !=
|
||||
this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.end()) {
|
||||
for (const auto& x : this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id)) {
|
||||
x.second->cancel();
|
||||
}
|
||||
this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id);
|
||||
}
|
||||
this->orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id);
|
||||
}
|
||||
virtual void onClose(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode ec) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
|
||||
this->exchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
|
||||
this->instrumentGroupByWsConnectionIdMap.erase(wsConnection.id);
|
||||
this->correlationIdByConnectionIdMap.erase(wsConnection.id);
|
||||
Service::onClose(wsConnectionPtr, ec);
|
||||
}
|
||||
virtual void subscribeToExchange(std::shared_ptr<WsConnection> wsConnectionPtr) {
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
CCAPI_LOGGER_INFO("exchange is " + this->exchangeName);
|
||||
std::vector<std::string> sendStringList;
|
||||
if (this->correlationIdByConnectionIdMap.find(wsConnection.id) == this->correlationIdByConnectionIdMap.end()) {
|
||||
sendStringList = this->createSendStringList(wsConnection);
|
||||
} else {
|
||||
auto subscription = wsConnection.subscriptionList.at(0);
|
||||
sendStringList = std::vector<std::string>(1, subscription.getRawOptions());
|
||||
}
|
||||
for (const auto& sendString : sendStringList) {
|
||||
CCAPI_LOGGER_INFO("sendString = " + sendString);
|
||||
ErrorCode ec;
|
||||
this->send(wsConnectionPtr, sendString, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
}
|
||||
}
|
||||
void startSubscribe(std::shared_ptr<WsConnection> wsConnectionPtr) {
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
auto instrumentGroup = wsConnection.group;
|
||||
for (const auto& subscription : wsConnection.subscriptionList) {
|
||||
auto instrument = subscription.getInstrument();
|
||||
this->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup][instrument] = Subscription::Status::SUBSCRIBING;
|
||||
if (subscription.getRawOptions().empty()) {
|
||||
this->prepareSubscription(wsConnection, subscription);
|
||||
} else {
|
||||
this->correlationIdByConnectionIdMap.insert({wsConnection.id, subscription.getCorrelationId()});
|
||||
}
|
||||
}
|
||||
CCAPI_LOGGER_INFO("about to subscribe to exchange");
|
||||
this->subscribeToExchange(wsConnectionPtr);
|
||||
}
|
||||
virtual void logonToExchange(std::shared_ptr<WsConnection> wsConnectionPtr, const TimePoint& now, const std::map<std::string, std::string>& credential) {
|
||||
WsConnection& wsConnection = *wsConnectionPtr;
|
||||
CCAPI_LOGGER_INFO("about to logon to exchange");
|
||||
CCAPI_LOGGER_INFO("exchange is " + this->exchangeName);
|
||||
auto subscriptionList = wsConnection.subscriptionList;
|
||||
std::vector<std::string> sendStringList = this->createSendStringListFromSubscriptionList(wsConnection, subscriptionList, now, credential);
|
||||
for (const auto& sendString : sendStringList) {
|
||||
CCAPI_LOGGER_INFO("sendString = " + sendString);
|
||||
ErrorCode ec;
|
||||
this->send(wsConnectionPtr, sendString, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
void updateOrderBook(std::map<Decimal, std::string>& snapshot, const Decimal& price, const std::string& size, bool sizeMayHaveTrailingZero = false) {
|
||||
auto it = snapshot.find(price);
|
||||
if (it == snapshot.end()) {
|
||||
if ((!sizeMayHaveTrailingZero && size != "0") ||
|
||||
@@ -308,11 +776,11 @@ class MarketDataService : public Service {
|
||||
int i2 = 0;
|
||||
std::map<Decimal, std::string> output;
|
||||
while (i1 < maxMarketDepth && i2 < maxMarketDepth && it1 != c1.rend() && it2 != c2.rend()) {
|
||||
if (it1->first < it2->first) {
|
||||
if (it1->first > it2->first) {
|
||||
output.insert(std::make_pair(it1->first, it1->second));
|
||||
++it1;
|
||||
++i1;
|
||||
} else if (it1->first > it2->first) {
|
||||
} else if (it1->first < it2->first) {
|
||||
output.insert(std::make_pair(it2->first, "0"));
|
||||
++it2;
|
||||
++i2;
|
||||
@@ -851,20 +1319,6 @@ class MarketDataService : public Service {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
virtual void onIncorrectStatesFound(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
|
||||
const std::string& exchangeSubscriptionId, std::string const& reason) {
|
||||
std::string errorMessage = "incorrect states found: connection = " + toString(wsConnection) + ", textMessage = " + textMessage +
|
||||
", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", exchangeSubscriptionId = " + exchangeSubscriptionId +
|
||||
", reason = " + reason;
|
||||
CCAPI_LOGGER_ERROR(errorMessage);
|
||||
ErrorCode ec;
|
||||
this->close(wsConnection, hdl, websocketpp::close::status::normal, "incorrect states found: " + reason, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, "shutdown");
|
||||
}
|
||||
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false;
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, errorMessage);
|
||||
}
|
||||
int calculateMarketDepthSubscribedToExchange(int depthWanted, std::vector<int> availableMarketDepth) {
|
||||
int i = ceilSearch(availableMarketDepth, 0, availableMarketDepth.size(), depthWanted);
|
||||
if (i < 0) {
|
||||
@@ -903,15 +1357,21 @@ class MarketDataService : public Service {
|
||||
}
|
||||
}
|
||||
if (waitMilliseconds > 0) {
|
||||
this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = this->serviceContextPtr->tlsClientPtr->set_timer(
|
||||
waitMilliseconds,
|
||||
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(waitMilliseconds)));
|
||||
timerPtr->async_wait(
|
||||
[wsConnection, channelId, symbolId, field, optionMap, correlationIdList, previousConflateTp, interval, gracePeriod, this](ErrorCode const& ec) {
|
||||
if (this->wsConnectionByIdMap.find(wsConnection.id) != this->wsConnectionByIdMap.end()) {
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", conflate timer error: " + ec.message());
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
|
||||
} else {
|
||||
if (this->wsConnectionByIdMap.at(wsConnection.id).status == WsConnection::Status::OPEN) {
|
||||
if (
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
this->wsConnectionByIdMap.at(wsConnection.id).status == WsConnection::Status::OPEN
|
||||
#else
|
||||
this->wsConnectionByIdMap.at(wsConnection.id)->status == WsConnection::Status::OPEN
|
||||
#endif
|
||||
) {
|
||||
auto conflateTp = previousConflateTp + interval;
|
||||
if (conflateTp > this->previousConflateTimeMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId)) {
|
||||
Event event;
|
||||
@@ -953,33 +1413,16 @@ class MarketDataService : public Service {
|
||||
}
|
||||
}
|
||||
});
|
||||
this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = timerPtr;
|
||||
}
|
||||
}
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
virtual void subscribeToExchange(const WsConnection& wsConnection) {
|
||||
CCAPI_LOGGER_INFO("exchange is " + this->exchangeName);
|
||||
std::vector<std::string> sendStringList;
|
||||
if (this->correlationIdByConnectionIdMap.find(wsConnection.id) == this->correlationIdByConnectionIdMap.end()) {
|
||||
sendStringList = this->createSendStringList(wsConnection);
|
||||
} else {
|
||||
auto subscription = wsConnection.subscriptionList.at(0);
|
||||
sendStringList = std::vector<std::string>(1, subscription.getRawOptions());
|
||||
}
|
||||
for (const auto& sendString : sendStringList) {
|
||||
CCAPI_LOGGER_INFO("sendString = " + sendString);
|
||||
ErrorCode ec;
|
||||
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
|
||||
}
|
||||
}
|
||||
}
|
||||
void processSuccessfulTextMessageRest(int statusCode, const Request& request, const std::string& textMessage, const TimePoint& timeReceived,
|
||||
Queue<Event>* eventQueuePtr) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
Event event;
|
||||
if (this->doesHttpBodyContainError(request, textMessage)) {
|
||||
if (this->doesHttpBodyContainError(textMessage)) {
|
||||
event.setType(Event::Type::RESPONSE);
|
||||
Message message;
|
||||
message.setType(Message::Type::RESPONSE_ERROR);
|
||||
@@ -1052,74 +1495,6 @@ class MarketDataService : public Service {
|
||||
messageList.emplace_back(std::move(message));
|
||||
event.addMessages(messageList);
|
||||
}
|
||||
void connect(WsConnection& wsConnection) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
Service::connect(wsConnection);
|
||||
this->instrumentGroupByWsConnectionIdMap.insert(std::pair<std::string, std::string>(wsConnection.id, wsConnection.group));
|
||||
CCAPI_LOGGER_DEBUG("this->instrumentGroupByWsConnectionIdMap = " + toString(this->instrumentGroupByWsConnectionIdMap));
|
||||
CCAPI_LOGGER_FUNCTION_EXIT;
|
||||
}
|
||||
void onOpen(wspp::connection_hdl hdl) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
Service::onOpen(hdl);
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
auto instrumentGroup = wsConnection.group;
|
||||
for (const auto& subscription : wsConnection.subscriptionList) {
|
||||
auto instrument = subscription.getInstrument();
|
||||
this->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup][instrument] = Subscription::Status::SUBSCRIBING;
|
||||
if (subscription.getRawOptions().empty()) {
|
||||
this->prepareSubscription(wsConnection, subscription);
|
||||
} else {
|
||||
this->correlationIdByConnectionIdMap.insert({wsConnection.id, subscription.getCorrelationId()});
|
||||
}
|
||||
}
|
||||
CCAPI_LOGGER_INFO("about to subscribe to exchange");
|
||||
this->subscribeToExchange(wsConnection);
|
||||
}
|
||||
void onFail_(WsConnection& wsConnection) override {
|
||||
WsConnection thisWsConnection = wsConnection;
|
||||
Service::onFail_(wsConnection);
|
||||
this->instrumentGroupByWsConnectionIdMap.erase(thisWsConnection.id);
|
||||
}
|
||||
void clearStates(WsConnection& wsConnection) override {
|
||||
Service::clearStates(wsConnection);
|
||||
this->fieldByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->optionMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->subscriptionListByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id);
|
||||
this->snapshotBidByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->snapshotAskByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->previousConflateSnapshotBidByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->previousConflateSnapshotAskByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->processedInitialTradeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->previousConflateTimeMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
if (this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.end()) {
|
||||
for (const auto& x : this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
|
||||
for (const auto& y : x.second) {
|
||||
y.second->cancel();
|
||||
}
|
||||
}
|
||||
this->conflateTimerMapByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
}
|
||||
this->openByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->highByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->lowByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->closeByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
this->orderBookChecksumByConnectionIdSymbolIdMap.erase(wsConnection.id);
|
||||
}
|
||||
void onClose(wspp::connection_hdl hdl) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.erase(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]);
|
||||
this->exchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
|
||||
this->instrumentGroupByWsConnectionIdMap.erase(wsConnection.id);
|
||||
this->correlationIdByConnectionIdMap.erase(wsConnection.id);
|
||||
Service::onClose(hdl);
|
||||
}
|
||||
void convertRequestForRestGenericPublicRequest(http::request<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();
|
||||
@@ -1142,16 +1517,240 @@ class MarketDataService : public Service {
|
||||
req.prepare_payload();
|
||||
}
|
||||
}
|
||||
void processOrderBookWithVersionId(int64_t versionId, const WsConnection& wsConnection, const std::string& channelId, const std::string& symbolId,
|
||||
const std::string& exchangeSubscriptionId, const std::map<std::string, std::string>& optionMap,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList, const MarketDataMessage& marketDataMessage) {
|
||||
if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) {
|
||||
if (versionId > this->orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId)) {
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
this->orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = versionId;
|
||||
}
|
||||
} else {
|
||||
if (this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap[wsConnection.id][exchangeSubscriptionId].empty()) {
|
||||
int delayMilliSeconds = std::stoi(optionMap.at(CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS));
|
||||
if (delayMilliSeconds > 0) {
|
||||
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliSeconds)));
|
||||
timerPtr->async_wait([wsConnection, exchangeSubscriptionId, delayMilliSeconds, that = this](ErrorCode const& ec) {
|
||||
auto now = UtilTime::now();
|
||||
if (ec) {
|
||||
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
|
||||
} else {
|
||||
that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
|
||||
}
|
||||
});
|
||||
this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = timerPtr;
|
||||
} else {
|
||||
this->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
|
||||
}
|
||||
}
|
||||
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap[wsConnection.id][exchangeSubscriptionId][versionId] =
|
||||
marketDataMessage.data;
|
||||
}
|
||||
}
|
||||
void buildOrderBookInitialOnFail(const WsConnection& wsConnection, const std::string& exchangeSubscriptionId, long delayMilliSeconds) {
|
||||
auto thisDelayMilliSeconds = delayMilliSeconds * 2;
|
||||
if (thisDelayMilliSeconds > 0) {
|
||||
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(thisDelayMilliSeconds)));
|
||||
timerPtr->async_wait([wsConnection, exchangeSubscriptionId, thisDelayMilliSeconds, that = this](ErrorCode const& ec) {
|
||||
if (ec) {
|
||||
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
|
||||
} else {
|
||||
that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, thisDelayMilliSeconds);
|
||||
}
|
||||
});
|
||||
this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = timerPtr;
|
||||
} else {
|
||||
this->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, thisDelayMilliSeconds);
|
||||
}
|
||||
}
|
||||
void buildOrderBookInitial(const WsConnection& wsConnection, const std::string& exchangeSubscriptionId, long delayMilliSeconds) {
|
||||
auto now = UtilTime::now();
|
||||
http::request<http::string_body> req;
|
||||
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
|
||||
auto credential = wsConnection.credential;
|
||||
if (credential.empty()) {
|
||||
credential = this->credentialDefault;
|
||||
}
|
||||
this->createFetchOrderBookInitialReq(req, symbolId, now, credential);
|
||||
this->sendRequest(
|
||||
req,
|
||||
[wsConnection, exchangeSubscriptionId, delayMilliSeconds, that = shared_from_base<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) {
|
||||
auto timeReceived = UtilTime::now();
|
||||
int statusCode = res.result_int();
|
||||
std::string body = res.body();
|
||||
if (statusCode / 100 == 2 && !that->doesHttpBodyContainError(body)) {
|
||||
try {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
|
||||
int64_t versionId;
|
||||
that->extractOrderBookInitialVersionId(versionId, document);
|
||||
if (versionId >=
|
||||
that->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap[wsConnection.id][exchangeSubscriptionId].begin()->first) {
|
||||
const auto& channelId =
|
||||
that->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
|
||||
const auto& symbolId = that->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
|
||||
const auto& optionMap = that->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
|
||||
that->orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = versionId;
|
||||
const auto& correlationIdList = that->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
|
||||
std::map<Decimal, std::string>& snapshotBid = that->snapshotBidByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
|
||||
std::map<Decimal, std::string>& snapshotAsk = that->snapshotAskByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
|
||||
snapshotBid.clear();
|
||||
snapshotAsk.clear();
|
||||
MarketDataMessage::TypeForData input;
|
||||
that->extractOrderBookInitialData(input, document);
|
||||
for (const auto& x : input) {
|
||||
const auto& type = x.first;
|
||||
const auto& detail = x.second;
|
||||
if (type == MarketDataMessage::DataType::BID) {
|
||||
for (const auto& y : detail) {
|
||||
const auto& price = y.at(MarketDataMessage::DataFieldType::PRICE);
|
||||
const auto& size = y.at(MarketDataMessage::DataFieldType::SIZE);
|
||||
Decimal decimalPrice(price, that->sessionOptions.enableCheckOrderBookChecksum);
|
||||
snapshotBid.emplace(std::move(decimalPrice), std::move(size));
|
||||
}
|
||||
} else if (type == MarketDataMessage::DataType::ASK) {
|
||||
for (const auto& y : detail) {
|
||||
const auto& price = y.at(MarketDataMessage::DataFieldType::PRICE);
|
||||
const auto& size = y.at(MarketDataMessage::DataFieldType::SIZE);
|
||||
Decimal decimalPrice(price, that->sessionOptions.enableCheckOrderBookChecksum);
|
||||
snapshotAsk.emplace(std::move(decimalPrice), std::move(size));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (that->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.at(wsConnection.id).find(exchangeSubscriptionId) !=
|
||||
that->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.at(wsConnection.id).end()) {
|
||||
auto it = that->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.at(wsConnection.id)
|
||||
.at(exchangeSubscriptionId)
|
||||
.upper_bound(versionId);
|
||||
while (
|
||||
it !=
|
||||
that->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).end()) {
|
||||
const auto& input = it->second;
|
||||
for (const auto& x : input) {
|
||||
const auto& type = x.first;
|
||||
const auto& detail = x.second;
|
||||
if (type == MarketDataMessage::DataType::BID) {
|
||||
for (const auto& y : detail) {
|
||||
const auto& price = y.at(MarketDataMessage::DataFieldType::PRICE);
|
||||
const auto& size = y.at(MarketDataMessage::DataFieldType::SIZE);
|
||||
Decimal decimalPrice(price, that->sessionOptions.enableCheckOrderBookChecksum);
|
||||
that->updateOrderBook(snapshotBid, decimalPrice, size, that->sessionOptions.enableCheckOrderBookChecksum);
|
||||
}
|
||||
} else if (type == MarketDataMessage::DataType::ASK) {
|
||||
for (const auto& y : detail) {
|
||||
const auto& price = y.at(MarketDataMessage::DataFieldType::PRICE);
|
||||
const auto& size = y.at(MarketDataMessage::DataFieldType::SIZE);
|
||||
Decimal decimalPrice(price, that->sessionOptions.enableCheckOrderBookChecksum);
|
||||
that->updateOrderBook(snapshotAsk, decimalPrice, size, that->sessionOptions.enableCheckOrderBookChecksum);
|
||||
}
|
||||
}
|
||||
}
|
||||
that->orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = it->first;
|
||||
it++;
|
||||
}
|
||||
that->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap.at(wsConnection.id).erase(exchangeSubscriptionId);
|
||||
}
|
||||
Event event;
|
||||
event.setType(Event::Type::SUBSCRIPTION_DATA);
|
||||
std::vector<Element> elementList;
|
||||
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
|
||||
int bidIndex = 0;
|
||||
for (auto iter = snapshotBid.rbegin(); iter != snapshotBid.rend(); iter++) {
|
||||
if (bidIndex < maxMarketDepth) {
|
||||
Element element;
|
||||
element.insert(CCAPI_BEST_BID_N_PRICE, iter->first.toString());
|
||||
element.insert(CCAPI_BEST_BID_N_SIZE, iter->second);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
++bidIndex;
|
||||
}
|
||||
if (snapshotBid.empty()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_BEST_BID_N_PRICE, CCAPI_BEST_BID_N_PRICE_EMPTY);
|
||||
element.insert(CCAPI_BEST_BID_N_SIZE, CCAPI_BEST_BID_N_SIZE_EMPTY);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
int askIndex = 0;
|
||||
for (auto iter = snapshotAsk.begin(); iter != snapshotAsk.end(); iter++) {
|
||||
if (askIndex < maxMarketDepth) {
|
||||
Element element;
|
||||
element.insert(CCAPI_BEST_ASK_N_PRICE, iter->first.toString());
|
||||
element.insert(CCAPI_BEST_ASK_N_SIZE, iter->second);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
++askIndex;
|
||||
}
|
||||
if (snapshotAsk.empty()) {
|
||||
Element element;
|
||||
element.insert(CCAPI_BEST_ASK_N_PRICE, CCAPI_BEST_ASK_N_PRICE_EMPTY);
|
||||
element.insert(CCAPI_BEST_ASK_N_SIZE, CCAPI_BEST_ASK_N_SIZE_EMPTY);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(Message::Type::MARKET_DATA_EVENTS_MARKET_DEPTH);
|
||||
message.setRecapType(Message::RecapType::SOLICITED);
|
||||
message.setTime(timeReceived);
|
||||
message.setElementList(elementList);
|
||||
message.setCorrelationIdList(correlationIdList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
event.addMessages(messageList);
|
||||
that->eventHandler(event, nullptr);
|
||||
that->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
|
||||
} else {
|
||||
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
|
||||
// if (delayMilliSeconds > 0) {
|
||||
// that->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] =
|
||||
// that->serviceContextPtr->tlsClientPtr->set_timer(
|
||||
// delayMilliSeconds, [wsConnection, exchangeSubscriptionId, delayMilliSeconds, that](ErrorCode const& ec) {
|
||||
// if (ec) {
|
||||
// that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
|
||||
// } else {
|
||||
// that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
|
||||
// }
|
||||
// });
|
||||
// } else {
|
||||
// that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
|
||||
// }
|
||||
}
|
||||
return;
|
||||
} catch (const std::runtime_error& e) {
|
||||
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
}
|
||||
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
|
||||
// WsConnection thisWsConnection = wsConnection;
|
||||
// that->onFail_(thisWsConnection);
|
||||
},
|
||||
this->sessionOptions.httpRequestTimeoutMilliSeconds);
|
||||
}
|
||||
virtual std::vector<std::string> createSendStringListFromSubscriptionList(const WsConnection& wsConnection, const std::vector<Subscription>& subscriptionList,
|
||||
const TimePoint& now, const std::map<std::string, std::string>& credential) {
|
||||
return {};
|
||||
}
|
||||
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
|
||||
virtual void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
|
||||
Event& event, std::vector<MarketDataMessage>& marketDataMessageList) {}
|
||||
#else
|
||||
virtual void processTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived,
|
||||
Event& event, std::vector<MarketDataMessage>& marketDataMessageList) {}
|
||||
#endif
|
||||
virtual std::string calculateOrderBookChecksum(const std::map<Decimal, std::string>& snapshotBid, const std::map<Decimal, std::string>& snapshotAsk) {
|
||||
return {};
|
||||
}
|
||||
virtual std::vector<std::string> createSendStringList(const WsConnection& wsConnection) { return {}; }
|
||||
virtual void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) {}
|
||||
const Subscription& subscription, const std::map<std::string, std::string> optionMap) {}
|
||||
virtual void createFetchOrderBookInitialReq(http::request<http::string_body>& req, const std::string& symbolId, const TimePoint& now,
|
||||
const std::map<std::string, std::string>& credential) {}
|
||||
virtual void extractOrderBookInitialVersionId(int64_t& versionId, const rj::Document& document) {}
|
||||
virtual void extractOrderBookInitialData(MarketDataMessage::TypeForData& input, const rj::Document& document) {}
|
||||
std::map<std::string, std::map<std::string, std::map<std::string, std::string>>> fieldByConnectionIdChannelIdSymbolIdMap;
|
||||
std::map<std::string, std::map<std::string, std::map<std::string, std::map<std::string, std::string>>>> optionMapByConnectionIdChannelIdSymbolIdMap;
|
||||
std::map<std::string, std::map<std::string, std::map<std::string, int>>> marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap;
|
||||
@@ -1181,9 +1780,13 @@ class MarketDataService : public Service {
|
||||
std::string getInstrumentTarget;
|
||||
std::string getInstrumentsTarget;
|
||||
std::map<std::string, int> exchangeJsonPayloadIdByConnectionIdMap;
|
||||
std::map<int, std::vector<std::string>> exchangeSubscriptionIdListByExchangeJsonPayloadIdMap;
|
||||
std::map<std::string, std::map<int, std::vector<std::string>>> exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap;
|
||||
// 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>>>
|
||||
marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap;
|
||||
std::map<std::string, std::map<std::string, int64_t>> orderbookVersionIdByConnectionIdExchangeSubscriptionIdMap;
|
||||
std::map<std::string, std::map<std::string, TimerPtr>> fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceAscendex : public MarketDataService {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_ASCENDEX;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/api/pro/v1/stream";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/api/pro/v1/stream";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/api/pro/v1/trades";
|
||||
this->getInstrumentTarget = "/api/pro/v1/products";
|
||||
this->getInstrumentsTarget = "/api/pro/v1/products";
|
||||
@@ -27,9 +36,9 @@ class MarketDataServiceAscendex : public MarketDataService {
|
||||
|
||||
private:
|
||||
#endif
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; }
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; }
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
|
||||
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
if (marketDepthRequested == 1) {
|
||||
@@ -37,7 +46,7 @@ class MarketDataServiceAscendex : public MarketDataService {
|
||||
}
|
||||
}
|
||||
}
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({ "op": "ping" })", wspp::frame::opcode::text, ec); }
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); }
|
||||
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
|
||||
std::vector<std::string> sendStringList;
|
||||
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceBinance : public MarketDataServiceBinanceBase {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BINANCE_API_KEY;
|
||||
this->setupCredential({this->apiKeyName});
|
||||
this->getRecentTradesTarget = "/api/v3/trades";
|
||||
|
||||
@@ -16,9 +16,25 @@ class MarketDataServiceBinanceBase : public MarketDataService {
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
protected:
|
||||
#endif
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
void onOpen(wspp::connection_hdl hdl) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
auto now = UtilTime::now();
|
||||
Service::onOpen(hdl);
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
this->startSubscribe(wsConnection);
|
||||
}
|
||||
#else
|
||||
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override {
|
||||
CCAPI_LOGGER_FUNCTION_ENTER;
|
||||
auto now = UtilTime::now();
|
||||
Service::onOpen(wsConnectionPtr);
|
||||
this->startSubscribe(wsConnectionPtr);
|
||||
}
|
||||
#endif
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
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));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
@@ -78,7 +94,8 @@ class MarketDataServiceBinanceBase : public MarketDataService {
|
||||
}
|
||||
document.AddMember("params", params, allocator);
|
||||
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = exchangeSubscriptionIdList;
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
|
||||
exchangeSubscriptionIdList;
|
||||
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
@@ -87,8 +104,19 @@ class MarketDataServiceBinanceBase : public MarketDataService {
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
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("result") && document["result"].IsNull()) {
|
||||
@@ -99,8 +127,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->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.find(id) != this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.end()) {
|
||||
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.at(id)) {
|
||||
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
|
||||
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
|
||||
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
|
||||
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceBinanceCoinFutures : public MarketDataServiceBinanceDeriv
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceBinanceDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BINANCE_COIN_FUTURES_API_KEY;
|
||||
this->setupCredential({this->apiKeyName});
|
||||
this->getRecentTradesTarget = "/dapi/v1/trades";
|
||||
|
||||
+3
-1
@@ -17,7 +17,7 @@ class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceB
|
||||
protected:
|
||||
#endif
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
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));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
@@ -51,6 +51,8 @@ class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceB
|
||||
} else if (filterType == "LOT_SIZE") {
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, y["stepSize"].GetString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_MIN, y["minQty"].GetString());
|
||||
} else if (filterType == "MIN_NOTIONAL") {
|
||||
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, y["notional"].GetString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceBinanceUs : public MarketDataServiceBinanceBase {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_US;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BINANCE_US_API_KEY;
|
||||
this->setupCredential({this->apiKeyName});
|
||||
this->getRecentTradesTarget = "/api/v3/trades";
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceBinanceUsdsFutures : public MarketDataServiceBinanceDeriv
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceBinanceDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_BINANCE_USDS_FUTURES_API_KEY;
|
||||
this->setupCredential({this->apiKeyName});
|
||||
this->getRecentTradesTarget = "/fapi/v1/trades";
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceBitfinex : public MarketDataService {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BITFINEX;
|
||||
this->baseUrl = std::string(CCAPI_BITFINEX_PUBLIC_URL_WS_BASE) + "/ws/2";
|
||||
this->baseUrlWs = std::string(CCAPI_BITFINEX_PUBLIC_URL_WS_BASE) + "/ws/2";
|
||||
this->baseUrlRest = CCAPI_BITFINEX_PUBLIC_URL_REST_BASE;
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/v2/trades/{Symbol}/hist";
|
||||
this->getInstrumentsTarget = CCAPI_BITFINEX_GET_INSTRUMENTS_PATH;
|
||||
this->getInstrumentTarget = CCAPI_BITFINEX_GET_INSTRUMENTS_PATH;
|
||||
@@ -32,7 +41,7 @@ class MarketDataServiceBitfinex : public MarketDataService {
|
||||
this->send(hdl, "{\"cid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec);
|
||||
}
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
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));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_BITGET
|
||||
#include "ccapi_cpp/service/ccapi_market_data_service_bitget_base.h"
|
||||
namespace ccapi {
|
||||
class MarketDataServiceBitget : public MarketDataServiceBitgetBase {
|
||||
public:
|
||||
MarketDataServiceBitget(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET;
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/v1/stream";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/api/spot/v1/market/fills";
|
||||
this->getInstrumentTarget = "/api/spot/v1/public/product";
|
||||
this->getInstrumentsTarget = "/api/spot/v1/public/products";
|
||||
}
|
||||
virtual ~MarketDataServiceBitget() {}
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_H_
|
||||
@@ -0,0 +1,377 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_BASE_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_BASE_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
|
||||
#if defined(CCAPI_ENABLE_EXCHANGE_BITGET) || defined(CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES)
|
||||
#include "ccapi_cpp/service/ccapi_market_data_service.h"
|
||||
namespace ccapi {
|
||||
class MarketDataServiceBitgetBase : public MarketDataService {
|
||||
public:
|
||||
MarketDataServiceBitgetBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
|
||||
virtual ~MarketDataServiceBitgetBase() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
protected:
|
||||
#endif
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"00000\"")); }
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const Subscription& subscription, const std::map<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));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
if (this->isDerivatives) {
|
||||
if (conflateIntervalMilliSeconds < 200) {
|
||||
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS;
|
||||
} else {
|
||||
if (marketDepthRequested <= 1) {
|
||||
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1;
|
||||
} else if (marketDepthRequested <= 5) {
|
||||
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5;
|
||||
} else if (marketDepthRequested <= 15) {
|
||||
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15;
|
||||
} else {
|
||||
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (marketDepthRequested <= 5) {
|
||||
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5;
|
||||
} else if (marketDepthRequested <= 15) {
|
||||
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15;
|
||||
} else {
|
||||
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
|
||||
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
|
||||
std::vector<std::string> sendStringList;
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
|
||||
auto channelId = subscriptionListByChannelIdSymbolId.first;
|
||||
for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
|
||||
std::string symbolId = subscriptionListBySymbolId.first;
|
||||
if (channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1 || channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5 ||
|
||||
channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15) {
|
||||
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
|
||||
}
|
||||
std::string exchangeSubscriptionId = UtilString::split(channelId, "?").at(0) + ":" + symbolId;
|
||||
rj::Value arg(rj::kObjectType);
|
||||
std::string instType = this->isDerivatives ? "mc" : "sp";
|
||||
arg.AddMember("instType", rj::Value(instType.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("channel", rj::Value(channelId.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("instId", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
|
||||
args.PushBack(arg, allocator);
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
|
||||
}
|
||||
}
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
std::string calculateOrderBookChecksum(const std::map<Decimal, std::string>& snapshotBid, const std::map<Decimal, std::string>& snapshotAsk) override {
|
||||
auto i = 0;
|
||||
auto i1 = snapshotBid.rbegin();
|
||||
auto i2 = snapshotAsk.begin();
|
||||
std::vector<std::string> csData;
|
||||
while (i < 25 && (i1 != snapshotBid.rend() || i2 != snapshotAsk.end())) {
|
||||
if (i1 != snapshotBid.rend()) {
|
||||
csData.push_back(toString(i1->first));
|
||||
csData.push_back(i1->second);
|
||||
++i1;
|
||||
}
|
||||
if (i2 != snapshotAsk.end()) {
|
||||
csData.push_back(toString(i2->first));
|
||||
csData.push_back(i2->second);
|
||||
++i2;
|
||||
}
|
||||
++i;
|
||||
}
|
||||
std::string csStr = UtilString::join(csData, ":");
|
||||
uint_fast32_t csCalc = UtilAlgorithm::crc(csStr.begin(), csStr.end());
|
||||
return intToHex(csCalc);
|
||||
}
|
||||
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
if (textMessage != "pong") {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
auto it = document.FindMember("event");
|
||||
std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : "";
|
||||
// if (eventStr == "login") {
|
||||
// this->startSubscribe(wsConnection);
|
||||
// } else {
|
||||
if (!eventStr.empty()) {
|
||||
if (eventStr == "subscribe") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
std::vector<std::string> correlationIdList;
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
|
||||
const rj::Value& arg = document["arg"];
|
||||
std::string channelId = arg["channel"].GetString();
|
||||
std::string symbolId = arg["instId"].GetString();
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) {
|
||||
std::vector<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(Message::Type::SUBSCRIPTION_STARTED);
|
||||
Element element;
|
||||
element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
event.setMessageList(messageList);
|
||||
} else if (eventStr == "error") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
event.setMessageList(messageList);
|
||||
}
|
||||
} else if (document.HasMember("arg")) {
|
||||
const rj::Value& arg = document["arg"];
|
||||
std::string channelId = arg["channel"].GetString();
|
||||
std::string symbolId = arg["instId"].GetString();
|
||||
std::string exchangeSubscriptionId = channelId + ":" + symbolId;
|
||||
if (channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS || channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1 ||
|
||||
channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5 || channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15) {
|
||||
std::string action = document["action"].GetString();
|
||||
for (const auto& datum : document["data"].GetArray()) {
|
||||
if (this->sessionOptions.enableCheckOrderBookChecksum) {
|
||||
auto it = datum.FindMember("checksum");
|
||||
if (it != datum.MemberEnd()) {
|
||||
this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId] =
|
||||
intToHex(static_cast<uint_fast32_t>(static_cast<uint32_t>(std::stoi(it->value.GetString()))));
|
||||
}
|
||||
}
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString())));
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
|
||||
if (channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1 || channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5 ||
|
||||
channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15) {
|
||||
if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) {
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
} else {
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
|
||||
}
|
||||
} else {
|
||||
marketDataMessage.recapType = action == "update" ? MarketDataMessage::RecapType::NONE : MarketDataMessage::RecapType::SOLICITED;
|
||||
}
|
||||
for (const auto& x : datum["bids"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
if (this->sessionOptions.enableCheckOrderBookChecksum) {
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
|
||||
} else {
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
}
|
||||
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
for (const auto& x : datum["asks"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
if (this->sessionOptions.enableCheckOrderBookChecksum) {
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
|
||||
} else {
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
}
|
||||
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
} else if (channelId == CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_TRADES) {
|
||||
std::string action = document["action"].GetString();
|
||||
MarketDataMessage::RecapType recapType = action == "update" ? MarketDataMessage::RecapType::NONE : MarketDataMessage::RecapType::SOLICITED;
|
||||
for (const auto& datum : document["data"].GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.recapType = recapType;
|
||||
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum[0].GetString())));
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum[1].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum[2].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum[3].GetString()) == "sell" ? "1" : "0"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
// }
|
||||
}
|
||||
}
|
||||
void convertRequestForRest(http::request<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);
|
||||
std::string target;
|
||||
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");
|
||||
}
|
||||
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();
|
||||
if (this->isDerivatives) {
|
||||
this->appendParam(queryString, param,
|
||||
{
|
||||
{CCAPI_INSTRUMENT_TYPE, "productType"},
|
||||
});
|
||||
req.target(target + "?" + queryString);
|
||||
} else {
|
||||
req.target(target);
|
||||
}
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
void extractInstrumentInfo(Element& element, const rj::Value& x) {
|
||||
if (this->isDerivatives) {
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
|
||||
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
|
||||
int pricePlace = std::stoi(x["pricePlace"].GetString());
|
||||
if (pricePlace > 0) {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(pricePlace - 1, '0') + x["priceEndStep"].GetString());
|
||||
} else {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["priceEndStep"].GetString());
|
||||
}
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["sizeMultiplier"].GetString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minTradeNum"].GetString());
|
||||
} else {
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbolName"].GetString());
|
||||
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
|
||||
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
|
||||
int priceScale = std::stoi(x["priceScale"].GetString());
|
||||
if (priceScale > 0) {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(priceScale - 1, '0') + "1");
|
||||
} else {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1");
|
||||
}
|
||||
int quantityScale = std::stoi(x["quantityScale"].GetString());
|
||||
if (quantityScale > 0) {
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "0." + std::string(quantityScale - 1, '0') + "1");
|
||||
} else {
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "1");
|
||||
}
|
||||
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minTradeAmount"].GetString());
|
||||
}
|
||||
}
|
||||
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<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& datum : document["data"].GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum[this->isDerivatives ? "timestamp" : "fillTime"].GetString())));
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert(
|
||||
{MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum[this->isDerivatives ? "price" : "fillPrice"].GetString())});
|
||||
dataPoint.insert(
|
||||
{MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum[this->isDerivatives ? "size" : "fillQuantity"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, datum["tradeId"].GetString()});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "sell" ? "1" : "0"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENT: {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
for (const auto& x : document["data"].GetArray()) {
|
||||
if (std::string(x["symbol"].GetString()) == request.getInstrument()) {
|
||||
Element element;
|
||||
this->extractInstrumentInfo(element, x);
|
||||
message.setElementList({element});
|
||||
break;
|
||||
}
|
||||
}
|
||||
message.setCorrelationIdList({request.getCorrelationId()});
|
||||
event.addMessages({message});
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENTS: {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
std::vector<Element> elementList;
|
||||
for (const auto& x : document["data"].GetArray()) {
|
||||
Element element;
|
||||
this->extractInstrumentInfo(element, x);
|
||||
elementList.push_back(element);
|
||||
}
|
||||
message.setElementList(elementList);
|
||||
message.setCorrelationIdList({request.getCorrelationId()});
|
||||
event.addMessages({message});
|
||||
} break;
|
||||
default:
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
bool isDerivatives{};
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_BASE_H_
|
||||
@@ -0,0 +1,40 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_FUTURES_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_FUTURES_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_BITGET_FUTURES
|
||||
#include "ccapi_cpp/service/ccapi_market_data_service_bitget_base.h"
|
||||
namespace ccapi {
|
||||
class MarketDataServiceBitgetFutures : public MarketDataServiceBitgetBase {
|
||||
public:
|
||||
MarketDataServiceBitgetFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
std::shared_ptr<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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/api/mix/v1/market/fills";
|
||||
this->getInstrumentTarget = "/api/mix/v1/market/contracts";
|
||||
this->getInstrumentsTarget = "/api/mix/v1/market/contracts";
|
||||
this->isDerivatives = true;
|
||||
}
|
||||
virtual ~MarketDataServiceBitgetFutures() {}
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITGET_FUTURES_H_
|
||||
@@ -0,0 +1,328 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITMART_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITMART_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_BITMART
|
||||
#include "ccapi_cpp/service/ccapi_market_data_service.h"
|
||||
namespace ccapi {
|
||||
class MarketDataServiceBitmart : public MarketDataService {
|
||||
public:
|
||||
MarketDataServiceBitmart(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
std::shared_ptr<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
|
||||
this->apiKeyName = CCAPI_BITMART_API_KEY;
|
||||
this->apiSecretName = CCAPI_BITMART_API_SECRET;
|
||||
this->apiMemo = CCAPI_BITMART_API_MEMO;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiMemo});
|
||||
this->getRecentTradesTarget = "/spot/v1/symbols/trades";
|
||||
this->getInstrumentsTarget = "/spot/v1/symbols/details";
|
||||
}
|
||||
virtual ~MarketDataServiceBitmart() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
private:
|
||||
#endif
|
||||
void onClose(wspp::connection_hdl hdl) override {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
this->subscriptionStartedByConnectionIdChannelIdSymbolIdMap.erase(wsConnection.id);
|
||||
MarketDataService::onClose(hdl);
|
||||
}
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
|
||||
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
if (marketDepthRequested <= 5) {
|
||||
channelId = CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH5;
|
||||
} else if (marketDepthRequested <= 20) {
|
||||
channelId = CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH20;
|
||||
} else {
|
||||
channelId = CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH50;
|
||||
}
|
||||
}
|
||||
}
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*1000")); }
|
||||
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
|
||||
std::vector<std::string> sendStringList;
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
|
||||
auto channelId = subscriptionListByChannelIdSymbolId.first;
|
||||
for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
|
||||
std::string symbolId = subscriptionListBySymbolId.first;
|
||||
if (channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH5 || channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH20 ||
|
||||
channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH50) {
|
||||
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
|
||||
}
|
||||
std::string exchangeSubscriptionId = UtilString::split(channelId, "?").at(0) + ":" + symbolId;
|
||||
args.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
|
||||
}
|
||||
}
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
if (textMessage != "pong") {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
auto it = document.FindMember("errorCode");
|
||||
std::string errorCode = it != document.MemberEnd() ? it->value.GetString() : "";
|
||||
if (errorCode.empty()) {
|
||||
std::string channelId = document["table"].GetString();
|
||||
std::string symbolId = document["data"][0]["symbol"].GetString();
|
||||
std::string exchangeSubscriptionId = channelId + ":" + symbolId;
|
||||
if (!this->subscriptionStartedByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) {
|
||||
const auto& subscriptionList = this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
|
||||
std::vector<std::string> correlationIdList;
|
||||
for (const auto& subscription : subscriptionList) {
|
||||
correlationIdList.push_back(subscription.getCorrelationId());
|
||||
}
|
||||
Event event;
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList(correlationIdList);
|
||||
message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
Element element;
|
||||
element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
event.addMessages(messageList);
|
||||
this->eventHandler(event, nullptr);
|
||||
}
|
||||
if (channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH5 || channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH20 ||
|
||||
channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH50) {
|
||||
for (const auto& datum : document["data"].GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ms_t"].GetString())));
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
|
||||
if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) {
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
} else {
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
|
||||
}
|
||||
for (const auto& x : datum["bids"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
for (const auto& x : datum["asks"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
} else if (channelId == CCAPI_WEBSOCKET_BITMART_CHANNEL_TRADE) {
|
||||
MarketDataMessage::RecapType recapType = MarketDataMessage::RecapType::NONE;
|
||||
if (!this->subscriptionStartedByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) {
|
||||
recapType = MarketDataMessage::RecapType::SOLICITED;
|
||||
}
|
||||
for (const auto& datum : document["data"].GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.recapType = recapType;
|
||||
marketDataMessage.tp = TimePoint(std::chrono::seconds(std::stoll(datum["s_t"].GetString())));
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum["price"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum["size"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "buy" ? "1" : "0"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
}
|
||||
if (!this->subscriptionStartedByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) {
|
||||
this->subscriptionStartedByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
|
||||
}
|
||||
} else {
|
||||
std::string eventStr = document["event"].GetString();
|
||||
const auto& splitted = UtilString::split(eventStr, ':');
|
||||
if (splitted.at(0) == "subscribe") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
const auto& channelId = splitted.at(1);
|
||||
const auto& symbolId = splitted.at(2);
|
||||
const auto& subscriptionList = this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
|
||||
std::vector<std::string> correlationIdList;
|
||||
for (const auto& subscription : subscriptionList) {
|
||||
correlationIdList.push_back(subscription.getCorrelationId());
|
||||
}
|
||||
message.setCorrelationIdList(correlationIdList);
|
||||
messageList.emplace_back(std::move(message));
|
||||
event.setMessageList(messageList);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void convertRequestForRest(http::request<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, "N"},
|
||||
});
|
||||
this->appendSymbolId(queryString, symbolId, "symbol");
|
||||
req.target(target + "?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENT: {
|
||||
req.method(http::verb::get);
|
||||
auto target = this->getInstrumentsTarget;
|
||||
req.target(target);
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENTS: {
|
||||
req.method(http::verb::get);
|
||||
auto target = this->getInstrumentsTarget;
|
||||
req.target(target);
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
void extractInstrumentInfo(Element& element, const rj::Value& x) {
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
element.insert(CCAPI_BASE_ASSET, x["base_currency"].GetString());
|
||||
element.insert(CCAPI_QUOTE_ASSET, x["quote_currency"].GetString());
|
||||
int priceMaxPrecision = std::stoi(x["price_max_precision"].GetString());
|
||||
if (priceMaxPrecision > 0) {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(priceMaxPrecision - 1, '0') + "1");
|
||||
} else {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1" + std::string(-priceMaxPrecision, '0'));
|
||||
}
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, UtilString::normalizeDecimalString(x["quote_increment"].GetString()));
|
||||
element.insert(CCAPI_ORDER_QUANTITY_MIN, UtilString::normalizeDecimalString(x["base_min_size"].GetString()));
|
||||
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN,
|
||||
std::max(Decimal(x["min_buy_amount"].GetString()), Decimal(x["min_sell_amount"].GetString())).toString());
|
||||
}
|
||||
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<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& datum : document["data"]["trades"].GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["order_time"].GetString())));
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum["price"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum["count"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["type"].GetString()) == "buy" ? "1" : "0"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENT: {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
for (const auto& x : document["data"]["symbols"].GetArray()) {
|
||||
if (std::string(x["symbol"].GetString()) == request.getInstrument()) {
|
||||
Element element;
|
||||
this->extractInstrumentInfo(element, x);
|
||||
message.setElementList({element});
|
||||
break;
|
||||
}
|
||||
}
|
||||
message.setCorrelationIdList({request.getCorrelationId()});
|
||||
event.addMessages({message});
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENTS: {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
std::vector<Element> elementList;
|
||||
for (const auto& x : document["data"]["symbols"].GetArray()) {
|
||||
Element element;
|
||||
this->extractInstrumentInfo(element, x);
|
||||
elementList.push_back(element);
|
||||
}
|
||||
message.setElementList(elementList);
|
||||
message.setCorrelationIdList({request.getCorrelationId()});
|
||||
event.addMessages({message});
|
||||
} break;
|
||||
default:
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
std::vector<std::string> createSendStringListFromSubscriptionList(const WsConnection& wsConnection, const std::vector<Subscription>& subscriptionList,
|
||||
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("login").Move(), allocator);
|
||||
rj::Value arg(rj::kObjectType);
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto apiPassphrase = mapGetWithDefault(credential, this->apiMemo);
|
||||
std::string ts = std::to_string(std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count());
|
||||
arg.AddMember("apiKey", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("passphrase", rj::Value(apiPassphrase.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("timestamp", rj::Value(ts.c_str(), allocator).Move(), allocator);
|
||||
std::string signData = ts + "GET" + "/users/self/verify";
|
||||
std::string sign = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, signData));
|
||||
arg.AddMember("sign", rj::Value(sign.c_str(), allocator).Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
args.PushBack(arg, allocator);
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
std::string apiMemo;
|
||||
std::map<std::string, std::map<std::string, std::map<std::string, bool>>> subscriptionStartedByConnectionIdChannelIdSymbolIdMap;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITMART_H_
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceBitmex : public MarketDataService {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BITMEX;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/realtime";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/realtime";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/api/v1/trade";
|
||||
this->getInstrumentTarget = "/api/v1/instrument";
|
||||
this->getInstrumentsTarget = "/api/v1/instrument";
|
||||
@@ -29,15 +38,19 @@ class MarketDataServiceBitmex : public MarketDataService {
|
||||
private:
|
||||
#endif
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
|
||||
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
if (marketDepthRequested == 1) {
|
||||
channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_QUOTE;
|
||||
} else if (marketDepthRequested <= 10) {
|
||||
channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_10;
|
||||
} else if (marketDepthRequested <= 25) {
|
||||
channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_L2_25;
|
||||
if (optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS) == CCAPI_CONFLATE_INTERVAL_MILLISECONDS_DEFAULT) {
|
||||
channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_L2;
|
||||
} else {
|
||||
if (marketDepthRequested == 1) {
|
||||
channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_QUOTE;
|
||||
} else if (marketDepthRequested <= 10) {
|
||||
channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_10;
|
||||
} else if (marketDepthRequested <= 25) {
|
||||
channelId = CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_L2_25;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,15 +10,24 @@ class MarketDataServiceBitstamp : public MarketDataService {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BITSTAMP;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->enableCheckPingPongWebsocketApplicationLevel = false;
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/api/v2/transactions/{currency_pair}/"; // must have trailing slash
|
||||
this->getInstrumentTarget = "/api/v2/trading-pairs-info/";
|
||||
this->getInstrumentsTarget = "/api/v2/trading-pairs-info/";
|
||||
@@ -31,7 +40,7 @@ class MarketDataServiceBitstamp : public MarketDataService {
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
|
||||
this->send(hdl, R"({"event": "bts:heartbeat"})", wspp::frame::opcode::text, ec);
|
||||
}
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override {
|
||||
bool doesHttpBodyContainError(const std::string& body) override {
|
||||
return body.find(R"("status": "error")") != std::string::npos || body.find(R"("status":"error")") != std::string::npos;
|
||||
}
|
||||
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
|
||||
|
||||
@@ -2,36 +2,42 @@
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
|
||||
#include "ccapi_cpp/service/ccapi_market_data_service.h"
|
||||
#include "ccapi_cpp/service/ccapi_market_data_service_bybit_base.h"
|
||||
namespace ccapi {
|
||||
class MarketDataServiceBybit : public MarketDataService {
|
||||
class MarketDataServiceBybit : public MarketDataServiceBybitBase {
|
||||
public:
|
||||
MarketDataServiceBybit(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
: MarketDataServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/quote/ws/v2";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/public/v3";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
this->getRecentTradesTarget = "/spot/quote/v1/trades";
|
||||
this->getInstrumentTarget = "/spot/v1/symbols";
|
||||
this->getInstrumentsTarget = "/spot/v1/symbols";
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/spot/v3/public/quote/trades";
|
||||
this->getInstrumentsTarget = "/spot/v3/public/symbols";
|
||||
}
|
||||
virtual ~MarketDataServiceBybit() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
protected:
|
||||
#endif
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); }
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
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));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
if (marketDepthRequested == 1) {
|
||||
channelId = CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER;
|
||||
@@ -42,6 +48,12 @@ class MarketDataServiceBybit : public MarketDataService {
|
||||
}
|
||||
std::vector<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) {
|
||||
@@ -50,83 +62,93 @@ class MarketDataServiceBybit : public MarketDataService {
|
||||
if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER || channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH) {
|
||||
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
|
||||
}
|
||||
exchangeSubscriptionId += "|";
|
||||
exchangeSubscriptionId += symbolId;
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
std::string toReplace = "{symbol}";
|
||||
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), symbolId);
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
|
||||
document.AddMember("topic", rj::Value(channelId.c_str(), allocator).Move(), allocator);
|
||||
document.AddMember("event", rj::Value("sub").Move(), allocator);
|
||||
rj::Value params(rj::kObjectType);
|
||||
params.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
|
||||
params.AddMember("binary", rj::Value(false), allocator);
|
||||
document.AddMember("params", params, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
args.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
|
||||
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
|
||||
}
|
||||
}
|
||||
document.AddMember("args", args, allocator);
|
||||
document.AddMember("req_id", rj::Value(std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).c_str(), allocator).Move(), allocator);
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
|
||||
exchangeSubscriptionIdList;
|
||||
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
if (document.IsObject() && document.HasMember("code")) {
|
||||
std::string code = document["code"].GetString();
|
||||
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()) {
|
||||
std::string channelId = document["topic"].GetString();
|
||||
std::string symbolId = document["params"]["symbol"].GetString();
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) {
|
||||
std::vector<std::string> correlationIdList_2 =
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
|
||||
correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end());
|
||||
if (document.IsObject() && document.HasMember("op")) {
|
||||
std::string op = document["op"].GetString();
|
||||
if (op == "subscribe") {
|
||||
bool success = document["success"].GetBool();
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::vector<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);
|
||||
}
|
||||
message.setCorrelationIdList(correlationIdList);
|
||||
message.setType(code == "0" ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(code == "0" ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
event.setMessageList(messageList);
|
||||
} else if (document.IsObject() && document.HasMember("data")) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
std::string channelId = document["topic"].GetString();
|
||||
std::string symbolId = document["params"]["symbol"].GetString();
|
||||
std::string exchangeSubscriptionId = document["topic"].GetString();
|
||||
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
|
||||
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
|
||||
auto optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
|
||||
std::string exchangeSubscriptionId = channelId + "|" + symbolId;
|
||||
const rj::Value& data = document["data"];
|
||||
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(data["t"].GetString())));
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER) {
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
|
||||
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
|
||||
? MarketDataMessage::RecapType::NONE
|
||||
: MarketDataMessage::RecapType::SOLICITED;
|
||||
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(data["time"].GetString())));
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
{
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["bidPrice"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["bidQty"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["bp"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["bq"].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
{
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["askPrice"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["askQty"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["ap"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["aq"].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
@@ -135,8 +157,6 @@ class MarketDataServiceBybit : public MarketDataService {
|
||||
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
|
||||
? MarketDataMessage::RecapType::NONE
|
||||
: MarketDataMessage::RecapType::SOLICITED;
|
||||
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(data["t"].GetString())));
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
const char* bidsName = "b";
|
||||
int bidIndex = 0;
|
||||
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
|
||||
@@ -164,16 +184,13 @@ class MarketDataServiceBybit : public MarketDataService {
|
||||
}
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
} else if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_TRADE) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(data["t"].GetString()));
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(data["p"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(data["q"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(data["v"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, data["m"].GetBool() ? "1" : "0"});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, data["m"].GetBool() ? "0" : "1"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
@@ -199,12 +216,12 @@ class MarketDataServiceBybit : public MarketDataService {
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENT: {
|
||||
req.method(http::verb::get);
|
||||
auto target = this->getInstrumentTarget;
|
||||
auto target = this->getInstrumentsTarget;
|
||||
req.target(target);
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENTS: {
|
||||
req.method(http::verb::get);
|
||||
auto target = this->getInstrumentTarget;
|
||||
auto target = this->getInstrumentsTarget;
|
||||
req.target(target);
|
||||
} break;
|
||||
default:
|
||||
@@ -213,12 +230,12 @@ class MarketDataServiceBybit : public MarketDataService {
|
||||
}
|
||||
void extractInstrumentInfo(Element& element, const rj::Value& x) {
|
||||
element.insert(CCAPI_INSTRUMENT, x["name"].GetString());
|
||||
element.insert(CCAPI_BASE_ASSET, x["baseCurrency"].GetString());
|
||||
element.insert(CCAPI_QUOTE_ASSET, x["quoteCurrency"].GetString());
|
||||
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
|
||||
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["minPricePrecision"].GetString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["basePrecision"].GetString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minTradeQuantity"].GetString());
|
||||
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["minTradeAmount"].GetString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minTradeQty"].GetString());
|
||||
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["minTradeAmt"].GetString());
|
||||
}
|
||||
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
@@ -226,14 +243,14 @@ class MarketDataServiceBybit : public MarketDataService {
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
switch (request.getOperation()) {
|
||||
case Request::Operation::GET_RECENT_TRADES: {
|
||||
for (const auto& x : document["result"].GetArray()) {
|
||||
for (const auto& x : document["result"]["list"].GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString()));
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["qty"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, x["isBuyerMaker"].GetBool() ? "1" : "0"});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, x["isBuyerMaker"].GetString() ? "0" : "1"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
@@ -242,7 +259,7 @@ class MarketDataServiceBybit : public MarketDataService {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
for (const auto& x : document["result"].GetArray()) {
|
||||
for (const auto& x : document["result"]["list"].GetArray()) {
|
||||
if (std::string(x["name"].GetString()) == request.getInstrument()) {
|
||||
Element element;
|
||||
this->extractInstrumentInfo(element, x);
|
||||
@@ -258,7 +275,7 @@ class MarketDataServiceBybit : public MarketDataService {
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
std::vector<Element> elementList;
|
||||
for (const auto& x : document["result"].GetArray()) {
|
||||
for (const auto& x : document["result"]["list"].GetArray()) {
|
||||
Element element;
|
||||
this->extractInstrumentInfo(element, x);
|
||||
elementList.push_back(element);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_BASE_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_BASE_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
|
||||
#if defined(CCAPI_ENABLE_EXCHANGE_BYBIT) || defined(CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES)
|
||||
#include "ccapi_cpp/service/ccapi_market_data_service.h"
|
||||
namespace ccapi {
|
||||
class MarketDataServiceBybitBase : public MarketDataService {
|
||||
public:
|
||||
MarketDataServiceBybitBase(std::function<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; }
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); }
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_BASE_H_
|
||||
@@ -0,0 +1,315 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_DERIVATIVES_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_DERIVATIVES_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES
|
||||
#include "ccapi_cpp/service/ccapi_market_data_service_bybit_base.h"
|
||||
namespace ccapi {
|
||||
class MarketDataServiceBybitDerivatives : public MarketDataServiceBybitBase {
|
||||
public:
|
||||
MarketDataServiceBybitDerivatives(std::function<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(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
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_
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceCoinbase : public MarketDataService {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_COINBASE;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/products/<product-id>/trades";
|
||||
this->getInstrumentTarget = "/products/<product-id>";
|
||||
this->getInstrumentsTarget = "/products";
|
||||
@@ -65,8 +74,19 @@ class MarketDataServiceCoinbase : public MarketDataService {
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
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());
|
||||
auto type = std::string(document["type"].GetString());
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceCryptocom : public MarketDataService {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_CRYPTOCOM;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/market";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/market";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/v2/public/get-trades";
|
||||
this->getInstrumentTarget = "/v2/public/get-instruments";
|
||||
this->getInstrumentsTarget = "/v2/public/get-instruments";
|
||||
@@ -28,7 +37,7 @@ class MarketDataServiceCryptocom : public MarketDataService {
|
||||
private:
|
||||
#endif
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
|
||||
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
int marketDepthSubscribedToExchange = 1;
|
||||
@@ -162,6 +171,7 @@ class MarketDataServiceCryptocom : public MarketDataService {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::string id = it->value.GetString();
|
||||
std::string method = document["method"].GetString();
|
||||
if (method == "subscribe") {
|
||||
if (std::string(document["code"].GetString()) != "0") {
|
||||
@@ -196,18 +206,9 @@ class MarketDataServiceCryptocom : public MarketDataService {
|
||||
event.setMessageList(messageList);
|
||||
}
|
||||
} else if (method == "public/heartbeat") {
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
auto now = UtilTime::now();
|
||||
this->appendParam(document, allocator, std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count(), "public/respond-heartbeat",
|
||||
{});
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string msg = stringBuffer.GetString();
|
||||
std::string msg = R"({"id":)" + id + R"(,"method":"public/respond-heartbeat"})";
|
||||
ErrorCode ec;
|
||||
this->send(hdl, msg, wspp::frame::opcode::text, ec);
|
||||
this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec);
|
||||
if (ec) {
|
||||
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request");
|
||||
}
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceDeribit : public MarketDataService {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_DERIBIT;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/api/v2";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/api/v2";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->restTarget = "/api/v2";
|
||||
this->getRecentTradesTarget = "/public/get_last_trades_by_instrument";
|
||||
this->getInstrumentTarget = "/public/get_instrument";
|
||||
@@ -50,7 +59,7 @@ class MarketDataServiceDeribit : public MarketDataService {
|
||||
}
|
||||
}
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
|
||||
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
if (marketDepthRequested == 1) {
|
||||
|
||||
@@ -10,7 +10,7 @@ class MarketDataServiceErisx : public MarketDataService {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_ERISX;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
// this->convertNumberToStringInJsonRegex = std::regex("(\\[|,|\":)(-?\\d+\\.?\\d*)");
|
||||
}
|
||||
virtual ~MarketDataServiceErisx() {}
|
||||
@@ -19,7 +19,7 @@ class MarketDataServiceErisx : public MarketDataService {
|
||||
private:
|
||||
#endif
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
|
||||
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
if (marketDepthRequested <= 20) {
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceFtx : public MarketDataServiceFtxBase {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_FTX;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
}
|
||||
virtual ~MarketDataServiceFtx() {}
|
||||
};
|
||||
|
||||
@@ -21,7 +21,7 @@ class MarketDataServiceFtxBase : public MarketDataService {
|
||||
private:
|
||||
#endif
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
|
||||
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
if (marketDepthRequested == 1) {
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceFtxUs : public MarketDataServiceFtxBase {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_FTX_US;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
}
|
||||
virtual ~MarketDataServiceFtxUs() {}
|
||||
};
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceGateio : public MarketDataServiceGateioBase {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v4/";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v4/";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_GATEIO_API_KEY;
|
||||
this->setupCredential({this->apiKeyName});
|
||||
std::string prefix = "/api/v4";
|
||||
|
||||
@@ -21,7 +21,7 @@ class MarketDataServiceGateioBase : public MarketDataService {
|
||||
wspp::frame::opcode::text, ec);
|
||||
}
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
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));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
@@ -76,7 +76,8 @@ class MarketDataServiceGateioBase : public MarketDataService {
|
||||
document.AddMember("payload", payload, allocator);
|
||||
if (!this->isDerivatives) {
|
||||
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]
|
||||
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
|
||||
exchangeSubscriptionIdList;
|
||||
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
|
||||
}
|
||||
@@ -115,7 +116,8 @@ class MarketDataServiceGateioBase : public MarketDataService {
|
||||
std::vector<std::string> exchangeSubscriptionIdList;
|
||||
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
|
||||
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]
|
||||
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
|
||||
exchangeSubscriptionIdList;
|
||||
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
|
||||
}
|
||||
@@ -143,8 +145,11 @@ class MarketDataServiceGateioBase : public MarketDataService {
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
|
||||
int id = std::stoi(document["id"].GetString());
|
||||
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.find(id) != this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.end()) {
|
||||
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.at(id)) {
|
||||
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
|
||||
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
|
||||
auto splitted = UtilString::split(exchangeSubscriptionId, '|');
|
||||
std::string channelId = splitted.at(0);
|
||||
std::string symbolId = splitted.at(1);
|
||||
|
||||
+11
-2
@@ -10,14 +10,23 @@ class MarketDataServiceGateioPerpetualFutures : public MarketDataServiceGateioBa
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v4/ws/";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v4/ws/";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY;
|
||||
this->setupCredential({this->apiKeyName});
|
||||
std::string prefix = "/api/v4";
|
||||
@@ -33,7 +42,7 @@ class MarketDataServiceGateioPerpetualFutures : public MarketDataServiceGateioBa
|
||||
virtual ~MarketDataServiceGateioPerpetualFutures() {}
|
||||
std::string getInstrumentGroup(const Subscription& subscription) override {
|
||||
auto instrument = subscription.getInstrument();
|
||||
std::string url(this->baseUrl);
|
||||
std::string url(this->baseUrlWs);
|
||||
if (UtilString::endsWith(instrument, "_USD")) {
|
||||
url += "btc";
|
||||
} else if (UtilString::endsWith(instrument, "_USDT")) {
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceGemini : public MarketDataService {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_GEMINI;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v1/marketdata";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v1/marketdata";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/v1/trades/:symbol";
|
||||
this->getInstrumentTarget = "/v1/symbols/details/:symbol";
|
||||
this->getInstrumentsTarget = "/v1/symbols";
|
||||
@@ -28,7 +37,7 @@ class MarketDataServiceGemini : public MarketDataService {
|
||||
private:
|
||||
#endif
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
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));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
@@ -88,7 +97,7 @@ class MarketDataServiceGemini : public MarketDataService {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (type == "update") {
|
||||
if (type == "update" && !document["events"].GetArray().Empty()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.exchangeSubscriptionId = wsConnection.url;
|
||||
TimePoint time = timeReceived;
|
||||
@@ -154,7 +163,7 @@ class MarketDataServiceGemini : public MarketDataService {
|
||||
auto field = subscription.getField();
|
||||
auto parameterList = UtilString::split(this->sessionConfigs.getExchangeFieldWebsocketChannelMap().at(this->exchangeName).at(field), ",");
|
||||
std::set<std::string> parameterSet(parameterList.begin(), parameterList.end());
|
||||
std::string url = this->baseUrl + "/" + symbolId;
|
||||
std::string url = this->baseUrlWs + "/" + symbolId;
|
||||
url += "?";
|
||||
if ((parameterSet.find(CCAPI_WEBSOCKET_GEMINI_PARAMETER_BIDS) != parameterSet.end() ||
|
||||
parameterSet.find(CCAPI_WEBSOCKET_GEMINI_PARAMETER_OFFERS) != parameterSet.end())) {
|
||||
@@ -238,12 +247,19 @@ class MarketDataServiceGemini : public MarketDataService {
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENTS: {
|
||||
req.method(http::verb::get);
|
||||
req.target(this->getInstrumentTarget);
|
||||
req.target(this->getInstrumentsTarget);
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
void extractInstrumentInfo(Element& element, const rj::Value& x) {
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
element.insert(CCAPI_BASE_ASSET, x["base_currency"].GetString());
|
||||
element.insert(CCAPI_QUOTE_ASSET, x["quote_currency"].GetString());
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, Decimal(x["quote_increment"].GetString()).toString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, Decimal(x["tick_size"].GetString()).toString());
|
||||
}
|
||||
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
rj::Document document;
|
||||
@@ -268,11 +284,7 @@ class MarketDataServiceGemini : public MarketDataService {
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
Element element;
|
||||
element.insert(CCAPI_INSTRUMENT, document["symbol"].GetString());
|
||||
element.insert(CCAPI_BASE_ASSET, document["base_currency"].GetString());
|
||||
element.insert(CCAPI_QUOTE_ASSET, document["quote_currency"].GetString());
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, Decimal(document["quote_increment"].GetString()).toString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, Decimal(document["tick_size"].GetString()).toString());
|
||||
this->extractInstrumentInfo(element, document);
|
||||
message.setElementList({element});
|
||||
message.setCorrelationIdList({request.getCorrelationId()});
|
||||
event.addMessages({message});
|
||||
|
||||
@@ -10,20 +10,60 @@ class MarketDataServiceHuobi : public MarketDataServiceHuobiBase {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceHuobiBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/market/history/trade";
|
||||
this->getInstrumentTarget = "/v1/common/symbols";
|
||||
this->getInstrumentsTarget = "/v1/common/symbols";
|
||||
}
|
||||
virtual ~MarketDataServiceHuobi() {}
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find("err-code") != std::string::npos; }
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const Subscription& subscription, const std::map<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("");
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
CCAPI_LOGGER_TRACE("");
|
||||
if (conflateIntervalMilliSeconds < 100) {
|
||||
CCAPI_LOGGER_TRACE("");
|
||||
if (marketDepthRequested == 1) {
|
||||
CCAPI_LOGGER_TRACE("");
|
||||
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO;
|
||||
} else {
|
||||
CCAPI_LOGGER_TRACE("");
|
||||
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE;
|
||||
int marketDepthSubscribedToExchange = 1;
|
||||
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<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) {
|
||||
if (marketDepthRequested == 1) {
|
||||
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO;
|
||||
} else {
|
||||
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH;
|
||||
}
|
||||
} else {
|
||||
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH;
|
||||
}
|
||||
}
|
||||
}
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return body.find("err-code") != std::string::npos; }
|
||||
void convertRequestForRest(http::request<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()) {
|
||||
@@ -41,23 +81,6 @@ class MarketDataServiceHuobi : public MarketDataServiceHuobiBase {
|
||||
MarketDataServiceHuobiBase::convertRequestForRest(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
void extractInstrumentInfo(Element& element, const rj::Value& x) {
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
element.insert(CCAPI_BASE_ASSET, x["base-currency"].GetString());
|
||||
element.insert(CCAPI_QUOTE_ASSET, x["quote-currency"].GetString());
|
||||
int pricePrecision = std::stoi(x["price-precision"].GetString());
|
||||
if (pricePrecision > 0) {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(pricePrecision - 1, '0') + "1");
|
||||
} else {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1");
|
||||
}
|
||||
int amountPrecision = std::stoi(x["amount-precision"].GetString());
|
||||
if (amountPrecision > 0) {
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "0." + std::string(amountPrecision - 1, '0') + "1");
|
||||
} else {
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "1");
|
||||
}
|
||||
}
|
||||
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
switch (request.getOperation()) {
|
||||
|
||||
@@ -10,7 +10,12 @@ class MarketDataServiceHuobiBase : public MarketDataService {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->needDecompressWebsocketMessage = true;
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
ErrorCode ec = this->inflater.init(false, 31);
|
||||
#else
|
||||
this->inflater.setWindowBitsOverride(31);
|
||||
ErrorCode ec = this->inflater.init();
|
||||
#endif
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_FATAL(ec.message());
|
||||
}
|
||||
@@ -21,26 +26,17 @@ class MarketDataServiceHuobiBase : public MarketDataService {
|
||||
|
||||
protected:
|
||||
#endif
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<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));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
if (conflateIntervalMilliSeconds < 1000) {
|
||||
if (marketDepthRequested == 1) {
|
||||
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO;
|
||||
} else {
|
||||
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH;
|
||||
}
|
||||
} else {
|
||||
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH;
|
||||
}
|
||||
}
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
|
||||
auto now = UtilTime::now();
|
||||
this->send(hdl, "{\"ping\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + "}", wspp::frame::opcode::text, ec);
|
||||
}
|
||||
#else
|
||||
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override {
|
||||
auto now = UtilTime::now();
|
||||
this->send(wsConnectionPtr, "{\"ping\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + "}", ec);
|
||||
}
|
||||
#endif
|
||||
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
|
||||
std::vector<std::string> sendStringList;
|
||||
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
|
||||
@@ -59,13 +55,28 @@ class MarketDataServiceHuobiBase : public MarketDataService {
|
||||
exchangeSubscriptionId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH;
|
||||
} else if (channelId.rfind(CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL, 0) == 0) {
|
||||
exchangeSubscriptionId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL;
|
||||
} else if (channelId.rfind(CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE, 0) == 0) {
|
||||
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
|
||||
exchangeSubscriptionId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE;
|
||||
}
|
||||
std::string toReplace("$symbol");
|
||||
std::string replacement(symbolId);
|
||||
if (this->exchangeName == CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP) {
|
||||
replacement = UtilString::toUpper(replacement);
|
||||
{
|
||||
std::string toReplace("$symbol");
|
||||
std::string replacement(symbolId);
|
||||
if (this->exchangeName == CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP) {
|
||||
replacement = UtilString::toUpper(replacement);
|
||||
}
|
||||
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), replacement);
|
||||
}
|
||||
if (channelId.rfind(CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE, 0) == 0) {
|
||||
std::string toReplace("$levels");
|
||||
|
||||
CCAPI_LOGGER_TRACE("marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap=" +
|
||||
toString(marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap));
|
||||
std::string replacement(
|
||||
std::to_string(this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId)));
|
||||
|
||||
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), replacement);
|
||||
}
|
||||
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), replacement);
|
||||
document.AddMember("sub", rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
|
||||
if (this->isDerivatives) {
|
||||
document.AddMember("id", rj::Value(std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).c_str(), allocator).Move(),
|
||||
@@ -87,17 +98,28 @@ class MarketDataServiceHuobiBase : public MarketDataService {
|
||||
return sendStringList;
|
||||
}
|
||||
std::string getInstrumentGroup(const Subscription& subscription) override {
|
||||
auto url = this->baseUrl;
|
||||
auto url = this->baseUrlWs;
|
||||
auto field = subscription.getField();
|
||||
if (!this->isDerivatives) {
|
||||
if (field == CCAPI_TRADE || field == CCAPI_MARKET_DEPTH) {
|
||||
if (field == CCAPI_TRADE || field == CCAPI_MARKET_DEPTH || field == CCAPI_GENERIC_PUBLIC_SUBSCRIPTION) {
|
||||
url += "/ws";
|
||||
}
|
||||
}
|
||||
return url + "|" + field + "|" + subscription.getSerializedOptions();
|
||||
}
|
||||
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
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("ch") && document.HasMember("tick")) {
|
||||
@@ -145,6 +167,41 @@ class MarketDataServiceHuobiBase : public MarketDataService {
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
}
|
||||
} else if (std::regex_search(channelId, std::regex(CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE_REGEX))) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
|
||||
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
|
||||
? MarketDataMessage::RecapType::NONE
|
||||
: MarketDataMessage::RecapType::SOLICITED;
|
||||
const rj::Value& tick = document["tick"];
|
||||
std::string ts = document["ts"].GetString();
|
||||
ts.insert(ts.size() - 3, ".");
|
||||
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(ts));
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
int bidIndex = 0;
|
||||
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
|
||||
for (const auto& x : tick["bids"].GetArray()) {
|
||||
if (bidIndex >= maxMarketDepth) {
|
||||
break;
|
||||
}
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
++bidIndex;
|
||||
}
|
||||
int askIndex = 0;
|
||||
for (const auto& x : tick["asks"].GetArray()) {
|
||||
if (askIndex >= maxMarketDepth) {
|
||||
break;
|
||||
}
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
++askIndex;
|
||||
}
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
} else if (std::regex_search(channelId, std::regex(CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH_REGEX))) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
|
||||
@@ -209,7 +266,11 @@ class MarketDataServiceHuobiBase : public MarketDataService {
|
||||
payload += document["ping"].GetString();
|
||||
payload += "}";
|
||||
ErrorCode ec;
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
this->send(hdl, payload, wspp::frame::opcode::text, ec);
|
||||
#else
|
||||
this->send(wsConnectionPtr, payload, ec);
|
||||
#endif
|
||||
if (ec) {
|
||||
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "pong");
|
||||
}
|
||||
@@ -266,6 +327,7 @@ class MarketDataServiceHuobiBase : public MarketDataService {
|
||||
}
|
||||
}
|
||||
void extractInstrumentInfo(Element& element, const rj::Value& x) {
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
element.insert(CCAPI_BASE_ASSET, x["base-currency"].GetString());
|
||||
element.insert(CCAPI_QUOTE_ASSET, x["quote-currency"].GetString());
|
||||
int pricePrecision = std::stoi(x["price-precision"].GetString());
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceHuobiCoinSwap : public MarketDataServiceHuobiDerivativesB
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceHuobiDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/swap-ws";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/swap-ws";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = CCAPI_HUOBI_COIN_SWAP_GET_RECENT_TRADES_PATH;
|
||||
this->getInstrumentTarget = "/swap-api/v1/swap_contract_info";
|
||||
this->getInstrumentsTarget = "/swap-api/v1/swap_contract_info";
|
||||
|
||||
@@ -12,7 +12,23 @@ class MarketDataServiceHuobiDerivativesBase : public MarketDataServiceHuobiBase
|
||||
this->isDerivatives = true;
|
||||
}
|
||||
virtual ~MarketDataServiceHuobiDerivativesBase() {}
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find("err_code") != std::string::npos; }
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const Subscription& subscription, const std::map<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));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
if (conflateIntervalMilliSeconds < 1000) {
|
||||
if (marketDepthRequested == 1) {
|
||||
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO;
|
||||
} else {
|
||||
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH;
|
||||
}
|
||||
} else {
|
||||
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH;
|
||||
}
|
||||
}
|
||||
}
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return body.find("err_code") != std::string::npos; }
|
||||
void convertRequestForRest(http::request<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()) {
|
||||
@@ -35,7 +51,7 @@ class MarketDataServiceHuobiDerivativesBase : public MarketDataServiceHuobiBase
|
||||
void extractInstrumentInfo(Element& element, const rj::Value& x) {
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, UtilString::normalizeDecimalString(x["price_tick"].GetString()));
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, UtilString::normalizeDecimalString(x["contract_size"].GetString()));
|
||||
element.insert(CCAPI_CONTRACT_SIZE, UtilString::normalizeDecimalString(x["contract_size"].GetString()));
|
||||
}
|
||||
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceHuobiUsdtSwap : public MarketDataServiceHuobiDerivativesB
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceHuobiDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/linear-swap-ws";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/linear-swap-ws";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = CCAPI_HUOBI_USDT_SWAP_GET_RECENT_TRADES_PATH;
|
||||
this->getInstrumentTarget = "/linear-swap-api/v1/swap_contract_info";
|
||||
this->getInstrumentsTarget = "/linear-swap-api/v1/swap_contract_info";
|
||||
|
||||
@@ -10,18 +10,27 @@ class MarketDataServiceKraken : public MarketDataService {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->shouldAlignSnapshot = true;
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/0/public/Trades";
|
||||
this->getInstrumentTarget = "/0/public/AssetPairs";
|
||||
this->getInstrumentsTarget = "/0/public/AssetPairs";
|
||||
this->shouldAlignSnapshot = true;
|
||||
}
|
||||
virtual ~MarketDataServiceKraken() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
@@ -32,9 +41,9 @@ class MarketDataServiceKraken : public MarketDataService {
|
||||
auto now = UtilTime::now();
|
||||
this->send(hdl, "{\"reqid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec);
|
||||
}
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return body.find(R"("error":[])") == std::string::npos; }
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("error":[])") == std::string::npos; }
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
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));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceKrakenFutures : public MarketDataService {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v1";
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v1";
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
std::string prefix("/derivatives/api/v3");
|
||||
this->getRecentTradesTarget = prefix + "/history";
|
||||
this->getInstrumentTarget = prefix + "/instruments";
|
||||
@@ -29,7 +38,7 @@ class MarketDataServiceKrakenFutures : public MarketDataService {
|
||||
private:
|
||||
#endif
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
|
||||
symbolId = UtilString::toUpper(symbolId);
|
||||
}
|
||||
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
|
||||
@@ -56,6 +65,18 @@ class MarketDataServiceKrakenFutures : public MarketDataService {
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
}
|
||||
{
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
auto& allocator = document.GetAllocator();
|
||||
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
|
||||
document.AddMember("feed", rj::Value("heartbeat").Move(), allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
}
|
||||
return sendStringList;
|
||||
}
|
||||
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
@@ -104,8 +125,8 @@ class MarketDataServiceKrakenFutures : public MarketDataService {
|
||||
}
|
||||
} else {
|
||||
std::string feed = document["feed"].GetString();
|
||||
std::string productId = document["product_id"].GetString();
|
||||
if (feed == "book" || feed == "book_snapshot") {
|
||||
std::string productId = document["product_id"].GetString();
|
||||
if (feed == "book") {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
|
||||
@@ -139,6 +160,7 @@ class MarketDataServiceKrakenFutures : public MarketDataService {
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
} else if (feed == "trade" || feed == "trade_snapshot") {
|
||||
std::string productId = document["product_id"].GetString();
|
||||
if (feed == "trade") {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
|
||||
@@ -10,24 +10,39 @@ class MarketDataServiceKucoin : public MarketDataServiceKucoinBase {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceKucoinBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
// this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_KUCOIN_API_KEY;
|
||||
this->apiSecretName = CCAPI_KUCOIN_API_SECRET;
|
||||
this->apiPassphraseName = CCAPI_KUCOIN_API_PASSPHRASE;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
|
||||
this->getRecentTradesTarget = "/api/v1/market/histories";
|
||||
this->getInstrumentTarget = "/api/v1/symbols";
|
||||
this->getInstrumentsTarget = "/api/v1/symbols";
|
||||
this->channelMarketTicker = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_TICKER;
|
||||
this->channelMarketLevel2Depth5 = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2DEPTH5;
|
||||
this->channelMarketLevel2Depth50 = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2DEPTH50;
|
||||
this->channelMarketLevel2 = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2;
|
||||
this->tickerSubject = "trade.ticker";
|
||||
this->tickerBestBidPriceKey = "bestBid";
|
||||
this->tickerBestAskPriceKey = "bestAsk";
|
||||
this->matchSubject = "trade.l3match";
|
||||
this->level2Subject = "level2";
|
||||
this->recentTradesTimeKey = "time";
|
||||
}
|
||||
virtual ~MarketDataServiceKucoin() {}
|
||||
@@ -42,6 +57,7 @@ class MarketDataServiceKucoin : public MarketDataServiceKucoinBase {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["priceIncrement"].GetString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["baseIncrement"].GetString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["baseMinSize"].GetString());
|
||||
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["quoteMinSize"].GetString());
|
||||
}
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
|
||||
@@ -14,19 +14,32 @@ class MarketDataServiceKucoinBase : public MarketDataService {
|
||||
|
||||
protected:
|
||||
#endif
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override {
|
||||
return !std::regex_search(body, std::regex("\"code\":\\s*\"200000\""));
|
||||
}
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"200000\"")); }
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
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));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
if (marketDepthRequested == 1) {
|
||||
channelId = this->channelMarketTicker;
|
||||
} else if (marketDepthRequested <= 5) {
|
||||
channelId = this->channelMarketLevel2Depth5;
|
||||
if (this->isDerivatives) {
|
||||
if (marketDepthRequested == 1) {
|
||||
channelId = this->channelMarketTicker;
|
||||
} else if (marketDepthRequested <= 5) {
|
||||
channelId = this->channelMarketLevel2Depth5;
|
||||
} else {
|
||||
channelId = this->channelMarketLevel2Depth50;
|
||||
}
|
||||
} else {
|
||||
channelId = this->channelMarketLevel2Depth50;
|
||||
// if (conflateIntervalMilliSeconds < 100) {
|
||||
// channelId = this->channelMarketLevel2;
|
||||
// }else{
|
||||
if (marketDepthRequested == 1) {
|
||||
channelId = this->channelMarketTicker;
|
||||
} else if (marketDepthRequested <= 5) {
|
||||
channelId = this->channelMarketLevel2Depth5;
|
||||
} else {
|
||||
channelId = this->channelMarketLevel2Depth50;
|
||||
}
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,7 +128,8 @@ class MarketDataServiceKucoinBase : public MarketDataService {
|
||||
for (const auto& symbol : symbolList) {
|
||||
exchangeSubscriptionIdList.push_back(topic + ":" + symbol);
|
||||
}
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = exchangeSubscriptionIdList;
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
|
||||
exchangeSubscriptionIdList;
|
||||
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
|
||||
document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
@@ -126,6 +140,55 @@ class MarketDataServiceKucoinBase : public MarketDataService {
|
||||
}
|
||||
return sendStringList;
|
||||
}
|
||||
void createFetchOrderBookInitialReq(http::request<http::string_body>& req, const std::string& symbolId, const TimePoint& now,
|
||||
const std::map<std::string, std::string>& credential) override {
|
||||
req.set(http::field::host, this->hostRest);
|
||||
req.method(http::verb::get);
|
||||
req.target("/api/v3/market/orderbook/level2?symbol=" + Url::urlEncode(symbolId));
|
||||
this->prepareReq(req, now, credential);
|
||||
this->signRequest(req, "", credential);
|
||||
}
|
||||
void prepareReq(http::request<http::string_body>& req, const TimePoint& now, const std::map<std::string, std::string>& credential) {
|
||||
req.set(beast::http::field::content_type, "application/json");
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
req.set("KC-API-KEY", apiKey);
|
||||
req.set("KC-API-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
|
||||
req.set("KC-API-KEY-VERSION", "2");
|
||||
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
this->signApiPassphrase(req, apiPassphrase, apiSecret);
|
||||
}
|
||||
void signRequest(http::request<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("KC-API-TIMESTAMP").to_string();
|
||||
preSignedText += std::string(req.method_string());
|
||||
preSignedText += req.target().to_string();
|
||||
preSignedText += body;
|
||||
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText));
|
||||
req.set("KC-API-SIGN", signature);
|
||||
req.body() = body;
|
||||
req.prepare_payload();
|
||||
}
|
||||
void signApiPassphrase(http::request<http::string_body>& req, const std::string& apiPassphrase, const std::string& apiSecret) {
|
||||
req.set("KC-API-PASSPHRASE", UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, apiPassphrase)));
|
||||
}
|
||||
void extractOrderBookInitialVersionId(int64_t& versionId, const rj::Document& document) override {
|
||||
versionId = std::stoll(document["data"]["sequence"].GetString());
|
||||
}
|
||||
void extractOrderBookInitialData(MarketDataMessage::TypeForData& input, const rj::Document& document) override {
|
||||
for (const auto& x : document["data"]["bids"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
input[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
for (const auto& x : document["data"]["asks"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
input[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
}
|
||||
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
rj::Document document;
|
||||
@@ -135,7 +198,42 @@ class MarketDataServiceKucoinBase : public MarketDataService {
|
||||
if (it != document.MemberEnd()) {
|
||||
std::string type = it->value.GetString();
|
||||
if (type == "message") {
|
||||
if (std::string(document["subject"].GetString()) == this->tickerSubject) {
|
||||
if (std::string(document["subject"].GetString()) == "trade.l2update") {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
|
||||
std::string exchangeSubscriptionId = document["topic"].GetString();
|
||||
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
|
||||
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
|
||||
const auto& optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
const auto& data = document["data"];
|
||||
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(data["time"].GetString()));
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
const auto& changes = data["changes"];
|
||||
const auto& itAsks = changes.FindMember("asks");
|
||||
if (itAsks != changes.MemberEnd()) {
|
||||
const rj::Value& asks = itAsks->value;
|
||||
for (auto& x : asks.GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
}
|
||||
const auto& itBids = data.FindMember("changes");
|
||||
if (itBids != changes.MemberEnd()) {
|
||||
const rj::Value& bids = itBids->value;
|
||||
for (auto& x : bids.GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
}
|
||||
int64_t versionId = std::stoll(data["sequenceEnd"].GetString());
|
||||
this->processOrderBookWithVersionId(versionId, wsConnection, channelId, symbolId, exchangeSubscriptionId, optionMap, marketDataMessageList,
|
||||
marketDataMessage);
|
||||
} else if (std::string(document["subject"].GetString()) == this->tickerSubject) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
std::string exchangeSubscriptionId = document["topic"].GetString();
|
||||
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
|
||||
@@ -163,7 +261,7 @@ class MarketDataServiceKucoinBase : public MarketDataService {
|
||||
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
} else if (std::string(document["subject"].GetString()) == "level2") {
|
||||
} else if (std::string(document["subject"].GetString()) == this->level2Subject) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
std::string exchangeSubscriptionId = document["topic"].GetString();
|
||||
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
|
||||
@@ -223,7 +321,9 @@ class MarketDataServiceKucoinBase : public MarketDataService {
|
||||
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
|
||||
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1;
|
||||
}
|
||||
MarketDataService::onOpen(hdl);
|
||||
Service::onOpen(hdl);
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
this->startSubscribe(wsConnection);
|
||||
} else if (type == "pong") {
|
||||
auto now = UtilTime::now();
|
||||
this->lastPongTpByMethodByConnectionIdMap[wsConnection.id][PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = now;
|
||||
@@ -236,8 +336,11 @@ class MarketDataServiceKucoinBase : public MarketDataService {
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
|
||||
int id = std::stoi(document["id"].GetString());
|
||||
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.find(id) != this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.end()) {
|
||||
auto exchangeSubscriptionIdList = this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.at(id);
|
||||
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
|
||||
auto exchangeSubscriptionIdList = this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id);
|
||||
for (const auto& exchangeSubscriptionId : exchangeSubscriptionIdList) {
|
||||
auto splitted = UtilString::split(exchangeSubscriptionId, ":");
|
||||
auto channelId = splitted.at(0);
|
||||
@@ -361,11 +464,14 @@ class MarketDataServiceKucoinBase : public MarketDataService {
|
||||
std::string channelMarketTicker;
|
||||
std::string channelMarketLevel2Depth5;
|
||||
std::string channelMarketLevel2Depth50;
|
||||
std::string channelMarketLevel2;
|
||||
std::string tickerSubject;
|
||||
std::string tickerBestBidPriceKey;
|
||||
std::string tickerBestAskPriceKey;
|
||||
std::string matchSubject;
|
||||
std::string recentTradesTimeKey;
|
||||
std::string level2Subject;
|
||||
std::string apiPassphraseName;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
|
||||
@@ -10,14 +10,23 @@ class MarketDataServiceKucoinFutures : public MarketDataServiceKucoinBase {
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataServiceKucoinBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
// this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->getRecentTradesTarget = "/api/v1/trade/history";
|
||||
this->getInstrumentTarget = "/api/v1/contracts/active";
|
||||
this->getInstrumentsTarget = "/api/v1/contracts/active";
|
||||
@@ -29,6 +38,7 @@ class MarketDataServiceKucoinFutures : public MarketDataServiceKucoinBase {
|
||||
this->tickerBestBidPriceKey = "bestBidPrice";
|
||||
this->tickerBestAskPriceKey = "bestAskPrice";
|
||||
this->matchSubject = "match";
|
||||
this->level2Subject = "level2";
|
||||
this->recentTradesTimeKey = "ts";
|
||||
}
|
||||
virtual ~MarketDataServiceKucoinFutures() {}
|
||||
@@ -41,6 +51,7 @@ class MarketDataServiceKucoinFutures : public MarketDataServiceKucoinBase {
|
||||
element.insert(CCAPI_UNDERLYING_SYMBOL, x["indexSymbol"].GetString());
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["tickSize"].GetString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSize"].GetString());
|
||||
element.insert(CCAPI_CONTRACT_MULTIPLIER, x["multiplier"].GetString());
|
||||
}
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_MEXC_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_MEXC_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_MEXC
|
||||
#include "ccapi_cpp/service/ccapi_market_data_service.h"
|
||||
namespace ccapi {
|
||||
class MarketDataServiceMexc : public MarketDataService {
|
||||
public:
|
||||
MarketDataServiceMexc(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
std::shared_ptr<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
|
||||
this->getRecentTradesTarget = "/api/v3/trades";
|
||||
this->getRecentAggTradesTarget = "/api/v3/aggTrades";
|
||||
this->getInstrumentsTarget = "/api/v3/exchangeInfo";
|
||||
}
|
||||
virtual ~MarketDataServiceMexc() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
protected:
|
||||
#endif
|
||||
// bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; }
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
this->send(hdl, R"({"id":)" + std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]) + R"(,"method":"PING"})",
|
||||
wspp::frame::opcode::text, ec);
|
||||
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
|
||||
}
|
||||
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
|
||||
std::vector<std::string> sendStringList;
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
document.AddMember("method", rj::Value("SUBSCRIPTION").Move(), allocator);
|
||||
rj::Value params(rj::kArrayType);
|
||||
std::vector<std::string> exchangeSubscriptionIdList;
|
||||
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
|
||||
auto channelId = subscriptionListByChannelIdSymbolId.first;
|
||||
for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
|
||||
auto symbolId = subscriptionListByInstrument.first;
|
||||
auto exchangeSubscriptionId = channelId + "@" + subscriptionListByInstrument.first;
|
||||
params.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
|
||||
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
|
||||
}
|
||||
}
|
||||
document.AddMember("params", params, allocator);
|
||||
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
|
||||
exchangeSubscriptionIdList;
|
||||
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
void createFetchOrderBookInitialReq(http::request<http::string_body>& req, const std::string& symbolId, const TimePoint& now,
|
||||
const std::map<std::string, std::string>& credential) override {
|
||||
req.set(http::field::host, this->hostRest);
|
||||
req.method(http::verb::get);
|
||||
req.target("/api/v3/depth?symbol=" + Url::urlEncode(symbolId) + "&limit=5000");
|
||||
}
|
||||
void extractOrderBookInitialVersionId(int64_t& versionId, const rj::Document& document) override {
|
||||
versionId = std::stoll(document["lastUpdateId"].GetString());
|
||||
}
|
||||
void extractOrderBookInitialData(MarketDataMessage::TypeForData& input, const rj::Document& document) override {
|
||||
for (const auto& x : document["bids"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
input[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
for (const auto& x : document["asks"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
input[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
}
|
||||
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
if (document.IsObject() && document.HasMember("code") && std::string(document["code"].GetString()) == "0") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::vector<Message> messageList;
|
||||
std::vector<std::string> correlationIdListSuccess, correlationIdListFailure;
|
||||
std::string msg = document["msg"].GetString();
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
|
||||
int id = std::stoi(document["id"].GetString());
|
||||
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
|
||||
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
|
||||
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
|
||||
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) {
|
||||
std::vector<std::string> correlationIdList_2 =
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
|
||||
for (const auto& correlationId : correlationIdList_2) {
|
||||
if (exchangeSubscriptionId == msg) {
|
||||
correlationIdListSuccess.push_back(correlationId);
|
||||
} else {
|
||||
correlationIdListFailure.push_back(correlationId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!correlationIdListSuccess.empty()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList(correlationIdListSuccess);
|
||||
message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
Element element;
|
||||
element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
if (!correlationIdListFailure.empty()) {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setCorrelationIdList(correlationIdListFailure);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
event.setMessageList(messageList);
|
||||
} else if (document.IsObject() && document.HasMember("c") && document.HasMember("d")) {
|
||||
std::string exchangeSubscriptionId = document["c"].GetString();
|
||||
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
|
||||
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
|
||||
const auto& optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
|
||||
const auto& correlationIdList = this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
|
||||
const rj::Value& data = document["d"];
|
||||
if (channelId == CCAPI_WEBSOCKET_MEXC_CHANNEL_DIFF_DEPTH) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(document["t"].GetString()));
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
const auto& itAsks = data.FindMember("asks");
|
||||
if (itAsks != data.MemberEnd()) {
|
||||
const rj::Value& asks = itAsks->value;
|
||||
for (auto& x : asks.GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x["p"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x["v"].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
}
|
||||
const auto& itBids = data.FindMember("bids");
|
||||
if (itBids != data.MemberEnd()) {
|
||||
const rj::Value& bids = itBids->value;
|
||||
for (auto& x : bids.GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x["p"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x["v"].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
}
|
||||
int64_t versionId = std::stoll(document["d"]["r"].GetString());
|
||||
this->processOrderBookWithVersionId(versionId, wsConnection, channelId, symbolId, exchangeSubscriptionId, optionMap, marketDataMessageList,
|
||||
marketDataMessage);
|
||||
} else if (channelId == CCAPI_WEBSOCKET_MEXC_CHANNEL_TRADE) {
|
||||
for (const auto& x : data["deals"].GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["t"].GetString()));
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["p"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["v"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["S"].GetString()) == "2" ? "1" : "0"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void convertRequestForRest(http::request<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_RECENT_AGG_TRADES: {
|
||||
req.method(http::verb::get);
|
||||
auto target = this->getRecentAggTradesTarget;
|
||||
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;
|
||||
std::string queryString;
|
||||
this->appendSymbolId(queryString, symbolId, "symbol");
|
||||
req.target(target + "?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENTS: {
|
||||
req.method(http::verb::get);
|
||||
auto target = this->getInstrumentsTarget;
|
||||
req.target(target);
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
void extractInstrumentInfo(Element& element, const rj::Value& x) {
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
element.insert(CCAPI_BASE_ASSET, x["baseAsset"].GetString());
|
||||
element.insert(CCAPI_QUOTE_ASSET, x["quoteAsset"].GetString());
|
||||
int quotePrecision = std::stoi(x["quotePrecision"].GetString());
|
||||
if (quotePrecision > 0) {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(quotePrecision - 1, '0') + "1");
|
||||
} else {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1" + std::string(-quotePrecision, '0'));
|
||||
}
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["baseSizePrecision"].GetString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["baseSizePrecision"].GetString());
|
||||
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["quoteAmountPrecision"].GetString());
|
||||
}
|
||||
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<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.GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString()));
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["qty"].GetString()))});
|
||||
const auto& it = x.FindMember("id");
|
||||
if (it != x.MemberEnd() && !it->value.IsNull()) {
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, it->value.GetString()});
|
||||
}
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, x["isBuyerMaker"].GetBool() ? "1" : "0"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
} break;
|
||||
case Request::Operation::GET_RECENT_AGG_TRADES: {
|
||||
for (const auto& x : document.GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE;
|
||||
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["T"].GetString()));
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["p"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["q"].GetString()))});
|
||||
const auto& it = x.FindMember("a");
|
||||
if (it != x.MemberEnd() && !it->value.IsNull()) {
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, it->value.GetString()});
|
||||
}
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, x["m"].GetBool() ? "1" : "0"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::AGG_TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENT: {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
for (const auto& x : document["symbols"].GetArray()) {
|
||||
if (std::string(x["symbol"].GetString()) == request.getInstrument()) {
|
||||
Element element;
|
||||
this->extractInstrumentInfo(element, x);
|
||||
message.setElementList({element});
|
||||
break;
|
||||
}
|
||||
}
|
||||
message.setCorrelationIdList({request.getCorrelationId()});
|
||||
event.addMessages({message});
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENTS: {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
std::vector<Element> elementList;
|
||||
for (const auto& x : document["symbols"].GetArray()) {
|
||||
Element element;
|
||||
this->extractInstrumentInfo(element, x);
|
||||
elementList.push_back(element);
|
||||
}
|
||||
message.setElementList(elementList);
|
||||
message.setCorrelationIdList({request.getCorrelationId()});
|
||||
event.addMessages({message});
|
||||
} break;
|
||||
default:
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
std::string getRecentAggTradesTarget;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_MEXC_H_
|
||||
@@ -0,0 +1,260 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_MEXC_FUTURES_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_MEXC_FUTURES_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_MEXC_FUTURES
|
||||
#include "ccapi_cpp/service/ccapi_market_data_service.h"
|
||||
namespace ccapi {
|
||||
class MarketDataServiceMexcFutures : public MarketDataService {
|
||||
public:
|
||||
MarketDataServiceMexcFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
std::shared_ptr<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
|
||||
this->getRecentTradesTarget = "/api/v1/contract/deals/{symbol}";
|
||||
this->getInstrumentsTarget = "/api/v1/contract/detail";
|
||||
}
|
||||
virtual ~MarketDataServiceMexcFutures() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
protected:
|
||||
#endif
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; }
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"method":"ping"})", wspp::frame::opcode::text, ec); }
|
||||
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
|
||||
std::vector<std::string> sendStringList;
|
||||
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
|
||||
auto channelId = subscriptionListByChannelIdSymbolId.first;
|
||||
for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
|
||||
auto symbolId = subscriptionListByInstrument.first;
|
||||
auto exchangeSubscriptionId = channelId + subscriptionListByInstrument.first;
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
document.AddMember("method", rj::Value(("sub." + channelId).c_str(), allocator).Move(), allocator);
|
||||
rj::Value param(rj::kObjectType);
|
||||
param.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
|
||||
document.AddMember("param", param, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
}
|
||||
}
|
||||
return sendStringList;
|
||||
}
|
||||
void createFetchOrderBookInitialReq(http::request<http::string_body>& req, const std::string& symbolId, const TimePoint& now,
|
||||
const std::map<std::string, std::string>& credential) override {
|
||||
req.set(http::field::host, this->hostRest);
|
||||
req.method(http::verb::get);
|
||||
req.target("/api/v1/contract/depth/" + Url::urlEncode(symbolId));
|
||||
}
|
||||
void extractOrderBookInitialVersionId(int64_t& versionId, const rj::Document& document) override {
|
||||
versionId = std::stoll(document["data"]["version"].GetString());
|
||||
}
|
||||
void extractOrderBookInitialData(MarketDataMessage::TypeForData& input, const rj::Document& document) override {
|
||||
for (const auto& x : document["data"]["bids"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
input[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
for (const auto& x : document["data"]["asks"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
input[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
}
|
||||
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
if (document.IsObject() && document.HasMember("channel")) {
|
||||
std::string channel = document["channel"].GetString();
|
||||
if (channel.rfind("push.", 0) == 0) {
|
||||
std::string channelId = channel.substr(5);
|
||||
std::string symbolId = document["symbol"].GetString();
|
||||
auto exchangeSubscriptionId = channelId + symbolId;
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
const rj::Value& data = document["data"];
|
||||
if (channelId == CCAPI_WEBSOCKET_MEXC_FUTURES_CHANNEL_DEPTH) {
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
|
||||
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(document["ts"].GetString()));
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
const auto& itAsks = data.FindMember("asks");
|
||||
if (itAsks != data.MemberEnd()) {
|
||||
const rj::Value& asks = itAsks->value;
|
||||
for (auto& x : asks.GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
}
|
||||
const auto& itBids = data.FindMember("bids");
|
||||
if (itBids != data.MemberEnd()) {
|
||||
const rj::Value& bids = itBids->value;
|
||||
for (auto& x : bids.GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
}
|
||||
int64_t versionId = std::stoll(data["version"].GetString());
|
||||
const auto& optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
|
||||
this->processOrderBookWithVersionId(versionId, wsConnection, channelId, symbolId, exchangeSubscriptionId, optionMap, marketDataMessageList,
|
||||
marketDataMessage);
|
||||
} else if (channelId == CCAPI_WEBSOCKET_MEXC_FUTURES_CHANNEL_TRANSACTION) {
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(data["t"].GetString()));
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(data["p"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(data["v"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(data["T"].GetString()) == "2" ? "0" : "1"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
} else {
|
||||
std::vector<Message> messageList;
|
||||
if (channel == "rs.error") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
} else if (channel.rfind("rs.sub.", 0) == 0) {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
Element element;
|
||||
element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
}
|
||||
event.setMessageList(messageList);
|
||||
}
|
||||
}
|
||||
}
|
||||
void convertRequestForRest(http::request<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 toReplace = "{symbol}";
|
||||
target.replace(target.find(toReplace), toReplace.length(), symbolId);
|
||||
std::string queryString;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param,
|
||||
{
|
||||
{CCAPI_LIMIT, "limit"},
|
||||
});
|
||||
req.target(target + "?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENT: {
|
||||
req.method(http::verb::get);
|
||||
auto target = this->getInstrumentsTarget;
|
||||
std::string queryString;
|
||||
this->appendSymbolId(queryString, symbolId, "symbol");
|
||||
req.target(target + "?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENTS: {
|
||||
req.method(http::verb::get);
|
||||
auto target = this->getInstrumentsTarget;
|
||||
req.target(target);
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
void extractInstrumentInfo(Element& element, const rj::Value& x) {
|
||||
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
|
||||
element.insert(CCAPI_MARGIN_ASSET, x["settleCoin"].GetString());
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["priceUnit"].GetString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["volUnit"].GetString());
|
||||
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minVol"].GetString());
|
||||
element.insert(CCAPI_CONTRACT_SIZE, x["contractSize"].GetString());
|
||||
}
|
||||
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<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["data"].GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["t"].GetString()));
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["p"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["v"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["T"].GetString()) == "2" ? "1" : "0"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENT: {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
std::vector<Element> elementList;
|
||||
Element element;
|
||||
this->extractInstrumentInfo(element, document["data"]);
|
||||
elementList.push_back(element);
|
||||
message.setElementList(elementList);
|
||||
message.setCorrelationIdList({request.getCorrelationId()});
|
||||
event.addMessages({message});
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENTS: {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
std::vector<Element> elementList;
|
||||
for (const auto& x : document["data"].GetArray()) {
|
||||
Element element;
|
||||
this->extractInstrumentInfo(element, x);
|
||||
elementList.push_back(element);
|
||||
}
|
||||
message.setElementList(elementList);
|
||||
message.setCorrelationIdList({request.getCorrelationId()});
|
||||
event.addMessages({message});
|
||||
} break;
|
||||
default:
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_MEXC_FUTURES_H_
|
||||
+163
-115
@@ -1,54 +1,64 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKEX_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKEX_H_
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKX_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKX_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_OKEX
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_OKX
|
||||
#include "ccapi_cpp/service/ccapi_market_data_service.h"
|
||||
namespace ccapi {
|
||||
class MarketDataServiceOkex : public MarketDataService {
|
||||
class MarketDataServiceOkx : public MarketDataService {
|
||||
public:
|
||||
MarketDataServiceOkex(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
MarketDataServiceOkx(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
std::shared_ptr<ServiceContext> serviceContextPtr)
|
||||
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_OKEX;
|
||||
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + CCAPI_OKEX_PUBLIC_WS_PATH;
|
||||
this->needDecompressWebsocketMessage = true;
|
||||
ErrorCode ec = this->inflater.init(false);
|
||||
if (ec) {
|
||||
CCAPI_LOGGER_FATAL(ec.message());
|
||||
}
|
||||
this->exchangeName = CCAPI_EXCHANGE_NAME_OKX;
|
||||
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + CCAPI_OKX_PUBLIC_WS_PATH;
|
||||
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
|
||||
this->setHostRestFromUrlRest(this->baseUrlRest);
|
||||
this->setHostWsFromUrlWs(this->baseUrlWs);
|
||||
try {
|
||||
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#else
|
||||
try {
|
||||
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
|
||||
} catch (const std::exception& e) {
|
||||
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
|
||||
}
|
||||
#endif
|
||||
this->apiKeyName = CCAPI_OKX_API_KEY;
|
||||
this->apiSecretName = CCAPI_OKX_API_SECRET;
|
||||
this->apiPassphraseName = CCAPI_OKX_API_PASSPHRASE;
|
||||
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
|
||||
this->getRecentTradesTarget = "/api/v5/market/trades";
|
||||
this->getInstrumentTarget = "/api/v5/public/instruments";
|
||||
this->getInstrumentsTarget = "/api/v5/public/instruments";
|
||||
}
|
||||
virtual ~MarketDataServiceOkex() {}
|
||||
virtual ~MarketDataServiceOkx() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
private:
|
||||
#endif
|
||||
bool doesHttpBodyContainError(const Request& request, const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); }
|
||||
bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); }
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const std::map<std::string, std::string> optionMap) override {
|
||||
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));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
if (conflateIntervalMilliSeconds < 100) {
|
||||
if (marketDepthRequested <= 50) {
|
||||
channelId = CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH50_L2_TBT;
|
||||
if (marketDepthRequested == 1) {
|
||||
channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT;
|
||||
} else if (marketDepthRequested <= 50) {
|
||||
channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH50_L2_TBT;
|
||||
} else {
|
||||
channelId = CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400_L2_TBT;
|
||||
channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400_L2_TBT;
|
||||
}
|
||||
} else {
|
||||
if (marketDepthRequested <= 5) {
|
||||
channelId = CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5;
|
||||
channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH5;
|
||||
} else {
|
||||
channelId = CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400;
|
||||
channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,7 +75,7 @@ class MarketDataServiceOkex : public MarketDataService {
|
||||
auto channelId = subscriptionListByChannelIdSymbolId.first;
|
||||
for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
|
||||
std::string symbolId = subscriptionListBySymbolId.first;
|
||||
if (channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5) {
|
||||
if (channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT || channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH5) {
|
||||
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
|
||||
}
|
||||
std::string exchangeSubscriptionId = UtilString::split(channelId, "?").at(0) + ":" + symbolId;
|
||||
@@ -112,106 +122,114 @@ class MarketDataServiceOkex : public MarketDataService {
|
||||
if (textMessage != "pong") {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
if (document.IsObject() && document.HasMember("arg")) {
|
||||
const rj::Value& arg = document["arg"];
|
||||
std::string channelId = arg["channel"].GetString();
|
||||
std::string symbolId = arg["instId"].GetString();
|
||||
std::string exchangeSubscriptionId = channelId + ":" + symbolId;
|
||||
if (document.HasMember("event")) {
|
||||
std::string eventStr = document["event"].GetString();
|
||||
if (eventStr == "subscribe") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
std::vector<std::string> correlationIdList;
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
|
||||
const rj::Value& arg = document["arg"];
|
||||
std::string channelId = arg["channel"].GetString();
|
||||
std::string symbolId = arg["instId"].GetString();
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) {
|
||||
std::vector<std::string> correlationIdList_2 =
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
|
||||
correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end());
|
||||
auto it = document.FindMember("event");
|
||||
std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : "";
|
||||
if (eventStr == "login") {
|
||||
this->startSubscribe(wsConnection);
|
||||
} else {
|
||||
if (document.IsObject() && document.HasMember("arg")) {
|
||||
const rj::Value& arg = document["arg"];
|
||||
std::string channelId = arg["channel"].GetString();
|
||||
std::string symbolId = arg["instId"].GetString();
|
||||
std::string exchangeSubscriptionId = channelId + ":" + symbolId;
|
||||
if (!eventStr.empty()) {
|
||||
if (eventStr == "subscribe") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
std::vector<std::string> correlationIdList;
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
|
||||
const rj::Value& arg = document["arg"];
|
||||
std::string channelId = arg["channel"].GetString();
|
||||
std::string symbolId = arg["instId"].GetString();
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
|
||||
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) !=
|
||||
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) {
|
||||
std::vector<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(Message::Type::SUBSCRIPTION_STARTED);
|
||||
Element element;
|
||||
element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
event.setMessageList(messageList);
|
||||
} else if (eventStr == "error") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
event.setMessageList(messageList);
|
||||
}
|
||||
message.setCorrelationIdList(correlationIdList);
|
||||
message.setType(Message::Type::SUBSCRIPTION_STARTED);
|
||||
Element element;
|
||||
element.insert(CCAPI_INFO_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
event.setMessageList(messageList);
|
||||
} else if (eventStr == "error") {
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
|
||||
Element element;
|
||||
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
|
||||
message.setElementList({element});
|
||||
messageList.emplace_back(std::move(message));
|
||||
event.setMessageList(messageList);
|
||||
}
|
||||
} else {
|
||||
if (channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5 || channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400 ||
|
||||
channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH50_L2_TBT || channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400_L2_TBT) {
|
||||
std::string action = channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5 ? "" : document["action"].GetString();
|
||||
for (const auto& datum : document["data"].GetArray()) {
|
||||
if (this->sessionOptions.enableCheckOrderBookChecksum) {
|
||||
auto it = datum.FindMember("checksum");
|
||||
if (it != datum.MemberEnd()) {
|
||||
this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId] =
|
||||
intToHex(static_cast<uint_fast32_t>(static_cast<uint32_t>(std::stoi(it->value.GetString()))));
|
||||
} else {
|
||||
if (channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT || channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH5 ||
|
||||
channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400 || channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH50_L2_TBT ||
|
||||
channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400_L2_TBT) {
|
||||
std::string action = channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT || channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH5
|
||||
? ""
|
||||
: document["action"].GetString();
|
||||
for (const auto& datum : document["data"].GetArray()) {
|
||||
if (this->sessionOptions.enableCheckOrderBookChecksum) {
|
||||
auto it = datum.FindMember("checksum");
|
||||
if (it != datum.MemberEnd()) {
|
||||
this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId] =
|
||||
intToHex(static_cast<uint_fast32_t>(static_cast<uint32_t>(std::stoi(it->value.GetString()))));
|
||||
}
|
||||
}
|
||||
}
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString())));
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
|
||||
if (channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5) {
|
||||
if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) {
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString())));
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
|
||||
if (channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT || channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH5) {
|
||||
if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) {
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
} else {
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
|
||||
}
|
||||
} else {
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
|
||||
marketDataMessage.recapType = action == "update" ? MarketDataMessage::RecapType::NONE : MarketDataMessage::RecapType::SOLICITED;
|
||||
}
|
||||
} else {
|
||||
marketDataMessage.recapType = action == "update" ? MarketDataMessage::RecapType::NONE : MarketDataMessage::RecapType::SOLICITED;
|
||||
for (const auto& x : datum["bids"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
for (const auto& x : datum["asks"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
for (const auto& x : datum["bids"].GetArray()) {
|
||||
} else if (channelId == CCAPI_WEBSOCKET_OKX_CHANNEL_TRADE) {
|
||||
for (const auto& datum : document["data"].GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString())));
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum["px"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum["sz"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, datum["tradeId"].GetString()});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "sell" ? "1" : "0"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
for (const auto& x : datum["asks"].GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
} else if (channelId == CCAPI_WEBSOCKET_OKEX_CHANNEL_TRADE) {
|
||||
for (const auto& datum : document["data"].GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString())));
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum["px"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum["sz"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, datum["tradeId"].GetString()});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "sell" ? "1" : "0"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -257,7 +275,6 @@ class MarketDataServiceOkex : public MarketDataService {
|
||||
{
|
||||
{CCAPI_INSTRUMENT_TYPE, "instType"},
|
||||
});
|
||||
this->appendSymbolId(queryString, symbolId, "instId");
|
||||
req.target(target + "?" + queryString);
|
||||
} break;
|
||||
default:
|
||||
@@ -273,6 +290,8 @@ class MarketDataServiceOkex : public MarketDataService {
|
||||
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minSz"].GetString());
|
||||
element.insert(CCAPI_MARGIN_ASSET, x["settleCcy"].GetString());
|
||||
element.insert(CCAPI_UNDERLYING_SYMBOL, x["uly"].GetString());
|
||||
element.insert(CCAPI_CONTRACT_SIZE, x["ctVal"].GetString());
|
||||
element.insert(CCAPI_CONTRACT_MULTIPLIER, x["ctMult"].GetString());
|
||||
}
|
||||
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
@@ -326,8 +345,37 @@ class MarketDataServiceOkex : public MarketDataService {
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
std::vector<std::string> createSendStringListFromSubscriptionList(const WsConnection& wsConnection, const std::vector<Subscription>& subscriptionList,
|
||||
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("login").Move(), allocator);
|
||||
rj::Value arg(rj::kObjectType);
|
||||
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
|
||||
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
|
||||
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
|
||||
std::string ts = std::to_string(std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count());
|
||||
arg.AddMember("apiKey", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("passphrase", rj::Value(apiPassphrase.c_str(), allocator).Move(), allocator);
|
||||
arg.AddMember("timestamp", rj::Value(ts.c_str(), allocator).Move(), allocator);
|
||||
std::string signData = ts + "GET" + "/users/self/verify";
|
||||
std::string sign = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, signData));
|
||||
arg.AddMember("sign", rj::Value(sign.c_str(), allocator).Move(), allocator);
|
||||
rj::Value args(rj::kArrayType);
|
||||
args.PushBack(arg, allocator);
|
||||
document.AddMember("args", args, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
return sendStringList;
|
||||
}
|
||||
std::string apiPassphraseName;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKEX_H_
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKX_H_
|
||||
@@ -0,0 +1,340 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_WHITEBIT_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_WHITEBIT_H_
|
||||
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
|
||||
#ifdef CCAPI_ENABLE_EXCHANGE_WHITEBIT
|
||||
#include "ccapi_cpp/service/ccapi_market_data_service.h"
|
||||
namespace ccapi {
|
||||
class MarketDataServiceWhitebit : public MarketDataService {
|
||||
public:
|
||||
MarketDataServiceWhitebit(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
|
||||
std::shared_ptr<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
|
||||
this->getRecentTradesTarget = "/api/v4/public/trades/{market}";
|
||||
this->getInstrumentsTarget = "/api/v4/public/markets";
|
||||
this->methodDepthSubscribe = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_DEPTH) + "_subscribe";
|
||||
this->methodTradesSubscribe = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES) + "_subscribe";
|
||||
this->methodDepthUpdate = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_DEPTH) + "_update";
|
||||
this->methodTradesUpdate = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES) + "_update";
|
||||
this->shouldAlignSnapshot = true;
|
||||
}
|
||||
virtual ~MarketDataServiceWhitebit() {}
|
||||
#ifndef CCAPI_EXPOSE_INTERNAL
|
||||
|
||||
private:
|
||||
#endif
|
||||
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
|
||||
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
|
||||
this->send(hdl, R"({"id":)" + std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]) + R"(,"method":"ping","params":[]})",
|
||||
wspp::frame::opcode::text, ec);
|
||||
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
|
||||
}
|
||||
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
|
||||
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
|
||||
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
|
||||
if (field == CCAPI_MARKET_DEPTH) {
|
||||
int marketDepthSubscribedToExchange = marketDepthRequested;
|
||||
// channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
|
||||
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
|
||||
}
|
||||
}
|
||||
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
|
||||
std::vector<std::string> sendStringList;
|
||||
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
|
||||
auto channelId = subscriptionListByChannelIdSymbolId.first;
|
||||
if (channelId == CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_DEPTH) {
|
||||
for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
|
||||
auto symbolId = subscriptionListByInstrument.first;
|
||||
auto exchangeSubscriptionId = channelId + subscriptionListByInstrument.first;
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
|
||||
document.AddMember("method", rj::Value("depth_subscribe").Move(), allocator);
|
||||
rj::Value params(rj::kArrayType);
|
||||
params.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
|
||||
int marketDepthSubscribedToExchange =
|
||||
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
|
||||
params.PushBack(rj::Value(marketDepthSubscribedToExchange).Move(), allocator);
|
||||
params.PushBack(rj::Value("0").Move(), allocator);
|
||||
params.PushBack(rj::Value(true).Move(), allocator);
|
||||
document.AddMember("params", params, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<rj::StringBuffer> writer(stringBuffer);
|
||||
document.Accept(writer);
|
||||
std::string sendString = stringBuffer.GetString();
|
||||
sendStringList.push_back(sendString);
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
|
||||
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]
|
||||
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = {
|
||||
exchangeSubscriptionId};
|
||||
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
|
||||
}
|
||||
} else if (channelId == CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES) {
|
||||
rj::Document document;
|
||||
document.SetObject();
|
||||
rj::Document::AllocatorType& allocator = document.GetAllocator();
|
||||
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
|
||||
document.AddMember("method", rj::Value("trades_subscribe").Move(), allocator);
|
||||
rj::Value params(rj::kArrayType);
|
||||
std::vector<std::string> exchangeSubscriptionIdList;
|
||||
for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
|
||||
auto symbolId = subscriptionListByInstrument.first;
|
||||
params.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
|
||||
auto exchangeSubscriptionId = channelId + subscriptionListByInstrument.first;
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
|
||||
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
|
||||
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
|
||||
}
|
||||
document.AddMember("params", params, allocator);
|
||||
rj::StringBuffer stringBuffer;
|
||||
rj::Writer<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;
|
||||
}
|
||||
}
|
||||
return sendStringList;
|
||||
}
|
||||
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<MarketDataMessage>& marketDataMessageList) override {
|
||||
rj::Document document;
|
||||
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
|
||||
auto itId = document.FindMember("id");
|
||||
if (itId == document.MemberEnd() || itId->value.IsNull()) {
|
||||
std::string method = document["method"].GetString();
|
||||
const auto& params = document["params"];
|
||||
if (method == this->methodDepthUpdate) {
|
||||
bool isFullReload = params[0].GetBool();
|
||||
std::string symbolId = params[2].GetString();
|
||||
const auto& exchangeSubscriptionId = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_DEPTH) + symbolId;
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
marketDataMessage.recapType = isFullReload ? MarketDataMessage::RecapType::SOLICITED : MarketDataMessage::RecapType::NONE;
|
||||
marketDataMessage.tp = timeReceived;
|
||||
auto itBids = params[1].FindMember("bids");
|
||||
if (itBids != params[1].MemberEnd()) {
|
||||
const rj::Value& bids = itBids->value;
|
||||
for (const auto& x : bids.GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
}
|
||||
auto itAsks = params[1].FindMember("asks");
|
||||
if (itAsks != params[1].MemberEnd()) {
|
||||
const rj::Value& asks = itAsks->value;
|
||||
for (const auto& x : asks.GetArray()) {
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
|
||||
}
|
||||
}
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
} else if (method == this->methodTradesUpdate) {
|
||||
std::string symbolId = params[0].GetString();
|
||||
const auto& exchangeSubscriptionId = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES) + symbolId;
|
||||
for (const auto& x : params[1].GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
|
||||
auto timePair = UtilTime::divide(std::string(x["time"].GetString()));
|
||||
auto tp = TimePoint(std::chrono::duration<int64_t>(timePair.first));
|
||||
tp += std::chrono::nanoseconds(timePair.second);
|
||||
marketDataMessage.tp = tp;
|
||||
if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES][symbolId]) {
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
|
||||
} else {
|
||||
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
|
||||
this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_TRADES][symbolId] = true;
|
||||
}
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["amount"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["id"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["type"].GetString()) == "sell" ? "1" : "0"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
int id = std::stoi(itId->value.GetString());
|
||||
auto itResult = document.FindMember("result");
|
||||
if (itResult != document.MemberEnd()) {
|
||||
if (itResult->value.IsObject()) {
|
||||
const auto& result = itResult->value;
|
||||
auto itError = document.FindMember("error");
|
||||
bool success = itError == document.MemberEnd() || itError->value.IsNull();
|
||||
event.setType(Event::Type::SUBSCRIPTION_STATUS);
|
||||
std::vector<Message> messageList;
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
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)) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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;
|
||||
this->substituteParam(target, {
|
||||
{"{market}", symbolId},
|
||||
});
|
||||
std::string queryString;
|
||||
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
|
||||
this->appendParam(queryString, param, {});
|
||||
req.target(queryString.empty() ? target : target + "?" + queryString);
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENT: {
|
||||
req.method(http::verb::get);
|
||||
auto target = this->getInstrumentsTarget;
|
||||
req.target(target);
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENTS: {
|
||||
req.method(http::verb::get);
|
||||
req.target(this->getInstrumentsTarget);
|
||||
} break;
|
||||
default:
|
||||
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
|
||||
}
|
||||
}
|
||||
void extractInstrumentInfo(Element& element, const rj::Value& x) {
|
||||
element.insert(CCAPI_INSTRUMENT, x["name"].GetString());
|
||||
element.insert(CCAPI_BASE_ASSET, x["stock"].GetString());
|
||||
element.insert(CCAPI_QUOTE_ASSET, x["money"].GetString());
|
||||
int moneyPrec = std::stoi(x["moneyPrec"].GetString());
|
||||
if (moneyPrec > 0) {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(moneyPrec - 1, '0') + "1");
|
||||
} else {
|
||||
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1" + std::string(-moneyPrec, '0'));
|
||||
}
|
||||
int stockPrec = std::stoi(x["stockPrec"].GetString());
|
||||
if (stockPrec > 0) {
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "0." + std::string(stockPrec - 1, '0') + "1");
|
||||
} else {
|
||||
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "1" + std::string(-stockPrec, '0'));
|
||||
}
|
||||
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minAmount"].GetString());
|
||||
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["minTotal"].GetString());
|
||||
}
|
||||
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
|
||||
std::vector<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.GetArray()) {
|
||||
MarketDataMessage marketDataMessage;
|
||||
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
|
||||
auto timePair = UtilTime::divide(std::string(x["trade_timestamp"].GetString()));
|
||||
auto tp = TimePoint(std::chrono::duration<int64_t>(timePair.first));
|
||||
tp += std::chrono::nanoseconds(timePair.second);
|
||||
marketDataMessage.tp = tp;
|
||||
MarketDataMessage::TypeForDataPoint dataPoint;
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["base_volume"].GetString()))});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["tradeID"].GetString())});
|
||||
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["type"].GetString()) == "sell" ? "1" : "0"});
|
||||
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
|
||||
marketDataMessageList.emplace_back(std::move(marketDataMessage));
|
||||
}
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENT: {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
for (const auto& x : document.GetArray()) {
|
||||
if (std::string(x["name"].GetString()) == request.getInstrument()) {
|
||||
Element element;
|
||||
this->extractInstrumentInfo(element, x);
|
||||
message.setElementList({element});
|
||||
break;
|
||||
}
|
||||
}
|
||||
message.setCorrelationIdList({request.getCorrelationId()});
|
||||
event.addMessages({message});
|
||||
} break;
|
||||
case Request::Operation::GET_INSTRUMENTS: {
|
||||
Message message;
|
||||
message.setTimeReceived(timeReceived);
|
||||
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
|
||||
std::vector<Element> elementList;
|
||||
for (const auto& x : document.GetArray()) {
|
||||
Element element;
|
||||
this->extractInstrumentInfo(element, x);
|
||||
elementList.emplace_back(std::move(element));
|
||||
}
|
||||
message.setElementList(elementList);
|
||||
message.setCorrelationIdList({request.getCorrelationId()});
|
||||
event.addMessages({message});
|
||||
} break;
|
||||
default:
|
||||
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
|
||||
}
|
||||
}
|
||||
std::string methodDepthSubscribe, methodDepthUpdate, methodTradesSubscribe, methodTradesUpdate;
|
||||
};
|
||||
} /* namespace ccapi */
|
||||
#endif
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_WHITEBIT_H_
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,6 @@
|
||||
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_
|
||||
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_
|
||||
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
|
||||
#include "ccapi_cpp/ccapi_logger.h"
|
||||
#include "websocketpp/client.hpp"
|
||||
#include "websocketpp/common/connection_hdl.hpp"
|
||||
@@ -23,7 +24,7 @@ class ServiceContext CCAPI_FINAL {
|
||||
};
|
||||
#endif
|
||||
#ifdef CCAPI_WEBSOCKET_READ_BUFFER_SIZE
|
||||
static const size_t connection_read_buffer_size = CCAPI_WEBSOCKET_READ_BUFFER_SIZE;
|
||||
static const size_t connection_read_buffer_size = CCAPI_WEBSOCKET_READ_BUFFER_SIZE;
|
||||
#endif
|
||||
static const wspp::log::level alog_level = wspp::log::alevel::none;
|
||||
static const wspp::log::level elog_level = wspp::log::elevel::none;
|
||||
@@ -63,9 +64,52 @@ static const size_t connection_read_buffer_size = CCAPI_WEBSOCKET_READ_BUFFER_SI
|
||||
}
|
||||
IoContextPtr ioContextPtr{new IoContext()};
|
||||
TlsClientPtr tlsClientPtr{new TlsClient()};
|
||||
SslContextPtr sslContextPtr{new SslContext(SslContext::sslv23)};
|
||||
SslContextPtr sslContextPtr{new SslContext(SslContext::tls_client)};
|
||||
};
|
||||
|
||||
} /* namespace ccapi */
|
||||
#else
|
||||
#include "ccapi_cpp/ccapi_logger.h"
|
||||
namespace ccapi {
|
||||
/**
|
||||
* Defines the service that the service depends on.
|
||||
*/
|
||||
class ServiceContext CCAPI_FINAL {
|
||||
public:
|
||||
typedef boost::asio::io_context IoContext;
|
||||
typedef std::shared_ptr<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 boost::asio::ssl::context SslContext;
|
||||
typedef std::shared_ptr<SslContext> SslContextPtr;
|
||||
ServiceContext() {
|
||||
// this->sslContextPtr->set_options(SslContext::default_workarounds | SslContext::no_sslv2 | SslContext::no_sslv3 | SslContext::single_dh_use);
|
||||
this->sslContextPtr->set_verify_mode(boost::asio::ssl::verify_none);
|
||||
// TODO(cryptochassis): verify ssl certificate to strengthen security
|
||||
// https://github.com/boostorg/asio/blob/develop/example/cpp03/ssl/client.cpp
|
||||
}
|
||||
ServiceContext(const ServiceContext&) = delete;
|
||||
ServiceContext& operator=(const ServiceContext&) = delete;
|
||||
virtual ~ServiceContext() {
|
||||
// delete this->ExecutorWorkGuardPtr;
|
||||
// delete this->ioContextPtr;
|
||||
// delete this->sslContextPtr;
|
||||
}
|
||||
void start() {
|
||||
CCAPI_LOGGER_INFO("about to start client asio io_context run loop");
|
||||
this->ioContextPtr->run();
|
||||
CCAPI_LOGGER_INFO("just exited client asio io_context run loop");
|
||||
}
|
||||
void stop() {
|
||||
this->executorWorkGuardPtr->reset();
|
||||
this->ioContextPtr->stop();
|
||||
}
|
||||
IoContextPtr ioContextPtr{new IoContext()};
|
||||
ExecutorWorkGuardPtr executorWorkGuardPtr{new ExecutorWorkGuard(ioContextPtr->get_executor())};
|
||||
SslContextPtr sslContextPtr{new SslContext(SslContext::tls_client)};
|
||||
};
|
||||
|
||||
} /* namespace ccapi */
|
||||
|
||||
#endif
|
||||
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_
|
||||
Reference in new issue
Block a user