Add ccapi [header-only] lib to includes

This is the open source crypto connector lib
This commit is contained in:
John Colvin committed 2022-06-06 11:57:00 -04:00
1 parent 27310d2829
commit 99c440f568
102 files changed
+33735

No files matched your search

File diff suppressed because it is too large. Load diff
+229
View File
@@ -0,0 +1,229 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_DECIMAL_H_
#define INCLUDE_CCAPI_CPP_CCAPI_DECIMAL_H_
#include <string>
#include "ccapi_cpp/ccapi_util_private.h"
namespace ccapi {
// minimalistic just for the purpose of being used as the key of a map
class Decimal CCAPI_FINAL {
public:
Decimal() {}
explicit Decimal(const std::string& originalValue, bool keepTrailingZero = false) {
if (originalValue.empty()) {
CCAPI_LOGGER_FATAL("Decimal constructor input value cannot be empty");
}
// std::string originalValue = originalValue;
// this->sign = true;
if (originalValue.at(0) == '-') {
// originalValue.erase(0, 1);
this->sign = false;
}
auto foundE = originalValue.find('E');
if (foundE != std::string::npos || originalValue.find('e') != std::string::npos) {
if (foundE == std::string::npos) {
foundE = originalValue.find('e');
}
std::string fixedPointValue = originalValue.substr(this->sign ? 0 : 1, this->sign ? foundE : foundE - 1);
auto foundDot = fixedPointValue.find('.');
if (foundDot != std::string::npos) {
fixedPointValue.erase(fixedPointValue.find_last_not_of('0') + 1);
fixedPointValue.erase(fixedPointValue.find_last_not_of('.') + 1);
}
std::string exponent = originalValue.substr(foundE + 1);
if (exponent.at(0) == '+') {
exponent.erase(0, 1);
}
exponent.erase(0, exponent.find_first_not_of('0'));
if (exponent.empty()) {
exponent = "0";
}
if (exponent != "0") {
foundDot = fixedPointValue.find('.');
if (foundDot != std::string::npos) {
if (exponent.at(0) != '-') {
if (std::stoi(exponent) < fixedPointValue.substr(foundDot + 1).length()) {
fixedPointValue = fixedPointValue.substr(0, foundDot) + fixedPointValue.substr(foundDot + 1).substr(0, std::stoi(exponent)) + "." +
fixedPointValue.substr(foundDot + 1).substr(std::stoi(exponent));
} else {
fixedPointValue = fixedPointValue.substr(0, foundDot) + fixedPointValue.substr(foundDot + 1) +
std::string(std::stoi(exponent) - fixedPointValue.substr(foundDot + 1).length(), '0');
}
} else {
fixedPointValue = "0." + std::string(-std::stoi(exponent) - 1, '0') + fixedPointValue.substr(0, foundDot) + fixedPointValue.substr(foundDot + 1);
}
} else {
if (exponent.at(0) != '-') {
fixedPointValue += std::string(std::stoi(exponent), '0');
} else {
fixedPointValue = "0." + std::string(-std::stoi(exponent) - 1, '0') + fixedPointValue;
}
}
}
foundDot = fixedPointValue.find('.');
// TODO(cryptochassis): replace with std::from_chars() once upgrade to C++17
this->before = std::stoull(fixedPointValue.substr(0, foundDot));
if (foundDot != std::string::npos) {
this->frac = fixedPointValue.substr(foundDot + 1);
if (!keepTrailingZero) {
this->frac.erase(this->frac.find_last_not_of('0') + 1);
}
}
} else {
auto found = originalValue.find('.');
// TODO(cryptochassis): replace with std::from_chars() once upgrade to C++17
this->before = std::stoull(originalValue.substr(this->sign ? 0 : 1, found));
if (found != std::string::npos) {
this->frac = originalValue.substr(found + 1);
if (!keepTrailingZero) {
this->frac.erase(this->frac.find_last_not_of('0') + 1);
}
}
}
}
std::string toString() const {
std::string stringValue;
if (!this->sign) {
stringValue += "-";
}
stringValue += std::to_string(this->before);
if (!this->frac.empty()) {
stringValue += ".";
stringValue += this->frac;
}
return stringValue;
}
double toDouble() const { return std::stod(this->toString()); }
friend bool operator<(const Decimal& l, const Decimal& r) {
if (l.sign && r.sign) {
if (l.before < r.before) {
return true;
} else if (l.before > r.before) {
return false;
} else {
return l.frac < r.frac;
}
} else if (l.sign && !r.sign) {
return false;
} else if (!l.sign && r.sign) {
if (l.before == 0 && l.frac.empty() && r.before == 0 && r.frac.empty()) {
return false;
} else {
return true;
}
} else {
Decimal nl = l;
nl.sign = true;
Decimal nr = r;
nr.sign = true;
return nl > nr;
}
}
friend bool operator>(const Decimal& l, const Decimal& r) { return r < l; }
friend bool operator<=(const Decimal& l, const Decimal& r) { return !(l > r); }
friend bool operator>=(const Decimal& l, const Decimal& r) { return !(l < r); }
friend bool operator==(const Decimal& l, const Decimal& r) { return !(l > r) && !(l < r); }
friend bool operator!=(const Decimal& l, const Decimal& r) { return !(l == r); }
Decimal negate() const {
Decimal o;
o.before = this->before;
o.frac = this->frac;
o.sign = !this->sign;
return o;
}
Decimal add(const Decimal& x) const {
if (this->sign && x.sign) {
Decimal o;
o.sign = true;
o.before = this->before + x.before;
if (this->frac.empty()) {
o.frac = x.frac;
} else if (x.frac.empty()) {
o.frac = this->frac;
} else {
auto l1 = this->frac.length();
auto l2 = x.frac.length();
if (l1 > l2) {
auto a = std::to_string(std::stoull(this->frac) + std::stoull(UtilString::rightPadTo(x.frac, l1, '0')));
if (a.length() < l1) {
a = UtilString::leftPadTo(a, l1, '0');
}
if (a.length() == l1) {
o.frac = UtilString::rtrim(a, "0");
} else {
o.frac = UtilString::rtrim(a.substr(a.length() - l1), "0");
o.before += std::stoull(a.substr(0, a.length() - l1));
}
} else if (l1 < l2) {
auto a = std::to_string(std::stoull(UtilString::rightPadTo(this->frac, l2, '0')) + std::stoull(x.frac));
if (a.length() < l2) {
a = UtilString::leftPadTo(a, l2, '0');
}
if (a.length() == l2) {
o.frac = UtilString::rtrim(a, "0");
} else {
o.frac = UtilString::rtrim(a.substr(a.length() - l2), "0");
o.before += std::stoull(a.substr(0, a.length() - l2));
}
} else {
auto a = std::to_string(std::stoull(this->frac) + std::stoull(x.frac));
if (a.length() < l1) {
a = UtilString::leftPadTo(a, l1, '0');
}
if (a.length() == l1) {
o.frac = UtilString::rtrim(a, "0");
} else {
o.frac = UtilString::rtrim(a.substr(a.length() - l1), "0");
o.before += std::stoull(a.substr(0, a.length() - l1));
}
}
}
return o;
} else if (!this->sign && x.sign) {
return x.subtract(this->negate());
} else if (this->sign && !x.sign) {
return this->subtract(x.negate());
} else {
return (this->negate().add(x.negate())).negate();
}
}
Decimal subtract(const Decimal& x) const {
if (this->sign && x.sign) {
if (*this >= x) {
Decimal o;
o.sign = true;
if (this->frac >= x.frac) {
o.before = this->before - x.before;
} else {
o.before = this->before - 1 - x.before;
}
auto l1 = this->frac.length();
auto l2 = x.frac.length();
auto lmax = std::max(l1, l2);
auto a = lmax > 0 ? std::to_string(std::stoull(UtilString::rightPadTo(this->frac, lmax, '0')) +
(this->frac >= x.frac ? (unsigned)0 : std::stoull(UtilString::rightPadTo("1", 1 + lmax, '0'))) -
std::stoull(UtilString::rightPadTo(x.frac, lmax, '0')))
: "";
if (a.length() < lmax) {
a = UtilString::leftPadTo(a, lmax, '0');
}
o.frac = UtilString::rtrim(a, "0");
return o;
} else {
return x.subtract(*this).negate();
}
} else if (!this->sign && x.sign) {
return x.subtract(this->negate());
} else if (this->sign && !x.sign) {
return this->subtract(x.negate());
} else {
return x.negate().subtract(this->negate());
}
}
// {-}bbbb.aaaa
unsigned long long before{};
std::string frac;
// false means negative sign needed
bool sign{true};
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_DECIMAL_H_
+50
View File
@@ -0,0 +1,50 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_ELEMENT_H_
#define INCLUDE_CCAPI_CPP_CCAPI_ELEMENT_H_
#include <map>
#include <string>
#include "ccapi_cpp/ccapi_util_private.h"
namespace ccapi {
class Element CCAPI_FINAL {
public:
explicit Element(bool isFix = false) : isFix(isFix) {}
void insert(const std::string& name, const std::string& value) { this->nameValueMap.insert(std::pair<std::string, std::string>(name, value)); }
void insert(int tag, const std::string& value) { this->tagValueMap.insert(std::pair<int, std::string>(tag, value)); }
void emplace(std::string& name, std::string& value) { this->nameValueMap.emplace(std::move(name), std::move(value)); }
void emplace(int tag, std::string& value) { this->tagValueMap.emplace(std::move(tag), std::move(value)); }
bool has(const std::string& name) const { return this->nameValueMap.find(name) != this->nameValueMap.end(); }
bool has(int tag) const { return this->tagValueMap.find(tag) != this->tagValueMap.end(); }
std::string getValue(const std::string& name, const std::string valueDefault = "") const {
auto it = this->nameValueMap.find(name);
return it == this->nameValueMap.end() ? valueDefault : it->second;
}
std::string getValue(int tag, const std::string valueDefault = "") const {
auto it = this->tagValueMap.find(tag);
return it == this->tagValueMap.end() ? valueDefault : it->second;
}
std::string toString() const {
std::string output =
isFix ? "Element [tagValueMap = " + ccapi::toString(tagValueMap) + "]" : "Element [nameValueMap = " + ccapi::toString(nameValueMap) + "]";
return output;
}
std::string toStringPretty(const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) const {
std::string sl(leftToIndent, ' ');
std::string ss(leftToIndent + space, ' ');
std::string output = isFix ? (indentFirstLine ? sl : "") + "Element [\n" + ss +
"tagValueMap = " + ccapi::toStringPretty(tagValueMap, space, space + leftToIndent, false) + "\n" + sl + "]"
: (indentFirstLine ? sl : "") + "Element [\n" + ss +
"nameValueMap = " + ccapi::toStringPretty(nameValueMap, space, space + leftToIndent, false) + "\n" + sl + "]";
return output;
}
const std::map<std::string, std::string>& getNameValueMap() const { return nameValueMap; }
const std::map<int, std::string>& getTagValueMap() const { return tagValueMap; }
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
bool isFix;
std::map<std::string, std::string> nameValueMap;
std::map<int, std::string> tagValueMap;
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_ELEMENT_H_
+93
View File
@@ -0,0 +1,93 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_EVENT_H_
#define INCLUDE_CCAPI_CPP_CCAPI_EVENT_H_
#include <vector>
#include "ccapi_cpp/ccapi_logger.h"
#include "ccapi_cpp/ccapi_message.h"
namespace ccapi {
class Event CCAPI_FINAL {
public:
enum class Type {
UNKNOWN,
SESSION_STATUS,
SUBSCRIPTION_STATUS,
REQUEST_STATUS,
RESPONSE,
SUBSCRIPTION_DATA,
AUTHORIZATION_STATUS,
FIX,
FIX_STATUS,
};
static std::string typeToString(Type type) {
std::string output;
switch (type) {
case Type::UNKNOWN:
output = "UNKNOWN";
break;
case Type::SESSION_STATUS:
output = "SESSION_STATUS";
break;
case Type::SUBSCRIPTION_STATUS:
output = "SUBSCRIPTION_STATUS";
break;
case Type::REQUEST_STATUS:
output = "REQUEST_STATUS";
break;
case Type::RESPONSE:
output = "RESPONSE";
break;
case Type::SUBSCRIPTION_DATA:
output = "SUBSCRIPTION_DATA";
break;
case Type::AUTHORIZATION_STATUS:
output = "AUTHORIZATION_STATUS";
break;
case Type::FIX:
output = "FIX";
break;
case Type::FIX_STATUS:
output = "FIX_STATUS";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
return output;
}
std::string toString() const {
std::string output = "Event [type = " + typeToString(type) + ", messageList = " + ccapi::toString(messageList) + "]";
return output;
}
std::string toStringPretty(const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) const {
std::string sl(leftToIndent, ' ');
std::string ss(leftToIndent + space, ' ');
std::string output = (indentFirstLine ? sl : "") + "Event [\n" + ss + "type = " + typeToString(type) + ",\n" + ss +
"messageList = " + ccapi::toStringPretty(messageList, space, leftToIndent + space, false) + "\n" + sl + "]";
return output;
}
const std::vector<Message>& getMessageList() const { return messageList; }
void addMessages(const std::vector<Message>& newMessageList) {
this->messageList.insert(std::end(this->messageList), std::begin(newMessageList), std::end(newMessageList));
}
void addMessages(std::vector<Message>& newMessageList) {
if (this->messageList.empty()) {
this->messageList = std::move(newMessageList);
} else {
this->messageList.reserve(this->messageList.size() + newMessageList.size());
std::move(std::begin(newMessageList), std::end(newMessageList), std::back_inserter(this->messageList));
}
}
void addMessage(const Message& newMessage) { this->messageList.push_back(newMessage); }
void addMessage(Message& newMessage) { this->messageList.emplace_back(std::move(newMessage)); }
void setMessageList(const std::vector<Message>& messageList) { this->messageList = messageList; }
void setMessageList(std::vector<Message>& messageList) { this->messageList = std::move(messageList); }
Type getType() const { return type; }
void setType(Type type) { this->type = type; }
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
Type type{Type::UNKNOWN};
std::vector<Message> messageList;
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_EVENT_H_
@@ -0,0 +1,91 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_EVENT_DISPATCHER_H_
#define INCLUDE_CCAPI_CPP_CCAPI_EVENT_DISPATCHER_H_
#include <stddef.h>
#include <atomic>
#include <condition_variable>
#include <functional>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
#include "ccapi_cpp/ccapi_logger.h"
#include "ccapi_cpp/ccapi_util_private.h"
namespace ccapi {
class EventDispatcher CCAPI_FINAL {
public:
explicit EventDispatcher(const int numDispatcherThreads = 1) : numDispatcherThreads(numDispatcherThreads) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_TRACE("numDispatcherThreads = " + size_tToString(numDispatcherThreads));
this->start();
CCAPI_LOGGER_FUNCTION_EXIT;
}
~EventDispatcher() {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_FUNCTION_EXIT;
}
void dispatch(const std::function<void()>& op) {
CCAPI_LOGGER_FUNCTION_ENTER;
if (this->shouldContinue.load()) {
CCAPI_LOGGER_TRACE("start to dispatch an operation");
std::unique_lock<std::mutex> lock(this->lock);
this->queue.push(op);
// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lock.unlock();
this->cv.notify_all();
} else {
CCAPI_LOGGER_WARN("dispatching of events were paused");
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
void start() {
this->shouldContinue = true;
for (size_t i = 0; i < numDispatcherThreads; i++) {
this->dispatcherThreads.push_back(std::thread(&EventDispatcher::dispatch_thread_handler, this));
}
}
void resume() { this->shouldContinue = true; }
void pause() { this->shouldContinue = false; }
void stop() {
std::unique_lock<std::mutex> lock(this->lock);
this->quit = true;
lock.unlock();
this->cv.notify_all();
for (auto& dispatcherThread : this->dispatcherThreads) {
dispatcherThread.join();
}
}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
void dispatch_thread_handler() {
CCAPI_LOGGER_FUNCTION_ENTER;
std::unique_lock<std::mutex> lock(this->lock);
do {
CCAPI_LOGGER_TRACE("predicate is " + size_tToString(this->queue.size()));
this->cv.wait(lock, [&] { return (this->queue.size() || this->quit); });
CCAPI_LOGGER_TRACE("wait has exited");
CCAPI_LOGGER_TRACE("after wait, this->queue.size() = " + size_tToString(this->queue.size()));
if (!this->quit && this->queue.size()) {
auto op = std::move(this->queue.front());
this->queue.pop();
lock.unlock();
op();
lock.lock();
}
} while (!this->quit);
CCAPI_LOGGER_FUNCTION_EXIT;
}
size_t numDispatcherThreads;
std::atomic<bool> shouldContinue{};
std::vector<std::thread> dispatcherThreads;
std::mutex lock;
std::queue<std::function<void()> > queue;
std::condition_variable cv;
bool quit{};
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_EVENT_DISPATCHER_H_
@@ -0,0 +1,22 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_EVENT_HANDLER_H_
#define INCLUDE_CCAPI_CPP_CCAPI_EVENT_HANDLER_H_
#include "ccapi_cpp/ccapi_event.h"
namespace ccapi {
class Session;
class EventHandler {
public:
virtual ~EventHandler() {}
virtual bool processEvent(const Event& event, Session* session) { return true; }
// An implementation of processEvent should process the specified
// 'event' which originates from the specified 'session' and
// return true to indicate events should continue to be delivered
// or false to terminate dispatching of events.
//
// If the application wishes to process the event further
// after returning from the processEvents() call it must make
// a copy of the Event to ensure the underlying data is not
// freed.
// Note: no exceptions are thrown
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_EVENT_HANDLER_H_
@@ -0,0 +1,67 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_FIX_CONNECTION_H_
#define INCLUDE_CCAPI_CPP_CCAPI_FIX_CONNECTION_H_
#include <string>
#include "ccapi_cpp/ccapi_logger.h"
#include "ccapi_cpp/ccapi_subscription.h"
namespace beast = boost::beast;
namespace ccapi {
template <class T>
class FixConnection CCAPI_FINAL {
public:
FixConnection(std::string host, std::string port, Subscription subscription, std::shared_ptr<T> streamPtr)
: host(host), port(port), subscription(subscription), streamPtr(streamPtr) {
this->id = subscription.getCorrelationId();
this->url = host + ":" + port;
}
std::string toString() const {
std::ostringstream oss;
oss << streamPtr;
std::string output = "FixConnection [id = " + id + ", host = " + host + ", port = " + port + ", subscription = " + ccapi::toString(subscription) +
", status = " + statusToString(status) + ", streamPtr = " + oss.str() + "]";
return output;
}
enum class Status {
UNKNOWN,
CONNECTING,
OPEN,
FAILED,
CLOSING,
CLOSED,
};
static std::string statusToString(Status status) {
std::string output;
switch (status) {
case Status::UNKNOWN:
output = "UNKNOWN";
break;
case Status::CONNECTING:
output = "CONNECTING";
break;
case Status::OPEN:
output = "OPEN";
break;
case Status::FAILED:
output = "FAILED";
break;
case Status::CLOSING:
output = "CLOSING";
break;
case Status::CLOSED:
output = "CLOSED";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
return output;
}
std::string id;
std::string host;
std::string port;
std::string url;
Subscription subscription;
Status status{Status::UNKNOWN};
std::shared_ptr<T> streamPtr;
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_FIX_CONNECTION_H_
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,23 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_HTTP_CONNECTION_H_
#define INCLUDE_CCAPI_CPP_CCAPI_HTTP_CONNECTION_H_
#include <string>
#include "ccapi_cpp/ccapi_logger.h"
namespace beast = boost::beast;
namespace ccapi {
class HttpConnection CCAPI_FINAL {
public:
HttpConnection(std::string host, std::string port, std::shared_ptr<beast::ssl_stream<beast::tcp_stream> > streamPtr)
: host(host), port(port), streamPtr(streamPtr) {}
std::string toString() const {
std::ostringstream oss;
oss << streamPtr;
std::string output = "HttpConnection [host = " + host + ", port = " + port + ", streamPtr = " + oss.str() + "]";
return output;
}
std::string host;
std::string port;
std::shared_ptr<beast::ssl_stream<beast::tcp_stream> > streamPtr;
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_HTTP_CONNECTION_H_
@@ -0,0 +1,23 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_HTTP_RETRY_H_
#define INCLUDE_CCAPI_CPP_CCAPI_HTTP_RETRY_H_
#include <string>
namespace ccapi {
class HttpRetry CCAPI_FINAL {
public:
explicit HttpRetry(int numRetry = 0, int numRedirect = 0, std::string redirectUrlStr = "",
std::shared_ptr<std::promise<void> > promisePtr = std::shared_ptr<std::promise<void> >(nullptr))
: numRetry(numRetry), numRedirect(numRedirect), promisePtr(promisePtr) {}
std::string toString() const {
std::ostringstream oss;
oss << promisePtr;
std::string output =
"HttpConnection [numRetry = " + ccapi::toString(numRetry) + ", numRedirect = " + ccapi::toString(numRedirect) + ", promisePtr = " + oss.str() + "]";
return output;
}
int numRetry;
int numRedirect;
std::shared_ptr<std::promise<void> > promisePtr;
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_HTTP_RETRY_H_
+27
View File
@@ -0,0 +1,27 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_JWT_H_
#define INCLUDE_CCAPI_CPP_CCAPI_JWT_H_
#include "ccapi_cpp/ccapi_hmac.h"
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_util_private.h"
namespace ccapi {
class Jwt CCAPI_FINAL {
public:
static std::string generate(const Hmac::ShaVersion shaVersion, const std::string& secret, const std::string& payload) {
std::string output;
switch (shaVersion) {
case Hmac::ShaVersion::SHA256:
output += UtilAlgorithm::base64UrlEncode("{\"alg\":\"HS256\",\"typ\":\"JWT\"}");
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
output += ".";
output += UtilAlgorithm::base64UrlEncode(payload);
std::string signature = Hmac::hmac(shaVersion, secret, output);
output += ".";
output += UtilAlgorithm::base64UrlEncode(signature);
return output;
}
};
} // namespace ccapi
#endif // INCLUDE_CCAPI_CPP_CCAPI_JWT_H_
+130
View File
@@ -0,0 +1,130 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_LOGGER_H_
#define INCLUDE_CCAPI_CPP_CCAPI_LOGGER_H_
#ifdef _WIN32
#define CCAPI_LOGGER_FILE_SEPARATOR '\\'
#else
#define CCAPI_LOGGER_FILE_SEPARATOR '/'
#endif
#define CCAPI_LOGGER_FILE_NAME (strrchr(__FILE__, CCAPI_LOGGER_FILE_SEPARATOR) ? strrchr(__FILE__, CCAPI_LOGGER_FILE_SEPARATOR) + 1 : __FILE__)
#define CCAPI_LOGGER_LINE_NUMBER std::to_string(__LINE__)
#define CCAPI_LOGGER_THREAD_ID std::this_thread::get_id()
#define CCAPI_LOGGER_NOW std::chrono::system_clock::now()
#if defined(CCAPI_ENABLE_LOG_FATAL) || defined(CCAPI_ENABLE_LOG_ERROR) || defined(CCAPI_ENABLE_LOG_WARN) || defined(CCAPI_ENABLE_LOG_INFO) || \
defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
#define CCAPI_LOGGER_FATAL(message) \
if (::ccapi::Logger::logger) { \
::ccapi::Logger::logger->fatal(CCAPI_LOGGER_THREAD_ID, CCAPI_LOGGER_NOW, CCAPI_LOGGER_FILE_NAME, CCAPI_LOGGER_LINE_NUMBER, message); \
throw std::runtime_error(message); \
}
#else
#define CCAPI_LOGGER_FATAL(message) throw std::runtime_error(message)
#endif
#if defined(CCAPI_ENABLE_LOG_ERROR) || defined(CCAPI_ENABLE_LOG_WARN) || defined(CCAPI_ENABLE_LOG_INFO) || defined(CCAPI_ENABLE_LOG_DEBUG) || \
defined(CCAPI_ENABLE_LOG_TRACE)
#define CCAPI_LOGGER_ERROR(message) \
if (::ccapi::Logger::logger) { \
::ccapi::Logger::logger->error(CCAPI_LOGGER_THREAD_ID, CCAPI_LOGGER_NOW, CCAPI_LOGGER_FILE_NAME, CCAPI_LOGGER_LINE_NUMBER, message); \
}
#else
#define CCAPI_LOGGER_ERROR(message)
#endif
#if defined(CCAPI_ENABLE_LOG_WARN) || defined(CCAPI_ENABLE_LOG_INFO) || defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
#define CCAPI_LOGGER_WARN(message) \
if (::ccapi::Logger::logger) { \
::ccapi::Logger::logger->warn(CCAPI_LOGGER_THREAD_ID, CCAPI_LOGGER_NOW, CCAPI_LOGGER_FILE_NAME, CCAPI_LOGGER_LINE_NUMBER, message); \
}
#else
#define CCAPI_LOGGER_WARN(message)
#endif
#if defined(CCAPI_ENABLE_LOG_INFO) || defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
#define CCAPI_LOGGER_INFO(message) \
if (::ccapi::Logger::logger) { \
::ccapi::Logger::logger->info(CCAPI_LOGGER_THREAD_ID, CCAPI_LOGGER_NOW, CCAPI_LOGGER_FILE_NAME, CCAPI_LOGGER_LINE_NUMBER, message); \
}
#else
#define CCAPI_LOGGER_INFO(message)
#endif
#if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE)
#define CCAPI_LOGGER_DEBUG(message) \
if (::ccapi::Logger::logger) { \
::ccapi::Logger::logger->debug(CCAPI_LOGGER_THREAD_ID, CCAPI_LOGGER_NOW, CCAPI_LOGGER_FILE_NAME, CCAPI_LOGGER_LINE_NUMBER, message); \
}
#else
#define CCAPI_LOGGER_DEBUG(message)
#endif
#if defined(CCAPI_ENABLE_LOG_TRACE)
#define CCAPI_LOGGER_TRACE(message) \
if (::ccapi::Logger::logger) { \
::ccapi::Logger::logger->trace(CCAPI_LOGGER_THREAD_ID, CCAPI_LOGGER_NOW, CCAPI_LOGGER_FILE_NAME, CCAPI_LOGGER_LINE_NUMBER, message); \
}
#else
#define CCAPI_LOGGER_TRACE(message)
#endif
#ifdef __GNUC__
#define __ccapi_cpp_func__ __PRETTY_FUNCTION__
#else
#define __ccapi_cpp_func__ __func__
#endif
#define CCAPI_LOGGER_FUNCTION_ENTER CCAPI_LOGGER_TRACE(std::string("enter ") + std::string(__ccapi_cpp_func__))
#define CCAPI_LOGGER_FUNCTION_EXIT CCAPI_LOGGER_TRACE(std::string("exit ") + std::string(__ccapi_cpp_func__))
#include <cstring>
#include <string>
#include <thread>
#include "ccapi_cpp/ccapi_date.h"
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_util.h"
namespace ccapi {
class Logger {
public:
std::string LOG_SEVERITY_FATAL = "FATAL";
std::string LOG_SEVERITY_ERROR = "ERROR";
std::string LOG_SEVERITY_WARN = "WARN";
std::string LOG_SEVERITY_INFO = "INFO";
std::string LOG_SEVERITY_DEBUG = "DEBUG";
std::string LOG_SEVERITY_TRACE = "TRACE";
virtual ~Logger() {}
void fatal(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber,
const std::string& message) {
this->logMessagePrivate(LOG_SEVERITY_FATAL, threadId, time, fileName, lineNumber, message);
}
void error(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber,
const std::string& message) {
this->logMessagePrivate(LOG_SEVERITY_ERROR, threadId, time, fileName, lineNumber, message);
}
void warn(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber,
const std::string& message) {
this->logMessagePrivate(LOG_SEVERITY_WARN, threadId, time, fileName, lineNumber, message);
}
void info(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber,
const std::string& message) {
this->logMessagePrivate(LOG_SEVERITY_INFO, threadId, time, fileName, lineNumber, message);
}
void debug(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber,
const std::string& message) {
this->logMessagePrivate(LOG_SEVERITY_DEBUG, threadId, time, fileName, lineNumber, message);
}
void trace(const std::thread::id& threadId, const std::chrono::system_clock::time_point& time, const std::string& fileName, const std::string& lineNumber,
const std::string& message) {
this->logMessagePrivate(LOG_SEVERITY_TRACE, threadId, time, fileName, lineNumber, message);
}
static Logger* logger;
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
virtual void logMessage(const std::string& severity, const std::string& threadId, const std::string& timeISO, const std::string& fileName,
const std::string& lineNumber, const std::string& message) {}
void logMessagePrivate(const std::string& severity, const std::thread::id& threadId, const std::chrono::system_clock::time_point& time,
const std::string& fileName, const std::string& lineNumber, const std::string& message) {
std::stringstream ss;
ss << threadId;
this->logMessage(severity, ss.str(), getISOTimestamp(time), fileName, lineNumber, message);
}
template <typename T = std::chrono::nanoseconds>
static std::string getISOTimestamp(const TimePoint& tp, const std::string& fmt = "%FT%TZ") {
return date::format(fmt.c_str(), date::floor<T>(tp));
}
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_LOGGER_H_
+1000
View File
@@ -0,0 +1,1000 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_MACRO_H_
#define INCLUDE_CCAPI_CPP_CCAPI_MACRO_H_
#ifdef SWIG
#ifndef CCAPI_FINAL
#define CCAPI_FINAL
#endif
#else
#ifndef CCAPI_FINAL
#define CCAPI_FINAL final
#endif
#endif
#ifndef CCAPI_PRINT_DOUBLE_PRECISION_DEFAULT
#define CCAPI_PRINT_DOUBLE_PRECISION_DEFAULT 10
#endif
#ifndef CCAPI_DOUBLE_ERROR_DEFAULT
#define CCAPI_DOUBLE_ERROR_DEFAULT 1e-10
#endif
#ifndef CCAPI_GENERIC_PUBLIC_SUBSCRIPTION
#define CCAPI_GENERIC_PUBLIC_SUBSCRIPTION "GENERIC_PUBLIC_SUBSCRIPTION"
#endif
#ifndef CCAPI_MARKET_DEPTH
#define CCAPI_MARKET_DEPTH "MARKET_DEPTH"
#endif
#ifndef CCAPI_TRADE
#define CCAPI_TRADE "TRADE"
#endif
#ifndef CCAPI_AGG_TRADE
#define CCAPI_AGG_TRADE "AGG_TRADE"
#endif
#ifndef CCAPI_MARKET_DEPTH_MAX
#define CCAPI_MARKET_DEPTH_MAX CCAPI_MARKET_DEPTH "_MAX"
#endif
#define CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE CCAPI_MARKET_DEPTH "_SUBSCRIBED_TO_EXCHANGE"
#define CCAPI_MARKET_DEPTH_MAX_DEFAULT "1"
#ifndef CCAPI_CONFLATE_INTERVAL_MILLISECONDS
#define CCAPI_CONFLATE_INTERVAL_MILLISECONDS "CONFLATE_INTERVAL_MILLISECONDS"
#endif
#define CCAPI_CONFLATE_INTERVAL_MILLISECONDS_DEFAULT "0"
#ifndef CCAPI_CONFLATE_GRACE_PERIOD_MILLISECONDS
#define CCAPI_CONFLATE_GRACE_PERIOD_MILLISECONDS "CONFLATE_GRACE_PERIOD_MILLISECONDS"
#endif
#define CCAPI_CONFLATE_GRACE_PERIOD_MILLISECONDS_DEFAULT "-1"
#ifndef CCAPI_MARKET_DEPTH_RETURN_UPDATE
#define CCAPI_MARKET_DEPTH_RETURN_UPDATE "MARKET_DEPTH_RETURN_UPDATE"
#endif
#define CCAPI_MARKET_DEPTH_RETURN_UPDATE_DEFAULT "0"
#define CCAPI_MARKET_DEPTH_RETURN_UPDATE_ENABLE "1"
#ifndef CCAPI_EXCHANGE_NAME_COINBASE
#define CCAPI_EXCHANGE_NAME_COINBASE "coinbase"
#endif
#ifndef CCAPI_EXCHANGE_NAME_GEMINI
#define CCAPI_EXCHANGE_NAME_GEMINI "gemini"
#endif
#ifndef CCAPI_EXCHANGE_NAME_KRAKEN
#define CCAPI_EXCHANGE_NAME_KRAKEN "kraken"
#endif
#ifndef CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES
#define CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES "kraken-futures"
#endif
#ifndef CCAPI_EXCHANGE_NAME_BITSTAMP
#define CCAPI_EXCHANGE_NAME_BITSTAMP "bitstamp"
#endif
#ifndef CCAPI_EXCHANGE_NAME_BITFINEX
#define CCAPI_EXCHANGE_NAME_BITFINEX "bitfinex"
#endif
#ifndef CCAPI_EXCHANGE_NAME_BITMEX
#define CCAPI_EXCHANGE_NAME_BITMEX "bitmex"
#endif
#ifndef CCAPI_EXCHANGE_NAME_BINANCE_US
#define CCAPI_EXCHANGE_NAME_BINANCE_US "binance-us"
#endif
#ifndef CCAPI_EXCHANGE_NAME_BINANCE
#define CCAPI_EXCHANGE_NAME_BINANCE "binance"
#endif
#ifndef CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES
#define CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES "binance-usds-futures"
#endif
#ifndef CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES
#define CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES "binance-coin-futures"
#endif
#ifndef CCAPI_EXCHANGE_NAME_HUOBI
#define CCAPI_EXCHANGE_NAME_HUOBI "huobi"
#endif
#ifndef CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP
#define CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP "huobi-usdt-swap"
#endif
#ifndef CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP
#define CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP "huobi-coin-swap"
#endif
#ifndef CCAPI_EXCHANGE_NAME_OKEX
#define CCAPI_EXCHANGE_NAME_OKEX "okex"
#endif
#ifndef CCAPI_EXCHANGE_NAME_ERISX
#define CCAPI_EXCHANGE_NAME_ERISX "erisx"
#endif
#ifndef CCAPI_EXCHANGE_NAME_KUCOIN
#define CCAPI_EXCHANGE_NAME_KUCOIN "kucoin"
#endif
#ifndef CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES
#define CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES "kucoin-futures"
#endif
#ifndef CCAPI_EXCHANGE_NAME_FTX
#define CCAPI_EXCHANGE_NAME_FTX "ftx"
#endif
#ifndef CCAPI_EXCHANGE_NAME_FTX_US
#define CCAPI_EXCHANGE_NAME_FTX_US "ftx-us"
#endif
#ifndef CCAPI_EXCHANGE_NAME_DERIBIT
#define CCAPI_EXCHANGE_NAME_DERIBIT "deribit"
#endif
#ifndef CCAPI_EXCHANGE_NAME_GATEIO
#define CCAPI_EXCHANGE_NAME_GATEIO "gateio"
#endif
#ifndef CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES
#define CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES "gateio-perpetual-futures"
#endif
#ifndef CCAPI_EXCHANGE_NAME_CRYPTOCOM
#define CCAPI_EXCHANGE_NAME_CRYPTOCOM "cryptocom"
#endif
#ifndef CCAPI_EXCHANGE_NAME_BYBIT
#define CCAPI_EXCHANGE_NAME_BYBIT "bybit"
#endif
// #ifndef CCAPI_EXCHANGE_NAME_BYBIT_USDT_PERPETUAL
// #define CCAPI_EXCHANGE_NAME_BYBIT_USDT_PERPETUAL "bybit-usdt-perpetual"
// #endif
// #ifndef CCAPI_EXCHANGE_NAME_BYBIT_INVERSE_PERPETUAL
// #define CCAPI_EXCHANGE_NAME_BYBIT_INVERSE_PERPETUAL "bybit-inverse-perpetual"
// #endif
#ifndef CCAPI_EXCHANGE_NAME_ASCENDEX
#define CCAPI_EXCHANGE_NAME_ASCENDEX "ascendex"
#endif
#ifndef CCAPI_LAST_PRICE
#define CCAPI_LAST_PRICE "LAST_PRICE"
#endif
#ifndef CCAPI_LAST_SIZE
#define CCAPI_LAST_SIZE "LAST_SIZE"
#endif
#ifndef CCAPI_TRADE_ID
#define CCAPI_TRADE_ID "TRADE_ID"
#endif
#ifndef CCAPI_AGG_TRADE_ID
#define CCAPI_AGG_TRADE_ID "AGG_TRADE_ID"
#endif
#ifndef CCAPI_IS_BUYER_MAKER
#define CCAPI_IS_BUYER_MAKER "IS_BUYER_MAKER"
#endif
#ifndef CCAPI_SEQUENCE_NUMBER
#define CCAPI_SEQUENCE_NUMBER "SEQUENCE_NUMBER"
#endif
#ifndef CCAPI_IS_MAKER
#define CCAPI_IS_MAKER "IS_MAKER"
#endif
#ifndef CCAPI_BEST_BID_N_PRICE
#define CCAPI_BEST_BID_N_PRICE "BID_PRICE"
#endif
#ifndef CCAPI_BEST_BID_N_PRICE_EMPTY
#define CCAPI_BEST_BID_N_PRICE_EMPTY ""
#endif
#ifndef CCAPI_BEST_BID_N_SIZE
#define CCAPI_BEST_BID_N_SIZE "BID_SIZE"
#endif
#ifndef CCAPI_BEST_BID_N_SIZE_EMPTY
#define CCAPI_BEST_BID_N_SIZE_EMPTY ""
#endif
#ifndef CCAPI_BEST_ASK_N_PRICE
#define CCAPI_BEST_ASK_N_PRICE "ASK_PRICE"
#endif
#ifndef CCAPI_BEST_ASK_N_PRICE_EMPTY
#define CCAPI_BEST_ASK_N_PRICE_EMPTY ""
#endif
#ifndef CCAPI_BEST_ASK_N_SIZE
#define CCAPI_BEST_ASK_N_SIZE "ASK_SIZE"
#endif
#ifndef CCAPI_BEST_ASK_N_SIZE_EMPTY
#define CCAPI_BEST_ASK_N_SIZE_EMPTY ""
#endif
#ifndef CCAPI_OHLC_EMPTY
#define CCAPI_OHLC_EMPTY ""
#endif
#ifndef CCAPI_OPEN
#define CCAPI_OPEN "OPEN"
#endif
#ifndef CCAPI_HIGH
#define CCAPI_HIGH "HIGH"
#endif
#ifndef CCAPI_LOW
#define CCAPI_LOW "LOW"
#endif
#ifndef CCAPI_CLOSE
#define CCAPI_CLOSE "CLOSE"
#endif
#ifndef CCAPI_LIMIT
#define CCAPI_LIMIT "LIMIT"
#endif
#ifndef CCAPI_BASE_ASSET
#define CCAPI_BASE_ASSET "BASE_ASSET"
#endif
#ifndef CCAPI_QUOTE_ASSET
#define CCAPI_QUOTE_ASSET "QUOTE_ASSET"
#endif
#ifndef CCAPI_MARGIN_ASSET
#define CCAPI_MARGIN_ASSET "MARGIN_ASSET"
#endif
#ifndef CCAPI_ORDER_PRICE_INCREMENT
#define CCAPI_ORDER_PRICE_INCREMENT "PRICE_INCREMENT"
#endif
#ifndef CCAPI_ORDER_QUANTITY_INCREMENT
#define CCAPI_ORDER_QUANTITY_INCREMENT "QUANTITY_INCREMENT"
#endif
#ifndef CCAPI_ORDER_QUANTITY_MIN
#define CCAPI_ORDER_QUANTITY_MIN "QUANTITY_MIN"
#endif
#ifndef CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN
#define CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN "PRICE_TIMES_QUANTITY_MIN"
#endif
#define CCAPI_WEBSOCKET_COINBASE_CHANNEL_MATCH "matches"
#define CCAPI_WEBSOCKET_COINBASE_CHANNEL_LEVEL2 "level2"
#define CCAPI_WEBSOCKET_GEMINI_PARAMETER_TRADES "trades"
#define CCAPI_WEBSOCKET_GEMINI_PARAMETER_BIDS "bids"
#define CCAPI_WEBSOCKET_GEMINI_PARAMETER_OFFERS "offers"
#define CCAPI_WEBSOCKET_GEMINI_PARAMETER_TOP_OF_BOOK "top_of_book"
#define CCAPI_WEBSOCKET_KRAKEN_CHANNEL_TRADE "trade"
#define CCAPI_WEBSOCKET_KRAKEN_CHANNEL_BOOK "book"
#define CCAPI_WEBSOCKET_KRAKEN_FUTURES_CHANNEL_TRADE "trade"
#define CCAPI_WEBSOCKET_KRAKEN_FUTURES_CHANNEL_BOOK "book"
#define CCAPI_WEBSOCKET_BITSTAMP_CHANNEL_LIVE_TRADES "live_trades"
#define CCAPI_WEBSOCKET_BITSTAMP_CHANNEL_ORDER_BOOK "order_book"
#define CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES "trades"
#define CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK "book"
#define CCAPI_WEBSOCKET_BITMEX_CHANNEL_TRADE "trade"
#define CCAPI_WEBSOCKET_BITMEX_CHANNEL_QUOTE "quote"
#define CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_10 "orderBook10"
#define CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_L2_25 "orderBookL2_25"
#define CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_L2 "orderBookL2"
#define CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_TRADE "trade"
#define CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_BOOK_TICKER "bookTicker"
#define CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_PARTIAL_BOOK_DEPTH "depth"
#define CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_AGG_TRADE "aggTrade"
#define CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL "market.$symbol.trade.detail"
#define CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL_REGEX "market\\.(.+)\\.trade\\.detail"
#define CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO "market.$symbol.bbo"
#define CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO_REGEX "market\\.(.+)\\.bbo"
#define CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH "market.$symbol.depth.step0"
#define CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH_REGEX "market\\.(.+)\\.depth\\.step0"
#define CCAPI_WEBSOCKET_OKEX_CHANNEL_TRADE "trades"
#define CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH50_L2_TBT "books50-l2-tbt"
#define CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400_L2_TBT "books-l2-tbt"
#define CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5 "books5"
#define CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400 "books"
#define CCAPI_WEBSOCKET_ERISX_CHANNEL_MARKET_DATA_SUBSCRIBE "MarketDataSubscribe"
#define CCAPI_WEBSOCKET_ERISX_CHANNEL_TOP_OF_BOOK_MARKET_DATA_SUBSCRIBE "TopOfBookMarketDataSubscribe"
#define CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_MATCH "/market/match"
#define CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2 "/market/level2"
#define CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_TICKER "/market/ticker"
#define CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2DEPTH5 "/spotMarket/level2Depth5"
#define CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2DEPTH50 "/spotMarket/level2Depth50"
#define CCAPI_WEBSOCKET_KUCOIN_FUTURES_CHANNEL_MARKET_MATCH "/contractMarket/execution"
#define CCAPI_WEBSOCKET_KUCOIN_FUTURES_CHANNEL_MARKET_LEVEL2 "/contractMarket/level2"
#define CCAPI_WEBSOCKET_KUCOIN_FUTURES_CHANNEL_MARKET_TICKER "/contractMarket/tickerV2"
#define CCAPI_WEBSOCKET_KUCOIN_FUTURES_CHANNEL_MARKET_LEVEL2DEPTH5 "/contractMarket/level2Depth5"
#define CCAPI_WEBSOCKET_KUCOIN_FUTURES_CHANNEL_MARKET_LEVEL2DEPTH50 "/contractMarket/level2Depth50"
#define CCAPI_WEBSOCKET_FTX_BASE_CHANNEL_TRADES "trades"
#define CCAPI_WEBSOCKET_FTX_BASE_CHANNEL_ORDERBOOKS "orderbook"
#define CCAPI_WEBSOCKET_DERIBIT_CHANNEL_TRADES "trades.{instrument_name}.{interval}"
#define CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK "book.{instrument_name}.{group}.{depth}.{interval}"
#define CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK_TBT "book.{instrument_name}.{interval}"
#define CCAPI_WEBSOCKET_DERIBIT_CHANNEL_QUOTE "quote.{instrument_name}"
#define CCAPI_WEBSOCKET_GATEIO_CHANNEL_TRADES "spot.trades"
#define CCAPI_WEBSOCKET_GATEIO_CHANNEL_BOOK_TICKER "spot.book_ticker"
#define CCAPI_WEBSOCKET_GATEIO_CHANNEL_ORDER_BOOK "spot.order_book"
#define CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_TRADES "futures.trades"
#define CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_BOOK_TICKER "futures.book_ticker"
#define CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_ORDER_BOOK "futures.order_book"
#define CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_TRADE "trade.{instrument_name}"
#define CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_BOOK "book.{instrument_name}.{depth}"
#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_TRADE "trade"
#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER "bookTicker"
#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH "depth"
// #define CCAPI_WEBSOCKET_BYBIT_USDT_PERPETUAL_CHANNEL_TRADE "trade"
// #define CCAPI_WEBSOCKET_BYBIT_USDT_PERPETUAL_CHANNEL_ORDER_BOOK_L2_25 "orderBookL2_25"
// #define CCAPI_WEBSOCKET_BYBIT_USDT_PERPETUAL_CHANNEL_ORDER_BOOK_L2_200 "orderBookL2_200"
// #define CCAPI_WEBSOCKET_BYBIT_INVERSE_PERPETUAL_CHANNEL_TRADE "trade"
// #define CCAPI_WEBSOCKET_BYBIT_INVERSE_PERPETUAL_CHANNEL_ORDER_BOOK_L2_25 "orderBookL2_25"
// #define CCAPI_WEBSOCKET_BYBIT_INVERSE_PERPETUAL_CHANNEL_ORDER_BOOK_L2_200 "orderBookL2_200"
#define CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_TRADES "trades"
#define CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_BBO "bbo"
#define CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_DEPTH "depth"
#ifndef CCAPI_CHANNEL_ID
#define CCAPI_CHANNEL_ID "channelId"
#endif
#ifndef CCAPI_SYMBOL_ID
#define CCAPI_SYMBOL_ID "symbolId"
#endif
#ifndef CCAPI_CONNECTION_ID
#define CCAPI_CONNECTION_ID "CONNECTION_ID"
#endif
#ifndef CCAPI_REASON
#define CCAPI_REASON "REASON"
#endif
#ifndef CCAPI_MARKET_DATA
#define CCAPI_MARKET_DATA "market_data"
#endif
#ifndef CCAPI_EXECUTION_MANAGEMENT
#define CCAPI_EXECUTION_MANAGEMENT "execution_management"
#endif
#ifndef CCAPI_FIX
#define CCAPI_FIX "FIX"
#endif
#ifndef CCAPI_FIX_MARKET_DATA
#define CCAPI_FIX_MARKET_DATA "FIX_MARKET_DATA"
#endif
#ifndef CCAPI_FIX_EXECUTION_MANAGEMENT
#define CCAPI_FIX_EXECUTION_MANAGEMENT "FIX_EXECUTION_MANAGEMENT"
#endif
#ifndef CCAPI_UNKNOWN
#define CCAPI_UNKNOWN "unknown"
#endif
#define CCAPI_EM_ORDER_UPDATE "ORDER_UPDATE"
#define CCAPI_EM_PRIVATE_TRADE "PRIVATE_TRADE"
#ifndef CCAPI_EM_ORDER_SIDE
#define CCAPI_EM_ORDER_SIDE "SIDE"
#endif
#ifndef CCAPI_EM_ORDER_SIDE_BUY
#define CCAPI_EM_ORDER_SIDE_BUY "BUY"
#endif
#ifndef CCAPI_EM_ORDER_SIDE_SELL
#define CCAPI_EM_ORDER_SIDE_SELL "SELL"
#endif
#ifndef CCAPI_EM_ORDER_TYPE
#define CCAPI_EM_ORDER_TYPE "TYPE"
#endif
#ifndef CCAPI_EM_ORDER_QUANTITY
#define CCAPI_EM_ORDER_QUANTITY "QUANTITY"
#endif
#ifndef CCAPI_EM_ORDER_LIMIT_PRICE
#define CCAPI_EM_ORDER_LIMIT_PRICE "LIMIT_PRICE"
#endif
#ifndef CCAPI_EM_ORDER_LAST_EXECUTED_PRICE
#define CCAPI_EM_ORDER_LAST_EXECUTED_PRICE "LAST_EXECUTED_PRICE"
#endif
#ifndef CCAPI_EM_ORDER_LAST_EXECUTED_SIZE
#define CCAPI_EM_ORDER_LAST_EXECUTED_SIZE "LAST_EXECUTED_SIZE"
#endif
#ifndef CCAPI_EM_ORDER_FEE_QUANTITY
#define CCAPI_EM_ORDER_FEE_QUANTITY "FEE_QUANTITY"
#endif
#ifndef CCAPI_EM_ORDER_FEE_ASSET
#define CCAPI_EM_ORDER_FEE_ASSET "FEE_ASSET"
#endif
#ifndef CCAPI_EM_ACCOUNT_ID
#define CCAPI_EM_ACCOUNT_ID "ACCOUNT_ID"
#endif
#ifndef CCAPI_EM_ACCOUNT_TYPE
#define CCAPI_EM_ACCOUNT_TYPE "ACCOUNT_TYPE"
#endif
#ifndef CCAPI_EM_ASSET
#define CCAPI_EM_ASSET "ASSET"
#endif
#ifndef CCAPI_EM_QUANTITY_TOTAL
#define CCAPI_EM_QUANTITY_TOTAL "QUANTITY_TOTAL"
#endif
#ifndef CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING
#define CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING "QUANTITY_AVAILABLE_FOR_TRADING"
#endif
#ifndef CCAPI_EM_BASE_ASSET_QUANTITY_TOTAL
#define CCAPI_EM_BASE_ASSET_QUANTITY_TOTAL "BASE_ASSET_QUANTITY_TOTAL"
#endif
#ifndef CCAPI_EM_BASE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING
#define CCAPI_EM_BASE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING "BASE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING"
#endif
#ifndef CCAPI_EM_QUOTE_ASSET_QUANTITY_TOTAL
#define CCAPI_EM_QUOTE_ASSET_QUANTITY_TOTAL "QUOTE_ASSET_QUANTITY_TOTAL"
#endif
#ifndef CCAPI_EM_QUOTE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING
#define CCAPI_EM_QUOTE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING "QUOTE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING"
#endif
#ifndef CCAPI_EM_SYMBOL
#define CCAPI_EM_SYMBOL "SYMBOL"
#endif
#ifndef CCAPI_UNDERLYING_SYMBOL
#define CCAPI_UNDERLYING_SYMBOL "UNDERLYING_SYMBOL"
#endif
#ifndef CCAPI_EM_POSITION_SIDE
#define CCAPI_EM_POSITION_SIDE "POSITION_SIDE"
#endif
#ifndef CCAPI_EM_POSITION_QUANTITY
#define CCAPI_EM_POSITION_QUANTITY "QUANTITY"
#endif
#ifndef CCAPI_EM_POSITION_COST
#define CCAPI_EM_POSITION_COST "COST"
#endif
#ifndef CCAPI_EM_PARTY_ID
#define CCAPI_EM_PARTY_ID "PARTY_ID"
#endif
#ifndef CCAPI_EM_ORDER_ID
#define CCAPI_EM_ORDER_ID "ORDER_ID"
#endif
#ifndef CCAPI_EM_CLIENT_ORDER_ID
#define CCAPI_EM_CLIENT_ORDER_ID "CLIENT_ORDER_ID"
#endif
#ifndef CCAPI_EM_ORIGINAL_CLIENT_ORDER_ID
#define CCAPI_EM_ORIGINAL_CLIENT_ORDER_ID "ORIGINAL_CLIENT_ORDER_ID"
#endif
#ifndef CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY
#define CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY "CUMULATIVE_FILLED_QUANTITY"
#endif
#ifndef CCAPI_EM_ORDER_REMAINING_QUANTITY
#define CCAPI_EM_ORDER_REMAINING_QUANTITY "REMAINING_QUANTITY"
#endif
#ifndef CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY
#define CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY "CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY"
#endif
#ifndef CCAPI_EM_ORDER_INSTRUMENT
#define CCAPI_EM_ORDER_INSTRUMENT "INSTRUMENT"
#endif
#ifndef CCAPI_INSTRUMENT_TYPE
#define CCAPI_INSTRUMENT_TYPE "INSTRUMENT_TYPE"
#endif
#ifndef CCAPI_INSTRUMENT
#define CCAPI_INSTRUMENT "INSTRUMENT"
#endif
#ifndef CCAPI_EM_ORDER_STATUS
#define CCAPI_EM_ORDER_STATUS "STATUS"
#endif
#ifndef CCAPI_EM_ORDER_LEVERAGE
#define CCAPI_EM_ORDER_LEVERAGE "LEVERAGE"
#endif
#ifndef CCAPI_EM_POSITION_LEVERAGE
#define CCAPI_EM_POSITION_LEVERAGE "LEVERAGE"
#endif
#ifndef CCAPI_HTTP_STATUS_CODE
#define CCAPI_HTTP_STATUS_CODE "HTTP_STATUS_CODE"
#endif
#ifndef CCAPI_HTTP_PROTOCOL
#define CCAPI_HTTP_PROTOCOL "HTTP_PROTOCOL"
#endif
#ifndef CCAPI_HTTP_HOST
#define CCAPI_HTTP_HOST "HTTP_HOST"
#endif
#ifndef CCAPI_HTTP_PORT
#define CCAPI_HTTP_PORT "HTTP_PORT"
#endif
#ifndef CCAPI_HTTP_PATH
#define CCAPI_HTTP_PATH "HTTP_PATH"
#endif
#ifndef CCAPI_HTTP_METHOD
#define CCAPI_HTTP_METHOD "HTTP_METHOD"
#endif
#ifndef CCAPI_HTTP_HEADERS
#define CCAPI_HTTP_HEADERS "HTTP_HEADERS"
#endif
#ifndef CCAPI_HTTP_BODY
#define CCAPI_HTTP_BODY "HTTP_BODY"
#endif
#ifndef CCAPI_HTTP_QUERY_STRING
#define CCAPI_HTTP_QUERY_STRING "HTTP_QUERY_STRING"
#endif
#ifndef CCAPI_WEBSOCKET_MESSAGE_PAYLOAD
#define CCAPI_WEBSOCKET_MESSAGE_PAYLOAD "WEBSOCKET_MESSAGE_PAYLOAD"
#endif
#ifndef CCAPI_ERROR_MESSAGE
#define CCAPI_ERROR_MESSAGE "ERROR_MESSAGE"
#endif
#ifndef CCAPI_INFO_MESSAGE
#define CCAPI_INFO_MESSAGE "INFO_MESSAGE"
#endif
#define CCAPI_UNSUPPORTED_VALUE "UNSUPPORTED VALUE"
#ifndef CCAPI_CORRELATION_ID_GENERATED_LENGTH
#define CCAPI_CORRELATION_ID_GENERATED_LENGTH 8
#endif
#ifndef CCAPI_CREDENTIAL_DISPLAY_LENGTH
#define CCAPI_CREDENTIAL_DISPLAY_LENGTH 4
#endif
// start: exchange REST urls
#ifndef CCAPI_COINBASE_URL_REST_BASE
#define CCAPI_COINBASE_URL_REST_BASE "https://api.pro.coinbase.com"
#endif
#ifndef CCAPI_GEMINI_URL_REST_BASE
#define CCAPI_GEMINI_URL_REST_BASE "https://api.gemini.com"
#endif
#ifndef CCAPI_KRAKEN_URL_REST_BASE
#define CCAPI_KRAKEN_URL_REST_BASE "https://api.kraken.com"
#endif
#ifndef CCAPI_KRAKEN_FUTURES_URL_REST_BASE
#define CCAPI_KRAKEN_FUTURES_URL_REST_BASE "https://futures.kraken.com"
#endif
#ifndef CCAPI_BITSTAMP_URL_REST_BASE
#define CCAPI_BITSTAMP_URL_REST_BASE "https://www.bitstamp.net"
#endif
#ifndef CCAPI_BITFINEX_PUBLIC_URL_REST_BASE
#define CCAPI_BITFINEX_PUBLIC_URL_REST_BASE "https://api-pub.bitfinex.com"
#endif
#ifndef CCAPI_BITFINEX_PRIVATE_URL_REST_BASE
#define CCAPI_BITFINEX_PRIVATE_URL_REST_BASE "https://api.bitfinex.com"
#endif
#ifndef CCAPI_BITFINEX_GET_INSTRUMENTS_PATH
#define CCAPI_BITFINEX_GET_INSTRUMENTS_PATH "/v2/conf/pub:info:pair" // use conf/pub:info:pair:futures for futures
#endif
#ifndef CCAPI_BITMEX_URL_REST_BASE
#define CCAPI_BITMEX_URL_REST_BASE "https://www.bitmex.com"
#endif
#ifndef CCAPI_BINANCE_US_URL_REST_BASE
#define CCAPI_BINANCE_US_URL_REST_BASE "https://api.binance.us"
#endif
#ifndef CCAPI_BINANCE_US_CREATE_ORDER_PATH
#define CCAPI_BINANCE_US_CREATE_ORDER_PATH "/api/v3/order"
#endif
#ifndef CCAPI_BINANCE_US_LISTEN_KEY_PATH
#define CCAPI_BINANCE_US_LISTEN_KEY_PATH "/api/v3/userDataStream"
#endif
#ifndef CCAPI_BINANCE_URL_REST_BASE
#define CCAPI_BINANCE_URL_REST_BASE "https://api.binance.com"
#endif
#ifndef CCAPI_BINANCE_CREATE_ORDER_PATH
#define CCAPI_BINANCE_CREATE_ORDER_PATH "/api/v3/order"
#endif
#ifndef CCAPI_BINANCE_LISTEN_KEY_PATH
#define CCAPI_BINANCE_LISTEN_KEY_PATH "/api/v3/userDataStream"
#endif
#ifndef CCAPI_BINANCE_USDS_FUTURES_URL_REST_BASE
#define CCAPI_BINANCE_USDS_FUTURES_URL_REST_BASE "https://fapi.binance.com"
#endif
#ifndef CCAPI_BINANCE_USDS_FUTURES_CREATE_ORDER_PATH
#define CCAPI_BINANCE_USDS_FUTURES_CREATE_ORDER_PATH "/fapi/v1/order"
#endif
#ifndef CCAPI_BINANCE_USDS_FUTURES_LISTEN_KEY_PATH
#define CCAPI_BINANCE_USDS_FUTURES_LISTEN_KEY_PATH "/fapi/v1/listenKey"
#endif
#ifndef CCAPI_BINANCE_COIN_FUTURES_URL_REST_BASE
#define CCAPI_BINANCE_COIN_FUTURES_URL_REST_BASE "https://dapi.binance.com"
#endif
#ifndef CCAPI_BINANCE_COIN_FUTURES_CREATE_ORDER_PATH
#define CCAPI_BINANCE_COIN_FUTURES_CREATE_ORDER_PATH "/dapi/v1/order"
#endif
#ifndef CCAPI_BINANCE_COIN_FUTURES_LISTEN_KEY_PATH
#define CCAPI_BINANCE_COIN_FUTURES_LISTEN_KEY_PATH "/dapi/v1/listenKey"
#endif
#ifndef CCAPI_HUOBI_URL_REST_BASE
#define CCAPI_HUOBI_URL_REST_BASE "https://api.huobi.pro"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_URL_REST_BASE
#define CCAPI_HUOBI_USDT_SWAP_URL_REST_BASE "https://api.hbdm.com"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_URL_REST_BASE
#define CCAPI_HUOBI_COIN_SWAP_URL_REST_BASE "https://api.hbdm.com"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_CREATE_ORDER_PATH
#define CCAPI_HUOBI_USDT_SWAP_CREATE_ORDER_PATH "/linear-swap-api/v1/swap_cross_order"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_CREATE_ORDER_PATH
#define CCAPI_HUOBI_COIN_SWAP_CREATE_ORDER_PATH "/swap-api/v1/swap_order"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_CANCEL_ORDER_PATH
#define CCAPI_HUOBI_USDT_SWAP_CANCEL_ORDER_PATH "/linear-swap-api/v1/swap_cross_cancel"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_CANCEL_ORDER_PATH
#define CCAPI_HUOBI_COIN_SWAP_CANCEL_ORDER_PATH "/swap-api/v1/swap_cancel"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_GET_ORDER_PATH
#define CCAPI_HUOBI_USDT_SWAP_GET_ORDER_PATH "/linear-swap-api/v1/swap_cross_order_info"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_GET_ORDER_PATH
#define CCAPI_HUOBI_COIN_SWAP_GET_ORDER_PATH "/swap-api/v1/swap_order_info"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_GET_OPEN_ORDERS_PATH
#define CCAPI_HUOBI_USDT_SWAP_GET_OPEN_ORDERS_PATH "/linear-swap-api/v1/swap_cross_openorders"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_GET_OPEN_ORDERS_PATH
#define CCAPI_HUOBI_COIN_SWAP_GET_OPEN_ORDERS_PATH "/swap-api/v1/swap_openorders"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_CANCEL_ALL_ORDERS_PATH
#define CCAPI_HUOBI_USDT_SWAP_CANCEL_ALL_ORDERS_PATH "/linear-swap-api/v1/swap_cross_cancelall"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_CANCEL_ALL_ORDERS_PATH
#define CCAPI_HUOBI_COIN_SWAP_CANCEL_ALL_ORDERS_PATH "/swap-api/v1/swap_cancelall"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_GET_ACCOUNT_BALANCES_PATH
#define CCAPI_HUOBI_USDT_SWAP_GET_ACCOUNT_BALANCES_PATH "/linear-swap-api/v1/swap_cross_account_info"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_GET_ACCOUNT_BALANCES_PATH
#define CCAPI_HUOBI_COIN_SWAP_GET_ACCOUNT_BALANCES_PATH "/swap-api/v1/swap_account_info"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_GET_ACCOUNT_POSITIONS_PATH
#define CCAPI_HUOBI_USDT_SWAP_GET_ACCOUNT_POSITIONS_PATH "/linear-swap-api/v1/swap_cross_position_info"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_GET_ACCOUNT_POSITIONS_PATH
#define CCAPI_HUOBI_COIN_SWAP_GET_ACCOUNT_POSITIONS_PATH "/swap-api/v1/swap_position_info"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_GET_RECENT_TRADES_PATH
#define CCAPI_HUOBI_USDT_SWAP_GET_RECENT_TRADES_PATH "/linear-swap-ex/market/history/trade"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_GET_RECENT_TRADES_PATH
#define CCAPI_HUOBI_COIN_SWAP_GET_RECENT_TRADES_PATH "/swap-ex/market/history/trade"
#endif
#ifndef CCAPI_OKEX_URL_REST_BASE
#define CCAPI_OKEX_URL_REST_BASE "https://www.okex.com"
#endif
#ifndef CCAPI_ERISX_URL_REST_BASE
#define CCAPI_ERISX_URL_REST_BASE "https://trade-api.erisx.com"
#endif
#ifndef CCAPI_KUCOIN_URL_REST_BASE
#define CCAPI_KUCOIN_URL_REST_BASE "https://api.kucoin.com"
#endif
#ifndef CCAPI_KUCOIN_FUTURES_URL_REST_BASE
#define CCAPI_KUCOIN_FUTURES_URL_REST_BASE "https://api-futures.kucoin.com"
#endif
#ifndef CCAPI_FTX_URL_REST_BASE
#define CCAPI_FTX_URL_REST_BASE "https://ftx.com"
#endif
#ifndef CCAPI_FTX_US_URL_REST_BASE
#define CCAPI_FTX_US_URL_REST_BASE "https://ftx.us"
#endif
#ifndef CCAPI_DERIBIT_URL_REST_BASE
#define CCAPI_DERIBIT_URL_REST_BASE "https://www.deribit.com"
#endif
#ifndef CCAPI_GATEIO_URL_REST_BASE
#define CCAPI_GATEIO_URL_REST_BASE "https://api.gateio.ws"
#endif
#ifndef CCAPI_GATEIO_PERPETUAL_FUTURES_URL_REST_BASE
#define CCAPI_GATEIO_PERPETUAL_FUTURES_URL_REST_BASE "https://fx-api.gateio.ws"
#endif
#ifndef CCAPI_CRYPTOCOM_URL_REST_BASE
#define CCAPI_CRYPTOCOM_URL_REST_BASE "https://api.crypto.com"
#endif
#ifndef CCAPI_BYBIT_URL_REST_BASE
#define CCAPI_BYBIT_URL_REST_BASE "https://api.bybit.com"
#endif
// #ifndef CCAPI_BYBIT_USDT_PERPETUAL_URL_REST_BASE
// #define CCAPI_BYBIT_USDT_PERPETUAL_URL_REST_BASE "https://api.bybit.com"
// #endif
// #ifndef CCAPI_BYBIT_INVERSE_PERPETUAL_URL_REST_BASE
// #define CCAPI_BYBIT_INVERSE_PERPETUAL_URL_REST_BASE "https://api.bybit.com"
// #endif
#ifndef CCAPI_ASCENDEX_URL_REST_BASE
#define CCAPI_ASCENDEX_URL_REST_BASE "https://ascendex.com"
#endif
// end: exchange REST urls
// start: exchange WS urls
#ifndef CCAPI_COINBASE_URL_WS_BASE
#define CCAPI_COINBASE_URL_WS_BASE "wss://ws-feed.pro.coinbase.com"
#endif
#ifndef CCAPI_GEMINI_URL_WS_BASE
#define CCAPI_GEMINI_URL_WS_BASE "wss://api.gemini.com"
#endif
#ifndef CCAPI_KRAKEN_URL_WS_BASE
#define CCAPI_KRAKEN_URL_WS_BASE "wss://ws.kraken.com"
#endif
#ifndef CCAPI_KRAKEN_URL_WS_BASE_PRIVATE
#define CCAPI_KRAKEN_URL_WS_BASE_PRIVATE "wss://ws-auth.kraken.com"
#endif
#ifndef CCAPI_KRAKEN_FUTURES_URL_WS_BASE
#define CCAPI_KRAKEN_FUTURES_URL_WS_BASE "wss://futures.kraken.com"
#endif
#ifndef CCAPI_BITSTAMP_URL_WS_BASE
#define CCAPI_BITSTAMP_URL_WS_BASE "wss://ws.bitstamp.net"
#endif
#ifndef CCAPI_BITFINEX_PUBLIC_URL_WS_BASE
#define CCAPI_BITFINEX_PUBLIC_URL_WS_BASE "wss://api-pub.bitfinex.com"
#endif
#ifndef CCAPI_BITFINEX_PRIVATE_URL_WS_BASE
#define CCAPI_BITFINEX_PRIVATE_URL_WS_BASE "wss://api.bitfinex.com"
#endif
#ifndef CCAPI_BITMEX_URL_WS_BASE
#define CCAPI_BITMEX_URL_WS_BASE "wss://www.bitmex.com"
#endif
#ifndef CCAPI_BINANCE_US_URL_WS_BASE
#define CCAPI_BINANCE_US_URL_WS_BASE "wss://stream.binance.us:9443"
#endif
#ifndef CCAPI_BINANCE_URL_WS_BASE
#define CCAPI_BINANCE_URL_WS_BASE "wss://stream.binance.com:9443"
#endif
#ifndef CCAPI_BINANCE_USDS_FUTURES_URL_WS_BASE
#define CCAPI_BINANCE_USDS_FUTURES_URL_WS_BASE "wss://fstream.binance.com"
#endif
#ifndef CCAPI_BINANCE_COIN_FUTURES_URL_WS_BASE
#define CCAPI_BINANCE_COIN_FUTURES_URL_WS_BASE "wss://dstream.binance.com"
#endif
#ifndef CCAPI_HUOBI_URL_WS_BASE
#define CCAPI_HUOBI_URL_WS_BASE "wss://api.huobi.pro"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_URL_WS_BASE
#define CCAPI_HUOBI_USDT_SWAP_URL_WS_BASE "wss://api.hbdm.com"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_SUBSCRIBE_ORDER_DATA_TOPIC
#define CCAPI_HUOBI_USDT_SWAP_SUBSCRIBE_ORDER_DATA_TOPIC "orders_cross"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_SUBSCRIBE_MATCH_ORDER_DATA_TOPIC
#define CCAPI_HUOBI_USDT_SWAP_SUBSCRIBE_MATCH_ORDER_DATA_TOPIC "matchOrders_cross"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_URL_WS_BASE
#define CCAPI_HUOBI_COIN_SWAP_URL_WS_BASE "wss://api.hbdm.com"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_SUBSCRIBE_ORDER_DATA_TOPIC
#define CCAPI_HUOBI_COIN_SWAP_SUBSCRIBE_ORDER_DATA_TOPIC "orders"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_SUBSCRIBE_MATCH_ORDER_DATA_TOPIC
#define CCAPI_HUOBI_COIN_SWAP_SUBSCRIBE_MATCH_ORDER_DATA_TOPIC "matchOrders"
#endif
#ifndef CCAPI_OKEX_URL_WS_BASE
#define CCAPI_OKEX_URL_WS_BASE "wss://ws.okex.com:8443"
#endif
#ifndef CCAPI_OKEX_PUBLIC_WS_PATH
#define CCAPI_OKEX_PUBLIC_WS_PATH "/ws/v5/public"
#endif
#ifndef CCAPI_OKEX_PRIVATE_WS_PATH
#define CCAPI_OKEX_PRIVATE_WS_PATH "/ws/v5/private"
#endif
#ifndef CCAPI_ERISX_URL_WS_BASE
#define CCAPI_ERISX_URL_WS_BASE "wss://publicmd-api.erisx.com"
#endif
#ifndef CCAPI_FTX_URL_WS_BASE
#define CCAPI_FTX_URL_WS_BASE "wss://ftx.com"
#endif
#ifndef CCAPI_FTX_US_URL_WS_BASE
#define CCAPI_FTX_US_URL_WS_BASE "wss://ftx.us"
#endif
#ifndef CCAPI_DERIBIT_URL_WS_BASE
#define CCAPI_DERIBIT_URL_WS_BASE "wss://www.deribit.com"
#endif
#ifndef CCAPI_GATEIO_URL_WS_BASE
#define CCAPI_GATEIO_URL_WS_BASE "wss://api.gateio.ws"
#endif
#ifndef CCAPI_GATEIO_PERPETUAL_FUTURES_URL_WS_BASE
#define CCAPI_GATEIO_PERPETUAL_FUTURES_URL_WS_BASE "wss://fx-ws.gateio.ws"
#endif
#ifndef CCAPI_CRYPTOCOM_URL_WS_BASE
#define CCAPI_CRYPTOCOM_URL_WS_BASE "wss://stream.crypto.com"
#endif
#ifndef CCAPI_BYBIT_URL_WS_BASE
#define CCAPI_BYBIT_URL_WS_BASE "wss://stream.bybit.com"
#endif
// #ifndef CCAPI_BYBIT_USDT_PERPETUAL_URL_WS_BASE
// #define CCAPI_BYBIT_USDT_PERPETUAL_URL_WS_BASE "https://api.bybit.com"
// #endif
// #ifndef CCAPI_BYBIT_INVERSE_PERPETUAL_URL_WS_BASE
// #define CCAPI_BYBIT_INVERSE_PERPETUAL_URL_WS_BASE "https://api.bybit.com"
// #endif
#ifndef CCAPI_ASCENDEX_URL_WS_BASE
#define CCAPI_ASCENDEX_URL_WS_BASE "wss://ascendex.com"
#endif
// end: exchange WS urls
// start: exchange FIX urls
#ifndef CCAPI_COINBASE_URL_FIX_BASE
#define CCAPI_COINBASE_URL_FIX_BASE "tcp+ssl://fix.pro.coinbase.com:4198"
#endif
#ifndef CCAPI_GEMINI_URL_FIX_HOST
#define CCAPI_GEMINI_URL_FIX_HOST ""
#endif
#ifndef CCAPI_GEMINI_URL_FIX_PORT
#define CCAPI_GEMINI_URL_FIX_PORT ""
#endif
#ifndef CCAPI_FTX_URL_FIX_BASE
#define CCAPI_FTX_URL_FIX_BASE "tcp+ssl://fix.ftx.com:4363"
#endif
#ifndef CCAPI_FTX_US_URL_FIX_BASE
#define CCAPI_FTX_US_URL_FIX_BASE "tcp+ssl://fix.ftx.us:4363"
#endif
#ifndef CCAPI_DERIBIT_URL_FIX_BASE
#define CCAPI_DERIBIT_URL_FIX_BASE "www.deribit.com:9883"
#endif
// end: exchange FIX urls
// start: exchange API credentials
#ifndef CCAPI_COINBASE_API_KEY
#define CCAPI_COINBASE_API_KEY "COINBASE_API_KEY"
#endif
#ifndef CCAPI_COINBASE_API_SECRET
#define CCAPI_COINBASE_API_SECRET "COINBASE_API_SECRET"
#endif
#ifndef CCAPI_COINBASE_API_PASSPHRASE
#define CCAPI_COINBASE_API_PASSPHRASE "COINBASE_API_PASSPHRASE"
#endif
#ifndef CCAPI_GEMINI_API_KEY
#define CCAPI_GEMINI_API_KEY "GEMINI_API_KEY"
#endif
#ifndef CCAPI_GEMINI_API_SECRET
#define CCAPI_GEMINI_API_SECRET "GEMINI_API_SECRET"
#endif
#ifndef CCAPI_GEMINI_API_SENDER_COMP_ID
#define CCAPI_GEMINI_API_SENDER_COMP_ID ""
#endif
#ifndef CCAPI_GEMINI_API_TARGET_COMP_ID
#define CCAPI_GEMINI_API_TARGET_COMP_ID ""
#endif
#ifndef CCAPI_KRAKEN_API_KEY
#define CCAPI_KRAKEN_API_KEY "KRAKEN_API_KEY"
#endif
#ifndef CCAPI_KRAKEN_API_SECRET
#define CCAPI_KRAKEN_API_SECRET "KRAKEN_API_SECRET"
#endif
#ifndef CCAPI_KRAKEN_FUTURES_API_KEY
#define CCAPI_KRAKEN_FUTURES_API_KEY "KRAKEN_FUTURES_API_KEY"
#endif
#ifndef CCAPI_KRAKEN_FUTURES_API_SECRET
#define CCAPI_KRAKEN_FUTURES_API_SECRET "KRAKEN_FUTURES_API_SECRET"
#endif
#ifndef CCAPI_BITSTAMP_API_KEY
#define CCAPI_BITSTAMP_API_KEY "BITSTAMP_API_KEY"
#endif
#ifndef CCAPI_BITSTAMP_API_SECRET
#define CCAPI_BITSTAMP_API_SECRET "BITSTAMP_API_SECRET"
#endif
#ifndef CCAPI_BITFINEX_API_KEY
#define CCAPI_BITFINEX_API_KEY "BITFINEX_API_KEY"
#endif
#ifndef CCAPI_BITFINEX_API_SECRET
#define CCAPI_BITFINEX_API_SECRET "BITFINEX_API_SECRET"
#endif
#ifndef CCAPI_BITMEX_API_KEY
#define CCAPI_BITMEX_API_KEY "BITMEX_API_KEY"
#endif
#ifndef CCAPI_BITMEX_API_SECRET
#define CCAPI_BITMEX_API_SECRET "BITMEX_API_SECRET"
#endif
#ifndef CCAPI_BINANCE_US_API_KEY
#define CCAPI_BINANCE_US_API_KEY "BINANCE_US_API_KEY"
#endif
#ifndef CCAPI_BINANCE_US_API_SECRET
#define CCAPI_BINANCE_US_API_SECRET "BINANCE_US_API_SECRET"
#endif
#ifndef CCAPI_BINANCE_API_KEY
#define CCAPI_BINANCE_API_KEY "BINANCE_API_KEY"
#endif
#ifndef CCAPI_BINANCE_API_SECRET
#define CCAPI_BINANCE_API_SECRET "BINANCE_API_SECRET"
#endif
#ifndef CCAPI_BINANCE_USDS_FUTURES_API_KEY
#define CCAPI_BINANCE_USDS_FUTURES_API_KEY "BINANCE_USDS_FUTURES_API_KEY"
#endif
#ifndef CCAPI_BINANCE_USDS_FUTURES_API_SECRET
#define CCAPI_BINANCE_USDS_FUTURES_API_SECRET "BINANCE_USDS_FUTURES_API_SECRET"
#endif
#ifndef CCAPI_BINANCE_COIN_FUTURES_API_KEY
#define CCAPI_BINANCE_COIN_FUTURES_API_KEY "BINANCE_COIN_FUTURES_API_KEY"
#endif
#ifndef CCAPI_BINANCE_COIN_FUTURES_API_SECRET
#define CCAPI_BINANCE_COIN_FUTURES_API_SECRET "BINANCE_COIN_FUTURES_API_SECRET"
#endif
#ifndef CCAPI_HUOBI_API_KEY
#define CCAPI_HUOBI_API_KEY "HUOBI_API_KEY"
#endif
#ifndef CCAPI_HUOBI_API_SECRET
#define CCAPI_HUOBI_API_SECRET "HUOBI_API_SECRET"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_API_KEY
#define CCAPI_HUOBI_USDT_SWAP_API_KEY "HUOBI_USDT_SWAP_API_KEY"
#endif
#ifndef CCAPI_HUOBI_USDT_SWAP_API_SECRET
#define CCAPI_HUOBI_USDT_SWAP_API_SECRET "HUOBI_USDT_SWAP_API_SECRET"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_API_KEY
#define CCAPI_HUOBI_COIN_SWAP_API_KEY "HUOBI_COIN_SWAP_API_KEY"
#endif
#ifndef CCAPI_HUOBI_COIN_SWAP_API_SECRET
#define CCAPI_HUOBI_COIN_SWAP_API_SECRET "HUOBI_COIN_SWAP_API_SECRET"
#endif
#ifndef CCAPI_OKEX_API_KEY
#define CCAPI_OKEX_API_KEY "OKEX_API_KEY"
#endif
#ifndef CCAPI_OKEX_API_SECRET
#define CCAPI_OKEX_API_SECRET "OKEX_API_SECRET"
#endif
#ifndef CCAPI_OKEX_API_PASSPHRASE
#define CCAPI_OKEX_API_PASSPHRASE "OKEX_API_PASSPHRASE"
#endif
#ifndef CCAPI_OKEX_API_X_SIMULATED_TRADING
#define CCAPI_OKEX_API_X_SIMULATED_TRADING "OKEX_API_X_SIMULATED_TRADING"
#endif
#ifndef CCAPI_ERISX_API_KEY
#define CCAPI_ERISX_API_KEY "ERISX_API_KEY"
#endif
#ifndef CCAPI_ERISX_API_SECRET
#define CCAPI_ERISX_API_SECRET "ERISX_API_SECRET"
#endif
#ifndef CCAPI_KUCOIN_API_KEY
#define CCAPI_KUCOIN_API_KEY "KUCOIN_API_KEY"
#endif
#ifndef CCAPI_KUCOIN_API_SECRET
#define CCAPI_KUCOIN_API_SECRET "KUCOIN_API_SECRET"
#endif
#ifndef CCAPI_KUCOIN_API_PASSPHRASE
#define CCAPI_KUCOIN_API_PASSPHRASE "KUCOIN_API_PASSPHRASE"
#endif
#ifndef CCAPI_KUCOIN_API_KEY_VERSION
#define CCAPI_KUCOIN_API_KEY_VERSION "KUCOIN_API_KEY_VERSION"
#endif
#ifndef CCAPI_KUCOIN_FUTURES_API_KEY
#define CCAPI_KUCOIN_FUTURES_API_KEY "KUCOIN_FUTURES_API_KEY"
#endif
#ifndef CCAPI_KUCOIN_FUTURES_API_SECRET
#define CCAPI_KUCOIN_FUTURES_API_SECRET "KUCOIN_FUTURES_API_SECRET"
#endif
#ifndef CCAPI_KUCOIN_FUTURES_API_PASSPHRASE
#define CCAPI_KUCOIN_FUTURES_API_PASSPHRASE "KUCOIN_FUTURES_API_PASSPHRASE"
#endif
#ifndef CCAPI_KUCOIN_FUTURES_API_KEY_VERSION
#define CCAPI_KUCOIN_FUTURES_API_KEY_VERSION "KUCOIN_FUTURES_API_KEY_VERSION"
#endif
#ifndef CCAPI_FTX_API_KEY
#define CCAPI_FTX_API_KEY "FTX_API_KEY"
#endif
#ifndef CCAPI_FTX_API_SECRET
#define CCAPI_FTX_API_SECRET "FTX_API_SECRET"
#endif
#ifndef CCAPI_FTX_API_SUBACCOUNT
#define CCAPI_FTX_API_SUBACCOUNT "FTX_API_SUBACCOUNT"
#endif
#ifndef CCAPI_FTX_US_API_KEY
#define CCAPI_FTX_US_API_KEY "FTX_US_API_KEY"
#endif
#ifndef CCAPI_FTX_US_API_SECRET
#define CCAPI_FTX_US_API_SECRET "FTX_US_API_SECRET"
#endif
#ifndef CCAPI_FTX_US_API_SUBACCOUNT
#define CCAPI_FTX_US_API_SUBACCOUNT "FTX_US_API_SUBACCOUNT"
#endif
#ifndef CCAPI_DERIBIT_CLIENT_ID
#define CCAPI_DERIBIT_CLIENT_ID "DERIBIT_CLIENT_ID"
#endif
#ifndef CCAPI_DERIBIT_CLIENT_SECRET
#define CCAPI_DERIBIT_CLIENT_SECRET "DERIBIT_CLIENT_SECRET"
#endif
#ifndef CCAPI_GATEIO_API_KEY
#define CCAPI_GATEIO_API_KEY "GATEIO_API_KEY"
#endif
#ifndef CCAPI_GATEIO_API_SECRET
#define CCAPI_GATEIO_API_SECRET "GATEIO_API_SECRET"
#endif
#ifndef CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY
#define CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY "GATEIO_PERPETUAL_FUTURES_API_KEY"
#endif
#ifndef CCAPI_GATEIO_PERPETUAL_FUTURES_API_SECRET
#define CCAPI_GATEIO_PERPETUAL_FUTURES_API_SECRET "GATEIO_PERPETUAL_FUTURES_API_SECRET"
#endif
#ifndef CCAPI_CRYPTOCOM_API_KEY
#define CCAPI_CRYPTOCOM_API_KEY "CRYPTOCOM_API_KEY"
#endif
#ifndef CCAPI_CRYPTOCOM_API_SECRET
#define CCAPI_CRYPTOCOM_API_SECRET "CRYPTOCOM_API_SECRET"
#endif
#ifndef CCAPI_BYBIT_API_KEY
#define CCAPI_BYBIT_API_KEY "BYBIT_API_KEY"
#endif
#ifndef CCAPI_BYBIT_API_SECRET
#define CCAPI_BYBIT_API_SECRET "BYBIT_API_SECRET"
#endif
// #ifndef CCAPI_BYBIT_USDT_PERPETUAL_API_KEY
// #define CCAPI_BYBIT_USDT_PERPETUAL_API_KEY "BYBIT_USDT_PERPETUAL_API_KEY"
// #endif
// #ifndef CCAPI_BYBIT_USDT_PERPETUAL_API_SECRET
// #define CCAPI_BYBIT_USDT_PERPETUAL_API_SECRET "BYBIT_USDT_PERPETUAL_API_SECRET"
// #endif
// #ifndef CCAPI_BYBIT_INVERSE_PERPETUAL_API_KEY
// #define CCAPI_BYBIT_INVERSE_PERPETUAL_API_KEY "BYBIT_INVERSE_PERPETUAL_API_KEY"
// #endif
// #ifndef CCAPI_BYBIT_INVERSE_PERPETUAL_API_SECRET
// #define CCAPI_BYBIT_INVERSE_PERPETUAL_API_SECRET "BYBIT_INVERSE_PERPETUAL_API_SECRET"
// #endif
#ifndef CCAPI_ASCENDEX_API_KEY
#define CCAPI_ASCENDEX_API_KEY "ASCENDEX_API_KEY"
#endif
#ifndef CCAPI_ASCENDEX_API_SECRET
#define CCAPI_ASCENDEX_API_SECRET "ASCENDEX_API_SECRET"
#endif
#ifndef CCAPI_ASCENDEX_API_ACCOUNT_GROUP
#define CCAPI_ASCENDEX_API_ACCOUNT_GROUP "ASCENDEX_API_ACCOUNT_GROUP"
#endif
// end: exchange API credentials
#define CCAPI_HTTP_PORT_DEFAULT "80"
#define CCAPI_HTTPS_PORT_DEFAULT "443"
#ifndef CCAPI_BITMEX_API_RECEIVE_WINDOW_SECONDS
#define CCAPI_BITMEX_API_RECEIVE_WINDOW_SECONDS 5
#endif
#ifndef CCAPI_BITFINEX_STREAM_TRADE_RAW_MESSAGE_TYPE
#define CCAPI_BITFINEX_STREAM_TRADE_RAW_MESSAGE_TYPE "tu"
#endif
#define CCAPI_AUTHORIZATION "AUTHORIZATION"
#ifndef CCAPI_HFFIX_READ_MESSAGE_CHUNK_SIZE
#define CCAPI_HFFIX_READ_MESSAGE_CHUNK_SIZE 4096
#endif
#ifndef CCAPI_FIX_PROTOCOL_VERSION_COINBASE
#define CCAPI_FIX_PROTOCOL_VERSION_COINBASE "FIX.4.2"
#endif
#ifndef CCAPI_FIX_PROTOCOL_VERSION_GEMINI
#define CCAPI_FIX_PROTOCOL_VERSION_GEMINI "FIX.4.4"
#endif
#ifndef CCAPI_FIX_PROTOCOL_VERSION_FTX
#define CCAPI_FIX_PROTOCOL_VERSION_FTX "FIX.4.2"
#endif
#ifndef CCAPI_FIX_PROTOCOL_VERSION_FTX_US
#define CCAPI_FIX_PROTOCOL_VERSION_FTX_US "FIX.4.2"
#endif
#ifndef CCAPI_FIX_PROTOCOL_VERSION_DERIBIT
#define CCAPI_FIX_PROTOCOL_VERSION_DERIBIT "FIX.4.4"
#endif
#endif // INCLUDE_CCAPI_CPP_CCAPI_MACRO_H_
@@ -0,0 +1,171 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_MARKET_DATA_MESSAGE_H_
#define INCLUDE_CCAPI_CPP_CCAPI_MARKET_DATA_MESSAGE_H_
#include "ccapi_cpp/ccapi_logger.h"
#include "ccapi_cpp/ccapi_util_private.h"
// #include "ccapi_message.h"
namespace ccapi {
class MarketDataMessage CCAPI_FINAL {
public:
enum class Type {
UNKNOWN,
MARKET_DATA_EVENTS_MARKET_DEPTH,
MARKET_DATA_EVENTS_TRADE,
MARKET_DATA_EVENTS_AGG_TRADE,
};
enum class RecapType {
UNKNOWN,
NONE, // normal data tick; not a recap
SOLICITED, // generated on request by subscriber
};
static std::string recapTypeToString(RecapType recapType) {
std::string output;
switch (recapType) {
case RecapType::UNKNOWN:
output = "UNKNOWN";
break;
case RecapType::NONE:
output = "NONE";
break;
case RecapType::SOLICITED:
output = "SOLICITED";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
return output;
}
enum class DataType {
BID = 0,
ASK = 1,
TRADE = 2,
AGG_TRADE = 3,
};
static std::string dataTypeToString(DataType dataType) {
std::string output;
switch (dataType) {
case DataType::BID:
output = "BID";
break;
case DataType::ASK:
output = "ASK";
break;
case DataType::TRADE:
output = "TRADE";
break;
case DataType::AGG_TRADE:
output = "AGG_TRADE";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
return output;
}
enum class DataFieldType {
PRICE = 0,
SIZE = 1,
TRADE_ID = 2,
AGG_TRADE_ID = 3,
IS_BUYER_MAKER = 4,
SEQUENCE_NUMBER = 5,
};
static std::string dataFieldTypeToString(DataFieldType dataFieldType) {
std::string output;
switch (dataFieldType) {
case DataFieldType::PRICE:
output = "PRICE";
break;
case DataFieldType::SIZE:
output = "SIZE";
break;
case DataFieldType::TRADE_ID:
output = "TRADE_ID";
break;
case DataFieldType::AGG_TRADE_ID:
output = "AGG_TRADE_ID";
break;
case DataFieldType::IS_BUYER_MAKER:
output = "IS_BUYER_MAKER";
break;
case DataFieldType::SEQUENCE_NUMBER:
output = "SEQUENCE_NUMBER";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
return output;
}
typedef std::map<DataFieldType, std::string> TypeForDataPoint;
typedef std::map<DataType, std::vector<std::map<DataFieldType, std::string> > > TypeForData;
static std::string dataToString(const TypeForData& data) {
std::string output1 = "{";
auto size1 = data.size();
auto i1 = 0;
for (const auto& elem1 : data) {
output1 += dataTypeToString(elem1.first);
output1 += "=";
std::string output2 = "[ ";
auto size2 = elem1.second.size();
auto i2 = 0;
for (const auto& elem2 : elem1.second) {
std::string output3 = "{";
auto size3 = elem2.size();
auto i3 = 0;
for (const auto& elem3 : elem2) {
output3 += dataFieldTypeToString(elem3.first);
output3 += "=";
output3 += ccapi::toString(elem3.second);
if (i3 < size3 - 1) {
output3 += ", ";
}
++i3;
}
output3 += "}";
output2 += output3;
if (i2 < size2 - 1) {
output2 += ", ";
}
++i2;
}
output2 += " ]";
output1 += output2;
if (i1 < size1 - 1) {
output1 += ", ";
}
++i1;
}
output1 += "}";
return output1;
}
static std::string typeToString(Type type) {
std::string output;
switch (type) {
case Type::UNKNOWN:
output = "UNKNOWN";
break;
case Type::MARKET_DATA_EVENTS_MARKET_DEPTH:
output = "MARKET_DATA_EVENTS_MARKET_DEPTH";
break;
case Type::MARKET_DATA_EVENTS_TRADE:
output = "MARKET_DATA_EVENTS_TRADE";
break;
case Type::MARKET_DATA_EVENTS_AGG_TRADE:
output = "MARKET_DATA_EVENTS_AGG_TRADE";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
return output;
}
std::string toString() const {
std::string output = "MarketDataMessage [type = " + typeToString(type) + ", recapType = " + recapTypeToString(recapType) + ", tp = " + ccapi::toString(tp) +
", exchangeSubscriptionId = " + exchangeSubscriptionId + ", data = " + dataToString(data) + "]";
return output;
}
Type type{Type::UNKNOWN};
RecapType recapType{RecapType::UNKNOWN};
TimePoint tp{std::chrono::seconds{0}};
std::string exchangeSubscriptionId;
TypeForData data;
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_MARKET_DATA_MESSAGE_H_
+228
View File
@@ -0,0 +1,228 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_MESSAGE_H_
#define INCLUDE_CCAPI_CPP_CCAPI_MESSAGE_H_
#include <chrono>
#include <vector>
#include "ccapi_cpp/ccapi_element.h"
#include "ccapi_cpp/ccapi_logger.h"
namespace ccapi {
class Message CCAPI_FINAL {
public:
enum class RecapType {
UNKNOWN,
NONE, // normal data tick; not a recap
SOLICITED, // generated on request by subscriber
};
static std::string recapTypeToString(RecapType recapType) {
std::string output;
switch (recapType) {
case RecapType::UNKNOWN:
output = "UNKNOWN";
break;
case RecapType::NONE:
output = "NONE";
break;
case RecapType::SOLICITED:
output = "SOLICITED";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
return output;
}
enum class Type {
UNKNOWN,
AUTHORIZATION_SUCCESS,
AUTHORIZATION_FAILURE,
MARKET_DATA_EVENTS_MARKET_DEPTH,
MARKET_DATA_EVENTS_TRADE,
MARKET_DATA_EVENTS_AGG_TRADE,
EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE,
EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE,
SUBSCRIPTION_STARTED,
SUBSCRIPTION_FAILURE,
SESSION_CONNECTION_UP,
SESSION_CONNECTION_DOWN,
INCORRECT_STATE_FOUND,
CREATE_ORDER,
CANCEL_ORDER,
GET_ORDER,
GET_OPEN_ORDERS,
CANCEL_OPEN_ORDERS,
GET_ACCOUNTS,
GET_ACCOUNT_BALANCES,
GET_ACCOUNT_POSITIONS,
GET_RECENT_TRADES,
GET_RECENT_AGG_TRADES,
GET_INSTRUMENT,
GET_INSTRUMENTS,
RESPONSE_ERROR,
REQUEST_FAILURE,
GENERIC_ERROR,
CUSTOM,
FIX,
FIX_FAILURE,
GENERIC_PUBLIC_REQUEST,
GENERIC_PUBLIC_SUBSCRIPTION,
GENERIC_PRIVATE_REQUEST,
};
static std::string typeToString(Type type) {
std::string output;
switch (type) {
case Type::UNKNOWN:
output = "UNKNOWN";
break;
case Type::MARKET_DATA_EVENTS_MARKET_DEPTH:
output = "MARKET_DATA_EVENTS_MARKET_DEPTH";
break;
case Type::MARKET_DATA_EVENTS_TRADE:
output = "MARKET_DATA_EVENTS_TRADE";
break;
case Type::MARKET_DATA_EVENTS_AGG_TRADE:
output = "MARKET_DATA_EVENTS_AGG_TRADE";
break;
case Type::AUTHORIZATION_SUCCESS:
output = "AUTHORIZATION_SUCCESS";
break;
case Type::AUTHORIZATION_FAILURE:
output = "AUTHORIZATION_FAILURE";
break;
case Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE:
output = "EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE";
break;
case Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE:
output = "EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE";
break;
case Type::SUBSCRIPTION_STARTED:
output = "SUBSCRIPTION_STARTED";
break;
case Type::SUBSCRIPTION_FAILURE:
output = "SUBSCRIPTION_FAILURE";
break;
case Type::SESSION_CONNECTION_UP:
output = "SESSION_CONNECTION_UP";
break;
case Type::SESSION_CONNECTION_DOWN:
output = "SESSION_CONNECTION_DOWN";
break;
case Type::INCORRECT_STATE_FOUND:
output = "INCORRECT_STATE_FOUND";
break;
case Type::CREATE_ORDER:
output = "CREATE_ORDER";
break;
case Type::CANCEL_ORDER:
output = "CANCEL_ORDER";
break;
case Type::GET_ORDER:
output = "GET_ORDER";
break;
case Type::GET_OPEN_ORDERS:
output = "GET_OPEN_ORDERS";
break;
case Type::CANCEL_OPEN_ORDERS:
output = "CANCEL_OPEN_ORDERS";
break;
case Type::GET_ACCOUNTS:
output = "GET_ACCOUNTS";
break;
case Type::GET_ACCOUNT_BALANCES:
output = "GET_ACCOUNT_BALANCES";
break;
case Type::GET_ACCOUNT_POSITIONS:
output = "GET_ACCOUNT_POSITIONS";
break;
case Type::GET_RECENT_TRADES:
output = "GET_RECENT_TRADES";
break;
case Type::GET_RECENT_AGG_TRADES:
output = "GET_RECENT_AGG_TRADES";
break;
case Type::GET_INSTRUMENT:
output = "GET_INSTRUMENT";
break;
case Type::GET_INSTRUMENTS:
output = "GET_INSTRUMENTS";
break;
case Type::RESPONSE_ERROR:
output = "RESPONSE_ERROR";
break;
case Type::REQUEST_FAILURE:
output = "REQUEST_FAILURE";
break;
case Type::GENERIC_ERROR:
output = "GENERIC_ERROR";
break;
case Type::CUSTOM:
output = "CUSTOM";
break;
case Type::FIX:
output = "FIX";
break;
case Type::FIX_FAILURE:
output = "FIX_FAILURE";
break;
case Type::GENERIC_PUBLIC_REQUEST:
output = "GENERIC_PUBLIC_REQUEST";
break;
case Type::GENERIC_PUBLIC_SUBSCRIPTION:
output = "GENERIC_PUBLIC_SUBSCRIPTION";
break;
case Type::GENERIC_PRIVATE_REQUEST:
output = "GENERIC_PRIVATE_REQUEST";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
return output;
}
std::string toString() const {
std::string output = "Message [type = " + typeToString(type) + ", recapType = " + recapTypeToString(recapType) +
", time = " + UtilTime::getISOTimestamp(time) + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) +
", elementList = " + ccapi::firstNToString(elementList, 10) + ", correlationIdList = " + ccapi::toString(correlationIdList) + "]";
return output;
}
std::string toStringPretty(const int space = 2, const int leftToIndent = 0, const bool indentFirstLine = true) const {
std::string sl(leftToIndent, ' ');
std::string ss(leftToIndent + space, ' ');
std::string output = (indentFirstLine ? sl : "") + "Message [\n" + ss + "type = " + typeToString(type) + ",\n" + ss +
"recapType = " + recapTypeToString(recapType) + ",\n" + ss + "time = " + UtilTime::getISOTimestamp(time) + ",\n" + ss +
"timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ",\n" + ss +
"elementList = " + ccapi::firstNToStringPretty(elementList, 10, space, space + leftToIndent, false) + ",\n" + ss +
"correlationIdList = " + ccapi::toString(correlationIdList) + "\n" + sl + "]";
return output;
}
const std::vector<Element>& getElementList() const { return elementList; }
void setElementList(const std::vector<Element>& elementList) { this->elementList = elementList; }
void setElementList(std::vector<Element>& elementList) { this->elementList = std::move(elementList); }
const std::vector<std::string>& getCorrelationIdList() const { return correlationIdList; }
void setCorrelationIdList(const std::vector<std::string>& correlationIdList) { this->correlationIdList = correlationIdList; }
// 'getTime' only works in C++. For other languages, please use 'getTimeISO'.
TimePoint getTime() const { return time; }
std::string getTimeISO() const { return UtilTime::getISOTimestamp(time); }
std::pair<long long, long long> getTimeUnix() const { return UtilTime::divide(time); }
std::pair<long long, long long> getTimePair() const { return UtilTime::divide(time); }
void setTime(TimePoint time) { this->time = time; }
RecapType getRecapType() const { return recapType; }
void setRecapType(RecapType recapType) { this->recapType = recapType; }
Type getType() const { return type; }
void setType(Type type) { this->type = type; }
// 'getTimeReceived' only works in C++. For other languages, please use 'getTimeReceivedISO'.
TimePoint getTimeReceived() const { return timeReceived; }
std::string getTimeReceivedISO() const { return UtilTime::getISOTimestamp(timeReceived); }
std::pair<long long, long long> getTimeReceivedUnix() const { return UtilTime::divide(timeReceived); }
std::pair<long long, long long> getTimeReceivedPair() const { return UtilTime::divide(timeReceived); }
void setTimeReceived(TimePoint timeReceived) { this->timeReceived = timeReceived; }
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
TimePoint time{std::chrono::seconds{0}};
TimePoint timeReceived{std::chrono::seconds{0}};
std::vector<Element> elementList;
std::vector<std::string> correlationIdList;
Type type{Type::UNKNOWN};
RecapType recapType{RecapType::UNKNOWN};
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_MESSAGE_H_
+67
View File
@@ -0,0 +1,67 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_QUEUE_H_
#define INCLUDE_CCAPI_CPP_CCAPI_QUEUE_H_
#include <mutex>
#include <queue>
#include <vector>
#include "ccapi_cpp/ccapi_logger.h"
namespace ccapi {
template <class T>
class Queue {
public:
std::string EXCEPTION_QUEUE_FULL = "queue is full";
std::string EXCEPTION_QUEUE_EMPTY = "queue is empty";
explicit Queue(const size_t maxSize = 0) : maxSize(maxSize) {}
void pushBack(T&& t) {
std::lock_guard<std::mutex> lock(this->m);
if (this->maxSize <= 0 || this->queue.size() < this->maxSize) {
CCAPI_LOGGER_TRACE("this->queue.size() = " + size_tToString(this->queue.size()));
this->queue.push_back(t);
} else {
throw std::runtime_error(EXCEPTION_QUEUE_FULL);
}
}
T popBack() {
std::lock_guard<std::mutex> lock(this->m);
if (this->queue.empty()) {
throw std::runtime_error(EXCEPTION_QUEUE_EMPTY);
} else {
T t = std::move(this->queue.back());
this->queue.pop_back();
return t;
}
}
std::vector<T> purge() {
std::lock_guard<std::mutex> lock(this->m);
std::vector<T> p;
std::swap(p, this->queue);
return p;
}
void removeAll(std::vector<T>& c) {
std::lock_guard<std::mutex> lock(this->m);
if (c.empty()) {
c = std::move(this->queue);
} else {
c.reserve(c.size() + this->queue.size());
std::move(std::begin(this->queue), std::end(this->queue), std::back_inserter(c));
}
this->queue.clear();
}
size_t size() const {
std::lock_guard<std::mutex> lock(this->m);
return this->queue.size();
}
bool empty() const {
std::lock_guard<std::mutex> lock(this->m);
return this->queue.empty();
}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
std::vector<T> queue;
mutable std::mutex m;
size_t maxSize{};
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_QUEUE_H_
+170
View File
@@ -0,0 +1,170 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_REQUEST_H_
#define INCLUDE_CCAPI_CPP_CCAPI_REQUEST_H_
#include <condition_variable>
#include <map>
#include <mutex>
#include <string>
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_util_private.h"
namespace ccapi {
class Request CCAPI_FINAL {
public:
static constexpr int operationTypeCustom = 0x100;
static constexpr int operationTypeGenericPublicRequest = 0x200;
static constexpr int operationTypeGenericPrivateRequest = 0x300;
static constexpr int operationTypeFix = 0x400;
static constexpr int operationTypeMarketData = 0x500;
static constexpr int operationTypeExecutionManagement = 0x600;
static constexpr int operationTypeExecutionManagementOrder = operationTypeExecutionManagement;
static constexpr int operationTypeExecutionManagementAccount = 0x700;
enum class Operation {
CUSTOM = operationTypeCustom,
GENERIC_PUBLIC_REQUEST = operationTypeGenericPublicRequest,
GENERIC_PRIVATE_REQUEST = operationTypeGenericPrivateRequest,
FIX = operationTypeFix,
GET_RECENT_TRADES = operationTypeMarketData,
GET_RECENT_AGG_TRADES,
GET_INSTRUMENT,
GET_INSTRUMENTS,
CREATE_ORDER = operationTypeExecutionManagementOrder,
CANCEL_ORDER,
GET_ORDER,
GET_OPEN_ORDERS,
CANCEL_OPEN_ORDERS,
GET_ACCOUNTS = operationTypeExecutionManagementAccount,
GET_ACCOUNT_BALANCES,
GET_ACCOUNT_POSITIONS,
};
static std::string operationToString(Operation operation) {
std::string output;
switch (operation) {
case Operation::CUSTOM:
output = "CUSTOM";
break;
case Operation::GENERIC_PUBLIC_REQUEST:
output = "GENERIC_PUBLIC_REQUEST";
break;
case Operation::GENERIC_PRIVATE_REQUEST:
output = "GENERIC_PRIVATE_REQUEST";
break;
case Operation::FIX:
output = "FIX";
break;
case Operation::GET_RECENT_TRADES:
output = "GET_RECENT_TRADES";
break;
case Operation::GET_RECENT_AGG_TRADES:
output = "GET_RECENT_AGG_TRADES";
break;
case Operation::GET_INSTRUMENT:
output = "GET_INSTRUMENT";
break;
case Operation::GET_INSTRUMENTS:
output = "GET_INSTRUMENTS";
break;
case Operation::CREATE_ORDER:
output = "CREATE_ORDER";
break;
case Operation::CANCEL_ORDER:
output = "CANCEL_ORDER";
break;
case Operation::GET_ORDER:
output = "GET_ORDER";
break;
case Operation::GET_OPEN_ORDERS:
output = "GET_OPEN_ORDERS";
break;
case Operation::CANCEL_OPEN_ORDERS:
output = "CANCEL_OPEN_ORDERS";
break;
case Operation::GET_ACCOUNTS:
output = "GET_ACCOUNTS";
break;
case Operation::GET_ACCOUNT_BALANCES:
output = "GET_ACCOUNT_BALANCES";
break;
case Operation::GET_ACCOUNT_POSITIONS:
output = "GET_ACCOUNT_POSITIONS";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
return output;
}
Request() {}
Request(Operation operation, std::string exchange, std::string instrument = "", std::string correlationId = "",
std::map<std::string, std::string> credential = {})
: operation(operation), exchange(exchange), instrument(instrument), correlationId(correlationId), credential(credential) {
if (operation == Operation::CUSTOM) {
this->serviceName = CCAPI_UNKNOWN;
} else if (operation == Operation::GENERIC_PUBLIC_REQUEST) {
this->serviceName = CCAPI_MARKET_DATA;
} else if (operation == Operation::GENERIC_PRIVATE_REQUEST) {
this->serviceName = CCAPI_EXECUTION_MANAGEMENT;
} else if (operation == Operation::FIX) {
this->serviceName = CCAPI_FIX;
} else {
this->serviceName = static_cast<int>(operation) >= operationTypeExecutionManagement ? CCAPI_EXECUTION_MANAGEMENT : CCAPI_MARKET_DATA;
}
if (this->correlationId.empty()) {
this->correlationId = UtilString::generateRandomString(CCAPI_CORRELATION_ID_GENERATED_LENGTH);
}
}
std::string toString() const {
std::map<std::string, std::string> shortCredential;
for (const auto& x : credential) {
shortCredential.insert(std::make_pair(x.first, UtilString::firstNCharacter(x.second, CCAPI_CREDENTIAL_DISPLAY_LENGTH)));
}
std::string output =
"Request [exchange = " + exchange + ", instrument = " + instrument + ", serviceName = " + serviceName + ", correlationId = " + correlationId +
(this->serviceName == CCAPI_FIX ? ", paramListFix = " + ccapi::toString(paramListFix) : ", paramList = " + ccapi::toString(paramList)) +
", credential = " + ccapi::toString(shortCredential) + ", operation = " + operationToString(operation) +
", timeSent = " + UtilTime::getISOTimestamp(timeSent) + "]";
return output;
}
const std::string& getCorrelationId() const { return correlationId; }
const std::string& getExchange() const { return exchange; }
const std::string& getInstrument() const { return instrument; }
const std::map<std::string, std::string>& getCredential() const { return credential; }
const std::string& getServiceName() const { return serviceName; }
void appendParam(const std::map<std::string, std::string>& param) { this->paramList.push_back(param); }
void appendParamFix(const std::vector<std::pair<int, std::string> >& param) { this->paramListFix.push_back(param); }
void setParamListFix(const std::vector<std::vector<std::pair<int, std::string> > >& paramListFix) { this->paramListFix = paramListFix; }
Operation getOperation() const { return operation; }
const std::vector<std::map<std::string, std::string> >& getParamList() const { return paramList; }
const std::vector<std::vector<std::pair<int, std::string> > >& getParamListFix() const { return paramListFix; }
void setParamList(const std::vector<std::map<std::string, std::string> >& paramList) { this->paramList = paramList; }
std::map<std::string, std::string> getFirstParamWithDefault(const std::map<std::string, std::string> defaultValue = {}) const {
if (this->paramList.empty()) {
return defaultValue;
} else {
return this->paramList.front();
}
}
// 'getTimeSent' only works in C++. For other languages, please use 'getTimeSentISO'.
TimePoint getTimeSent() const { return timeSent; }
std::string getTimeSentISO() const { return UtilTime::getISOTimestamp(timeSent); }
std::pair<long long, long long> getTimeSentPair() const { return UtilTime::divide(timeSent); }
void setTimeSent(TimePoint timeSent) { this->timeSent = timeSent; }
int getIndex() const { return index; }
void setIndex(int index) { this->index = index; }
void setCredential(const std::map<std::string, std::string>& credential) { this->credential = credential; }
void setCorrelationId(const std::string& correlationId) { this->correlationId = correlationId; }
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
std::string exchange;
std::string instrument;
std::string serviceName;
std::string correlationId;
std::vector<std::map<std::string, std::string> > paramList;
std::map<std::string, std::string> credential;
Operation operation;
std::vector<std::vector<std::pair<int, std::string> > > paramListFix;
TimePoint timeSent{std::chrono::seconds{0}};
int index{};
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_REQUEST_H_
+794
View File
@@ -0,0 +1,794 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_SESSION_H_
#define INCLUDE_CCAPI_CPP_CCAPI_SESSION_H_
#include "ccapi_cpp/ccapi_macro.h"
// start: enable exchanges for market data
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_COINBASE
#include "ccapi_cpp/service/ccapi_market_data_service_coinbase.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GEMINI
#include "ccapi_cpp/service/ccapi_market_data_service_gemini.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN
#include "ccapi_cpp/service/ccapi_market_data_service_kraken.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN_FUTURES
#include "ccapi_cpp/service/ccapi_market_data_service_kraken_futures.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BITSTAMP
#include "ccapi_cpp/service/ccapi_market_data_service_bitstamp.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BITFINEX
#include "ccapi_cpp/service/ccapi_market_data_service_bitfinex.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BITMEX
#include "ccapi_cpp/service/ccapi_market_data_service_bitmex.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_US
#include "ccapi_cpp/service/ccapi_market_data_service_binance_us.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE
#include "ccapi_cpp/service/ccapi_market_data_service_binance.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES
#include "ccapi_cpp/service/ccapi_market_data_service_binance_usds_futures.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_COIN_FUTURES
#include "ccapi_cpp/service/ccapi_market_data_service_binance_coin_futures.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI
#include "ccapi_cpp/service/ccapi_market_data_service_huobi.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP
#include "ccapi_cpp/service/ccapi_market_data_service_huobi_usdt_swap.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP
#include "ccapi_cpp/service/ccapi_market_data_service_huobi_coin_swap.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_OKEX
#include "ccapi_cpp/service/ccapi_market_data_service_okex.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_ERISX
#include "ccapi_cpp/service/ccapi_market_data_service_erisx.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN
#include "ccapi_cpp/service/ccapi_market_data_service_kucoin.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN_FUTURES
#include "ccapi_cpp/service/ccapi_market_data_service_kucoin_futures.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_FTX
#include "ccapi_cpp/service/ccapi_market_data_service_ftx.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_FTX_US
#include "ccapi_cpp/service/ccapi_market_data_service_ftx_us.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT
#include "ccapi_cpp/service/ccapi_market_data_service_deribit.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GATEIO
#include "ccapi_cpp/service/ccapi_market_data_service_gateio.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GATEIO_PERPETUAL_FUTURES
#include "ccapi_cpp/service/ccapi_market_data_service_gateio_perpetual_futures.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_CRYPTOCOM
#include "ccapi_cpp/service/ccapi_market_data_service_cryptocom.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
#include "ccapi_cpp/service/ccapi_market_data_service_bybit.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX
#include "ccapi_cpp/service/ccapi_market_data_service_ascendex.h"
#endif
#endif
// end: enable exchanges for market data
// start: enable exchanges for execution management
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_COINBASE
#include "ccapi_cpp/service/ccapi_execution_management_service_coinbase.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GEMINI
#include "ccapi_cpp/service/ccapi_execution_management_service_gemini.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN
#include "ccapi_cpp/service/ccapi_execution_management_service_kraken.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN_FUTURES
#include "ccapi_cpp/service/ccapi_execution_management_service_kraken_futures.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BITSTAMP
#include "ccapi_cpp/service/ccapi_execution_management_service_bitstamp.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BITFINEX
#include "ccapi_cpp/service/ccapi_execution_management_service_bitfinex.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BITMEX
#include "ccapi_cpp/service/ccapi_execution_management_service_bitmex.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_US
#include "ccapi_cpp/service/ccapi_execution_management_service_binance_us.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE
#include "ccapi_cpp/service/ccapi_execution_management_service_binance.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES
#include "ccapi_cpp/service/ccapi_execution_management_service_binance_usds_futures.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_COIN_FUTURES
#include "ccapi_cpp/service/ccapi_execution_management_service_binance_coin_futures.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI
#include "ccapi_cpp/service/ccapi_execution_management_service_huobi.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP
#include "ccapi_cpp/service/ccapi_execution_management_service_huobi_usdt_swap.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP
#include "ccapi_cpp/service/ccapi_execution_management_service_huobi_coin_swap.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_OKEX
#include "ccapi_cpp/service/ccapi_execution_management_service_okex.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_ERISX
#include "ccapi_cpp/service/ccapi_execution_management_service_erisx.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN
#include "ccapi_cpp/service/ccapi_execution_management_service_kucoin.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN_FUTURES
#include "ccapi_cpp/service/ccapi_execution_management_service_kucoin_futures.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_FTX
#include "ccapi_cpp/service/ccapi_execution_management_service_ftx.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_FTX_US
#include "ccapi_cpp/service/ccapi_execution_management_service_ftx_us.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT
#include "ccapi_cpp/service/ccapi_execution_management_service_deribit.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GATEIO
#include "ccapi_cpp/service/ccapi_execution_management_service_gateio.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GATEIO_PERPETUAL_FUTURES
#include "ccapi_cpp/service/ccapi_execution_management_service_gateio_perpetual_futures.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_CRYPTOCOM
#include "ccapi_cpp/service/ccapi_execution_management_service_cryptocom.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
#include "ccapi_cpp/service/ccapi_execution_management_service_bybit.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX
#include "ccapi_cpp/service/ccapi_execution_management_service_ascendex.h"
#endif
#endif
// end: enable exchanges for execution management
// start: enable exchanges for FIX
#ifdef CCAPI_ENABLE_SERVICE_FIX
#ifdef CCAPI_ENABLE_EXCHANGE_COINBASE
#include "ccapi_cpp/service/ccapi_fix_service_coinbase.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GEMINI
#include "ccapi_cpp/service/ccapi_fix_service_gemini.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_FTX
#include "ccapi_cpp/service/ccapi_fix_service_ftx.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_FTX_US
#include "ccapi_cpp/service/ccapi_fix_service_ftx_us.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT
#include "ccapi_cpp/service/ccapi_fix_service_deribit.h"
#endif
#endif
// end: enable exchanges for FIX
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "ccapi_cpp/ccapi_event.h"
#include "ccapi_cpp/ccapi_event_dispatcher.h"
#include "ccapi_cpp/ccapi_event_handler.h"
#include "ccapi_cpp/ccapi_queue.h"
#include "ccapi_cpp/ccapi_session_configs.h"
#include "ccapi_cpp/ccapi_session_options.h"
#include "ccapi_cpp/service/ccapi_service.h"
#include "ccapi_cpp/service/ccapi_service_context.h"
using steady_timer = boost::asio::steady_timer;
namespace ccapi {
class Session {
public:
Session(const Session&) = delete;
Session& operator=(const Session&) = delete;
Session(const SessionOptions& sessionOptions = SessionOptions(), const SessionConfigs& sessionConfigs = SessionConfigs(),
EventHandler* eventHandler = nullptr, EventDispatcher* eventDispatcher = nullptr)
: sessionOptions(sessionOptions),
sessionConfigs(sessionConfigs),
eventHandler(eventHandler),
eventDispatcher(eventDispatcher),
eventQueue(sessionOptions.maxEventQueueSize),
serviceContextPtr(new ServiceContext()) {
CCAPI_LOGGER_FUNCTION_ENTER;
if (this->eventHandler) {
if (!this->eventDispatcher) {
this->eventDispatcher = new EventDispatcher();
this->useInternalEventDispatcher = true;
}
} else {
if (this->eventDispatcher) {
throw std::runtime_error("undefined behavior");
}
}
this->start();
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual ~Session() {
CCAPI_LOGGER_FUNCTION_ENTER;
if (this->useInternalEventDispatcher) {
delete this->eventDispatcher;
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void start() {
CCAPI_LOGGER_FUNCTION_ENTER;
std::thread t([this]() { this->serviceContextPtr->start(); });
this->t = std::move(t);
this->internalEventHandler = std::bind(&Session::onEvent, this, std::placeholders::_1, std::placeholders::_2);
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_COINBASE
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_COINBASE] =
std::make_shared<MarketDataServiceCoinbase>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GEMINI
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_GEMINI] =
std::make_shared<MarketDataServiceGemini>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_KRAKEN] =
std::make_shared<MarketDataServiceKraken>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN_FUTURES
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES] =
std::make_shared<MarketDataServiceKrakenFutures>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BITSTAMP
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BITSTAMP] =
std::make_shared<MarketDataServiceBitstamp>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BITFINEX
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BITFINEX] =
std::make_shared<MarketDataServiceBitfinex>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BITMEX
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BITMEX] =
std::make_shared<MarketDataServiceBitmex>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_US
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BINANCE_US] =
std::make_shared<MarketDataServiceBinanceUs>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BINANCE] =
std::make_shared<MarketDataServiceBinance>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES] =
std::make_shared<MarketDataServiceBinanceUsdsFutures>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_COIN_FUTURES
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES] =
std::make_shared<MarketDataServiceBinanceCoinFutures>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_HUOBI] =
std::make_shared<MarketDataServiceHuobi>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP] =
std::make_shared<MarketDataServiceHuobiUsdtSwap>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP] =
std::make_shared<MarketDataServiceHuobiCoinSwap>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_OKEX
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_OKEX] =
std::make_shared<MarketDataServiceOkex>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_ERISX
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_ERISX] =
std::make_shared<MarketDataServiceErisx>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_KUCOIN] =
std::make_shared<MarketDataServiceKucoin>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN_FUTURES
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES] =
std::make_shared<MarketDataServiceKucoinFutures>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_FTX
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_FTX] =
std::make_shared<MarketDataServiceFtx>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_FTX_US
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_FTX_US] =
std::make_shared<MarketDataServiceFtxUs>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_DERIBIT] =
std::make_shared<MarketDataServiceDeribit>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GATEIO
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_GATEIO] =
std::make_shared<MarketDataServiceGateio>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GATEIO_PERPETUAL_FUTURES
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES] =
std::make_shared<MarketDataServiceGateioPerpetualFutures>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_CRYPTOCOM
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_CRYPTOCOM] =
std::make_shared<MarketDataServiceCryptocom>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BYBIT] =
std::make_shared<MarketDataServiceBybit>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_ASCENDEX] =
std::make_shared<MarketDataServiceAscendex>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#endif
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_COINBASE
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_COINBASE] =
std::make_shared<ExecutionManagementServiceCoinbase>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GEMINI
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_GEMINI] =
std::make_shared<ExecutionManagementServiceGemini>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_KRAKEN] =
std::make_shared<ExecutionManagementServiceKraken>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN_FUTURES
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES] =
std::make_shared<ExecutionManagementServiceKrakenFutures>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BITSTAMP
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITSTAMP] =
std::make_shared<ExecutionManagementServiceBitstamp>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BITFINEX
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITFINEX] =
std::make_shared<ExecutionManagementServiceBitfinex>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BITMEX
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BITMEX] =
std::make_shared<ExecutionManagementServiceBitmex>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_US
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE_US] =
std::make_shared<ExecutionManagementServiceBinanceUs>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE] =
std::make_shared<ExecutionManagementServiceBinance>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES] =
std::make_shared<ExecutionManagementServiceBinanceUsdsFutures>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_COIN_FUTURES
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES] =
std::make_shared<ExecutionManagementServiceBinanceCoinFutures>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_HUOBI] =
std::make_shared<ExecutionManagementServiceHuobi>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP] =
std::make_shared<ExecutionManagementServiceHuobiUsdtSwap>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP] =
std::make_shared<ExecutionManagementServiceHuobiCoinSwap>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_OKEX
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_OKEX] =
std::make_shared<ExecutionManagementServiceOkex>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_ERISX
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_ERISX] =
std::make_shared<ExecutionManagementServiceErisx>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_KUCOIN] =
std::make_shared<ExecutionManagementServiceKucoin>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_KUCOIN_FUTURES
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES] =
std::make_shared<ExecutionManagementServiceKucoinFutures>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_FTX
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_FTX] =
std::make_shared<ExecutionManagementServiceFtx>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_FTX_US
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_FTX_US] =
std::make_shared<ExecutionManagementServiceFtxUs>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_DERIBIT] =
std::make_shared<ExecutionManagementServiceDeribit>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GATEIO
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_GATEIO] =
std::make_shared<ExecutionManagementServiceGateio>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GATEIO_PERPETUAL_FUTURES
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES] =
std::make_shared<ExecutionManagementServiceGateioPerpetualFutures>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_CRYPTOCOM
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_CRYPTOCOM] =
std::make_shared<ExecutionManagementServiceCryptocom>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_CRYPTOCOM] =
std::make_shared<ExecutionManagementServiceBybit>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_ASCENDEX] =
std::make_shared<ExecutionManagementServiceAscendex>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#endif
#ifdef CCAPI_ENABLE_SERVICE_FIX
#ifdef CCAPI_ENABLE_EXCHANGE_COINBASE
this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_COINBASE] =
std::make_shared<FixServiceCoinbase>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_GEMINI
this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_GEMINI] =
std::make_shared<FixServiceGemini>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_FTX
this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_FTX] =
std::make_shared<FixServiceFtx>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_FTX_US
this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_FTX_US] =
std::make_shared<FixServiceFtxUs>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT
this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_DERIBIT] =
std::make_shared<FixServiceDeribit>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#endif
for (const auto& x : this->serviceByServiceNameExchangeMap) {
auto serviceName = x.first;
for (const auto& y : x.second) {
auto exchange = y.first;
CCAPI_LOGGER_INFO("enabled service: " + serviceName + ", exchange: " + exchange);
}
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void stop() {
if (this->useInternalEventDispatcher) {
this->eventDispatcher->stop();
}
for (const auto& x : this->serviceByServiceNameExchangeMap) {
for (const auto& y : x.second) {
y.second->stop();
}
}
this->serviceContextPtr->stop();
this->t.join();
}
virtual void subscribe(Subscription& subscription) {
std::vector<Subscription> subscriptionList;
subscriptionList.push_back(subscription);
this->subscribe(subscriptionList);
}
virtual void subscribe(std::vector<Subscription>& subscriptionList) {
CCAPI_LOGGER_FUNCTION_ENTER;
std::map<std::string, std::vector<Subscription> > subscriptionListByServiceNameMap;
for (const auto& subscription : subscriptionList) {
auto serviceName = subscription.getServiceName();
subscriptionListByServiceNameMap[serviceName].push_back(subscription);
}
for (const auto& x : subscriptionListByServiceNameMap) {
auto serviceName = x.first;
auto subscriptionList = x.second;
if (this->serviceByServiceNameExchangeMap.find(serviceName) == this->serviceByServiceNameExchangeMap.end()) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE,
"please enable service: " + serviceName + ", and the exchanges that you want");
return;
}
if (serviceName == CCAPI_MARKET_DATA) {
std::set<std::string> correlationIdSet;
std::set<std::string> duplicateCorrelationIdSet;
std::unordered_set<std::string> unsupportedExchangeFieldSet;
std::map<std::string, std::vector<Subscription> > subscriptionListByExchangeMap;
auto exchangeFieldMap = this->sessionConfigs.getExchangeFieldMap();
CCAPI_LOGGER_DEBUG("exchangeFieldMap = " + toString(exchangeFieldMap));
for (const auto& subscription : subscriptionList) {
auto correlationId = subscription.getCorrelationId();
if (correlationIdSet.find(correlationId) != correlationIdSet.end()) {
duplicateCorrelationIdSet.insert(correlationId);
} else {
correlationIdSet.insert(correlationId);
}
auto exchange = subscription.getExchange();
CCAPI_LOGGER_DEBUG("exchange = " + exchange);
auto field = subscription.getField();
auto optionMap = subscription.getOptionMap();
CCAPI_LOGGER_DEBUG("field = " + field);
if (exchangeFieldMap.find(exchange) == exchangeFieldMap.end() ||
std::find(exchangeFieldMap.find(exchange)->second.begin(), exchangeFieldMap.find(exchange)->second.end(), field) ==
exchangeFieldMap.find(exchange)->second.end()) {
CCAPI_LOGGER_DEBUG("unsupported exchange " + exchange + ", field = " + field);
unsupportedExchangeFieldSet.insert(exchange + "|" + field);
}
subscriptionListByExchangeMap[exchange].push_back(subscription);
}
if (!duplicateCorrelationIdSet.empty()) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE,
"duplicated correlation ids: " + toString(duplicateCorrelationIdSet));
return;
}
if (!unsupportedExchangeFieldSet.empty()) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE,
"unsupported exchange fields: " + toString(unsupportedExchangeFieldSet));
return;
}
CCAPI_LOGGER_TRACE("subscriptionListByExchangeMap = " + toString(subscriptionListByExchangeMap));
for (auto& subscriptionListByExchange : subscriptionListByExchangeMap) {
auto exchange = subscriptionListByExchange.first;
auto subscriptionList = subscriptionListByExchange.second;
std::map<std::string, wspp::lib::shared_ptr<Service> >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName);
if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, "please enable exchange: " + exchange);
return;
}
serviceByExchangeMap.at(exchange)->subscribe(subscriptionList);
}
} else if (serviceName == CCAPI_EXECUTION_MANAGEMENT) {
std::map<std::string, std::vector<Subscription> > subscriptionListByExchangeMap;
for (const auto& subscription : subscriptionList) {
auto exchange = subscription.getExchange();
subscriptionListByExchangeMap[exchange].push_back(subscription);
}
CCAPI_LOGGER_TRACE("subscriptionListByExchangeMap = " + toString(subscriptionListByExchangeMap));
for (auto& subscriptionListByExchange : subscriptionListByExchangeMap) {
auto exchange = subscriptionListByExchange.first;
auto subscriptionList = subscriptionListByExchange.second;
std::map<std::string, wspp::lib::shared_ptr<Service> >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName);
if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, "please enable exchange: " + exchange);
return;
}
serviceByExchangeMap.at(exchange)->subscribe(subscriptionList);
}
}
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void subscribeByFix(Subscription& subscription) {
auto serviceName = subscription.getServiceName();
CCAPI_LOGGER_DEBUG("serviceName = " + serviceName);
if (this->serviceByServiceNameExchangeMap.find(serviceName) == this->serviceByServiceNameExchangeMap.end()) {
this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, "please enable service: " + serviceName + ", and the exchanges that you want");
return;
}
auto exchange = subscription.getExchange();
std::map<std::string, wspp::lib::shared_ptr<Service> >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName);
if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) {
this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, "please enable exchange: " + exchange);
return;
}
serviceByExchangeMap.at(exchange)->subscribeByFix(subscription);
}
virtual void subscribeByFix(std::vector<Subscription>& subscriptionList) {
for (auto& x : subscriptionList) {
this->subscribeByFix(x);
}
}
virtual void onEvent(Event& event, Queue<Event>* eventQueue) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_TRACE("event = " + toString(event));
if (eventQueue) {
eventQueue->pushBack(std::move(event));
} else {
if (this->eventHandler) {
CCAPI_LOGGER_TRACE("handle event in immediate mode");
this->eventDispatcher->dispatch([that = this, event = std::move(event)] {
bool shouldContinue = true;
try {
shouldContinue = that->eventHandler->processEvent(event, that);
} catch (const std::runtime_error& e) {
CCAPI_LOGGER_ERROR(e.what());
}
if (!shouldContinue) {
CCAPI_LOGGER_DEBUG("about to pause the event dispatcher");
that->eventDispatcher->pause();
}
});
} else {
CCAPI_LOGGER_TRACE("handle event in batching mode");
this->eventQueue.pushBack(std::move(event));
}
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void sendRequestByFix(Request& request) {
CCAPI_LOGGER_FUNCTION_ENTER;
auto serviceName = request.getServiceName();
CCAPI_LOGGER_DEBUG("serviceName = " + serviceName);
if (this->serviceByServiceNameExchangeMap.find(serviceName) == this->serviceByServiceNameExchangeMap.end()) {
this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, "please enable service: " + serviceName + ", and the exchanges that you want");
return;
}
std::map<std::string, wspp::lib::shared_ptr<Service> >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName);
auto exchange = request.getExchange();
if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) {
this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, "please enable exchange: " + exchange);
return;
}
std::shared_ptr<Service>& servicePtr = serviceByExchangeMap.at(exchange);
auto now = UtilTime::now();
servicePtr->sendRequestByFix(request, now);
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void sendRequestByFix(std::vector<Request>& requestList) {
for (auto& x : requestList) {
this->sendRequestByFix(x);
}
}
virtual void sendRequestByWebsocket(Request& request) {
CCAPI_LOGGER_FUNCTION_ENTER;
auto serviceName = request.getServiceName();
CCAPI_LOGGER_DEBUG("serviceName = " + serviceName);
if (this->serviceByServiceNameExchangeMap.find(serviceName) == this->serviceByServiceNameExchangeMap.end()) {
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "please enable service: " + serviceName + ", and the exchanges that you want");
return;
}
std::map<std::string, wspp::lib::shared_ptr<Service> >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName);
auto exchange = request.getExchange();
if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) {
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "please enable exchange: " + exchange);
return;
}
std::shared_ptr<Service>& servicePtr = serviceByExchangeMap.at(exchange);
auto now = UtilTime::now();
servicePtr->sendRequestByWebsocket(request, now);
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void sendRequestByWebsocket(std::vector<Request>& requestList) {
for (auto& x : requestList) {
this->sendRequestByWebsocket(x);
}
}
virtual void sendRequest(Request& request, Queue<Event>* eventQueuePtr = nullptr, long delayMilliSeconds = 0) {
CCAPI_LOGGER_FUNCTION_ENTER;
std::vector<Request> requestList({request});
this->sendRequest(requestList, eventQueuePtr, delayMilliSeconds);
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void sendRequest(std::vector<Request>& requestList, Queue<Event>* eventQueuePtr = nullptr, long delayMilliSeconds = 0) {
CCAPI_LOGGER_FUNCTION_ENTER;
std::vector<std::shared_ptr<std::future<void> > > futurePtrList;
// std::set<std::string> serviceNameExchangeSet;
int i = 0;
for (auto& request : requestList) {
request.setIndex(i);
auto serviceName = request.getServiceName();
CCAPI_LOGGER_DEBUG("serviceName = " + serviceName);
if (this->serviceByServiceNameExchangeMap.find(serviceName) == this->serviceByServiceNameExchangeMap.end()) {
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE,
"please enable service: " + serviceName + ", and the exchanges that you want", eventQueuePtr);
return;
}
std::map<std::string, wspp::lib::shared_ptr<Service> >& serviceByExchangeMap = this->serviceByServiceNameExchangeMap.at(serviceName);
auto exchange = request.getExchange();
if (serviceByExchangeMap.find(exchange) == serviceByExchangeMap.end()) {
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "please enable exchange: " + exchange, eventQueuePtr);
return;
}
std::shared_ptr<Service>& servicePtr = serviceByExchangeMap.at(exchange);
std::string key = serviceName + exchange;
// if (eventQueuePtr && serviceNameExchangeSet.find(key) == serviceNameExchangeSet.end()) {
// // servicePtr->setEventHandler(std::bind(&Session::onEvent, this, std::placeholders::_1, eventQueuePtr));
// serviceNameExchangeSet.insert(key);
// }
auto now = UtilTime::now();
auto futurePtr = servicePtr->sendRequest(request, !!eventQueuePtr, now, delayMilliSeconds, eventQueuePtr);
if (eventQueuePtr) {
futurePtrList.push_back(futurePtr);
}
++i;
}
if (eventQueuePtr) {
for (auto& futurePtr : futurePtrList) {
CCAPI_LOGGER_TRACE("before future wait");
futurePtr->wait();
CCAPI_LOGGER_TRACE("after future wait");
}
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual Queue<Event>& getEventQueue() { return eventQueue; }
virtual void onError(const Event::Type eventType, const Message::Type messageType, const std::string& errorMessage, Queue<Event>* eventQueuePtr = nullptr) {
CCAPI_LOGGER_ERROR("errorMessage = " + errorMessage);
Event event;
event.setType(eventType);
Message message;
auto now = UtilTime::now();
message.setTimeReceived(now);
message.setTime(now);
message.setType(messageType);
Element element;
element.insert(CCAPI_ERROR_MESSAGE, errorMessage);
message.setElementList({element});
event.setMessageList({message});
this->onEvent(event, eventQueuePtr);
}
#ifndef SWIG
virtual void setTimer(const std::string& id, long delayMilliSeconds, std::function<void(const boost::system::error_code&)> errorHandler,
std::function<void()> successHandler) {
wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), [this, id, delayMilliSeconds, errorHandler, successHandler]() {
std::shared_ptr<steady_timer> timerPtr(new steady_timer(*this->serviceContextPtr->ioContextPtr, boost::asio::chrono::milliseconds(delayMilliSeconds)));
timerPtr->async_wait([this, id, errorHandler, successHandler](const boost::system::error_code& ec) {
if (this->eventHandler) {
this->eventDispatcher->dispatch([ec, errorHandler, successHandler] {
if (ec) {
errorHandler(ec);
} else {
successHandler();
}
});
}
this->delayTimerByIdMap.erase(id);
});
this->delayTimerByIdMap[id] = timerPtr;
});
}
virtual void cancelTimer(const std::string& id) {
wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), [this, id]() {
if (this->delayTimerByIdMap.find(id) != this->delayTimerByIdMap.end()) {
this->delayTimerByIdMap[id]->cancel();
this->delayTimerByIdMap.erase(id);
}
});
}
#endif
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
SessionOptions sessionOptions;
SessionConfigs sessionConfigs;
EventHandler* eventHandler;
EventDispatcher* eventDispatcher;
bool useInternalEventDispatcher{};
wspp::lib::shared_ptr<ServiceContext> serviceContextPtr;
std::map<std::string, std::map<std::string, wspp::lib::shared_ptr<Service> > > serviceByServiceNameExchangeMap;
std::thread t;
Queue<Event> eventQueue;
std::function<void(Event& event, Queue<Event>* eventQueue)> internalEventHandler;
std::map<std::string, std::shared_ptr<steady_timer> > delayTimerByIdMap;
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_SESSION_H_
@@ -0,0 +1,329 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_SESSION_CONFIGS_H_
#define INCLUDE_CCAPI_CPP_CCAPI_SESSION_CONFIGS_H_
#include <map>
#include <set>
#include <string>
#include <vector>
#include "ccapi_cpp/ccapi_logger.h"
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_util_private.h"
namespace ccapi {
class SessionConfigs CCAPI_FINAL {
public:
explicit SessionConfigs(std::map<std::string, std::string> credential = {}) : credential(credential) {
this->updateExchange();
this->updateExchangeRest();
this->initializUrlFixBase();
}
const std::map<std::string, std::vector<std::string> >& getExchangeFieldMap() const { return exchangeFieldMap; }
const std::map<std::string, std::map<std::string, std::string> >& getExchangeFieldWebsocketChannelMap() const { return exchangeFieldWebsocketChannelMap; }
const std::map<std::string, std::string>& getUrlWebsocketBase() const { return urlWebsocketBase; }
const std::map<std::string, std::string>& getUrlRestBase() const { return urlRestBase; }
const std::map<std::string, std::string>& getUrlFixBase() const { return urlFixBase; }
const std::map<std::string, int>& getInitialSequenceByExchangeMap() const { return initialSequenceByExchangeMap; }
const std::map<std::string, std::string>& getCredential() const { return credential; }
void setCredential(const std::map<std::string, std::string>& credential) { this->credential = credential; }
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
void updateExchange() {
std::map<std::string, std::string> fieldWebsocketChannelMapCoinbase = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_COINBASE_CHANNEL_MATCH},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_COINBASE_CHANNEL_LEVEL2},
};
std::map<std::string, std::string> fieldWebsocketChannelMapGemini = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_GEMINI_PARAMETER_TRADES},
{CCAPI_MARKET_DEPTH, std::string(CCAPI_WEBSOCKET_GEMINI_PARAMETER_BIDS) + "," + CCAPI_WEBSOCKET_GEMINI_PARAMETER_OFFERS},
};
std::map<std::string, std::string> fieldWebsocketChannelMapKraken = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_KRAKEN_CHANNEL_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_KRAKEN_CHANNEL_BOOK},
};
std::map<std::string, std::string> fieldWebsocketChannelMapKrakenFutures = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_KRAKEN_FUTURES_CHANNEL_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_KRAKEN_FUTURES_CHANNEL_BOOK},
};
std::map<std::string, std::string> fieldWebsocketChannelMapBitstamp = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_BITSTAMP_CHANNEL_LIVE_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BITSTAMP_CHANNEL_ORDER_BOOK},
};
std::map<std::string, std::string> fieldWebsocketChannelMapBitfinex = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK},
};
std::map<std::string, std::string> fieldWebsocketChannelMapBitmex = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_BITMEX_CHANNEL_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_L2},
};
std::map<std::string, std::string> fieldWebsocketChannelMapBinanceUs = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_TRADE},
{CCAPI_AGG_TRADE, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_AGG_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_PARTIAL_BOOK_DEPTH},
};
std::map<std::string, std::string> fieldWebsocketChannelMapBinance = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_TRADE},
{CCAPI_AGG_TRADE, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_AGG_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_PARTIAL_BOOK_DEPTH},
};
std::map<std::string, std::string> fieldWebsocketChannelMapBinanceUsdsFutures = {
{CCAPI_AGG_TRADE, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_AGG_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_PARTIAL_BOOK_DEPTH},
};
std::map<std::string, std::string> fieldWebsocketChannelMapBinanceCoinFutures = {
{CCAPI_AGG_TRADE, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_AGG_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_PARTIAL_BOOK_DEPTH},
};
std::map<std::string, std::string> fieldWebsocketChannelMapHuobi = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH},
};
std::map<std::string, std::string> fieldWebsocketChannelMapHuobiUsdtSwap = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH},
};
std::map<std::string, std::string> fieldWebsocketChannelMapHuobiCoinSwap = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH},
};
std::map<std::string, std::string> fieldWebsocketChannelMapOkex = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_OKEX_CHANNEL_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400},
};
std::map<std::string, std::string> fieldWebsocketChannelMapErisx = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_ERISX_CHANNEL_MARKET_DATA_SUBSCRIBE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_ERISX_CHANNEL_MARKET_DATA_SUBSCRIBE},
};
std::map<std::string, std::string> fieldWebsocketChannelMapKucoin = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_MATCH},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2},
};
std::map<std::string, std::string> fieldWebsocketChannelMapKucoinFutures = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_KUCOIN_FUTURES_CHANNEL_MARKET_MATCH},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_KUCOIN_FUTURES_CHANNEL_MARKET_LEVEL2},
};
std::map<std::string, std::string> fieldWebsocketChannelMapFtx = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_FTX_BASE_CHANNEL_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_FTX_BASE_CHANNEL_ORDERBOOKS},
};
std::map<std::string, std::string> fieldWebsocketChannelMapFtxUs = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_FTX_BASE_CHANNEL_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_FTX_BASE_CHANNEL_ORDERBOOKS},
};
std::map<std::string, std::string> fieldWebsocketChannelMapDeribit = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_DERIBIT_CHANNEL_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK_TBT},
};
std::map<std::string, std::string> fieldWebsocketChannelMapGateio = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_GATEIO_CHANNEL_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_GATEIO_CHANNEL_ORDER_BOOK},
};
std::map<std::string, std::string> fieldWebsocketChannelMapGateioPerpetualFutures = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_ORDER_BOOK},
};
std::map<std::string, std::string> fieldWebsocketChannelMapCryptocom = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_BOOK},
};
std::map<std::string, std::string> fieldWebsocketChannelMapBybit = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_BYBIT_CHANNEL_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH},
};
std::map<std::string, std::string> fieldWebsocketChannelMapAscendex = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_DEPTH},
};
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapCoinbase) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_COINBASE].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketParameter : fieldWebsocketChannelMapGemini) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_GEMINI].push_back(fieldWebsocketParameter.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapKraken) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_KRAKEN].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapKrakenFutures) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBitstamp) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BITSTAMP].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBitfinex) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BITFINEX].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBitmex) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BITMEX].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBinanceUs) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BINANCE_US].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBinance) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BINANCE].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBinanceUsdsFutures) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBinanceCoinFutures) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapHuobi) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_HUOBI].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapHuobiUsdtSwap) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapHuobiCoinSwap) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapOkex) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_OKEX].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapErisx) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_ERISX].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapKucoin) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_KUCOIN].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapKucoinFutures) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapFtx) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_FTX].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapFtxUs) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_FTX_US].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapDeribit) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_DERIBIT].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapGateio) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_GATEIO].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapGateioPerpetualFutures) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapCryptocom) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_CRYPTOCOM].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBybit) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BYBIT].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapAscendex) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_ASCENDEX].push_back(fieldWebsocketChannel.first);
}
for (auto& x : this->exchangeFieldMap) {
x.second.push_back(CCAPI_GENERIC_PUBLIC_SUBSCRIPTION);
}
CCAPI_LOGGER_TRACE("this->exchangeFieldMap = " + toString(this->exchangeFieldMap));
this->exchangeFieldWebsocketChannelMap = {
{CCAPI_EXCHANGE_NAME_COINBASE, fieldWebsocketChannelMapCoinbase},
{CCAPI_EXCHANGE_NAME_GEMINI, fieldWebsocketChannelMapGemini},
{CCAPI_EXCHANGE_NAME_KRAKEN, fieldWebsocketChannelMapKraken},
{CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES, fieldWebsocketChannelMapKrakenFutures},
{CCAPI_EXCHANGE_NAME_BITSTAMP, fieldWebsocketChannelMapBitstamp},
{CCAPI_EXCHANGE_NAME_BITFINEX, fieldWebsocketChannelMapBitfinex},
{CCAPI_EXCHANGE_NAME_BITMEX, fieldWebsocketChannelMapBitmex},
{CCAPI_EXCHANGE_NAME_BINANCE_US, fieldWebsocketChannelMapBinanceUs},
{CCAPI_EXCHANGE_NAME_BINANCE, fieldWebsocketChannelMapBinance},
{CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES, fieldWebsocketChannelMapBinanceUsdsFutures},
{CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES, fieldWebsocketChannelMapBinanceCoinFutures},
{CCAPI_EXCHANGE_NAME_HUOBI, fieldWebsocketChannelMapHuobi},
{CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP, fieldWebsocketChannelMapHuobiUsdtSwap},
{CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP, fieldWebsocketChannelMapHuobiCoinSwap},
{CCAPI_EXCHANGE_NAME_OKEX, fieldWebsocketChannelMapOkex},
{CCAPI_EXCHANGE_NAME_ERISX, fieldWebsocketChannelMapErisx},
{CCAPI_EXCHANGE_NAME_KUCOIN, fieldWebsocketChannelMapKucoin},
{CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES, fieldWebsocketChannelMapKucoinFutures},
{CCAPI_EXCHANGE_NAME_FTX, fieldWebsocketChannelMapFtx},
{CCAPI_EXCHANGE_NAME_FTX_US, fieldWebsocketChannelMapFtxUs},
{CCAPI_EXCHANGE_NAME_DERIBIT, fieldWebsocketChannelMapDeribit},
{CCAPI_EXCHANGE_NAME_GATEIO, fieldWebsocketChannelMapGateio},
{CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES, fieldWebsocketChannelMapGateioPerpetualFutures},
{CCAPI_EXCHANGE_NAME_CRYPTOCOM, fieldWebsocketChannelMapCryptocom},
{CCAPI_EXCHANGE_NAME_BYBIT, fieldWebsocketChannelMapBybit},
{CCAPI_EXCHANGE_NAME_ASCENDEX, fieldWebsocketChannelMapAscendex},
};
this->urlWebsocketBase = {
{CCAPI_EXCHANGE_NAME_COINBASE, CCAPI_COINBASE_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_GEMINI, CCAPI_GEMINI_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_KRAKEN, CCAPI_KRAKEN_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES, CCAPI_KRAKEN_FUTURES_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BITSTAMP, CCAPI_BITSTAMP_URL_WS_BASE},
// Bitfinex has different urls for public and private APIs. Here it is only a placeholder for subscription grouping purposes.
{CCAPI_EXCHANGE_NAME_BITFINEX, ""},
{CCAPI_EXCHANGE_NAME_BITMEX, CCAPI_BITMEX_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE_US, CCAPI_BINANCE_US_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE, CCAPI_BINANCE_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES, CCAPI_BINANCE_USDS_FUTURES_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES, CCAPI_BINANCE_COIN_FUTURES_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_HUOBI, CCAPI_HUOBI_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP, CCAPI_HUOBI_USDT_SWAP_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP, CCAPI_HUOBI_COIN_SWAP_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_OKEX, CCAPI_OKEX_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_ERISX, CCAPI_ERISX_URL_WS_BASE},
// Kucoin has dynamic websocket url. Here it is only a placeholder for subscription grouping purposes.
{CCAPI_EXCHANGE_NAME_KUCOIN, "CCAPI_EXCHANGE_NAME_KUCOIN_URL_WEBSOCKET_BASE"},
// Kucoin Futures has dynamic websocket url. Here it is only a placeholder for subscription grouping purposes.
{CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES, "CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES_URL_WEBSOCKET_BASE"},
{CCAPI_EXCHANGE_NAME_FTX, CCAPI_FTX_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_FTX_US, CCAPI_FTX_US_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_DERIBIT, CCAPI_DERIBIT_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_GATEIO, CCAPI_GATEIO_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES, CCAPI_GATEIO_PERPETUAL_FUTURES_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_CRYPTOCOM, CCAPI_CRYPTOCOM_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BYBIT, CCAPI_BYBIT_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_ASCENDEX, CCAPI_ASCENDEX_URL_WS_BASE},
};
this->initialSequenceByExchangeMap = {{CCAPI_EXCHANGE_NAME_GEMINI, 0}, {CCAPI_EXCHANGE_NAME_BITFINEX, 1}};
}
void updateExchangeRest() {
this->urlRestBase = {
{CCAPI_EXCHANGE_NAME_COINBASE, CCAPI_COINBASE_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_GEMINI, CCAPI_GEMINI_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_KRAKEN, CCAPI_KRAKEN_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES, CCAPI_KRAKEN_FUTURES_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BITSTAMP, CCAPI_BITSTAMP_URL_REST_BASE},
// Bitfinex has different urls for public and private APIs
{CCAPI_EXCHANGE_NAME_BITFINEX, ""},
{CCAPI_EXCHANGE_NAME_BITMEX, CCAPI_BITMEX_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE_US, CCAPI_BINANCE_US_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE, CCAPI_BINANCE_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES, CCAPI_BINANCE_USDS_FUTURES_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES, CCAPI_BINANCE_COIN_FUTURES_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_HUOBI, CCAPI_HUOBI_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP, CCAPI_HUOBI_USDT_SWAP_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP, CCAPI_HUOBI_COIN_SWAP_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_OKEX, CCAPI_OKEX_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_ERISX, CCAPI_ERISX_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_KUCOIN, CCAPI_KUCOIN_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES, CCAPI_KUCOIN_FUTURES_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_FTX, CCAPI_FTX_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_FTX_US, CCAPI_FTX_US_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_DERIBIT, CCAPI_DERIBIT_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_GATEIO, CCAPI_GATEIO_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES, CCAPI_GATEIO_PERPETUAL_FUTURES_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_CRYPTOCOM, CCAPI_CRYPTOCOM_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BYBIT, CCAPI_BYBIT_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_ASCENDEX, CCAPI_ASCENDEX_URL_REST_BASE},
};
}
void initializUrlFixBase() {
this->urlFixBase = {
{CCAPI_EXCHANGE_NAME_COINBASE, CCAPI_COINBASE_URL_FIX_BASE},
{CCAPI_EXCHANGE_NAME_FTX, CCAPI_FTX_URL_FIX_BASE},
{CCAPI_EXCHANGE_NAME_FTX_US, CCAPI_FTX_US_URL_FIX_BASE},
{CCAPI_EXCHANGE_NAME_DERIBIT, CCAPI_DERIBIT_URL_FIX_BASE},
};
}
std::map<std::string, std::vector<std::string> > exchangeFieldMap;
std::map<std::string, std::map<std::string, std::string> > exchangeFieldWebsocketChannelMap;
std::map<std::string, std::string> urlWebsocketBase;
std::map<std::string, std::string> urlRestBase;
std::map<std::string, std::string> urlFixBase;
std::map<std::string, int> initialSequenceByExchangeMap;
std::map<std::string, std::string> credential;
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_SESSION_CONFIGS_H_
@@ -0,0 +1,55 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_SESSION_OPTIONS_H_
#define INCLUDE_CCAPI_CPP_CCAPI_SESSION_OPTIONS_H_
#include <string>
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_util_private.h"
namespace ccapi {
class SessionOptions CCAPI_FINAL {
public:
std::string toString() const {
std::string output = "SessionOptions [warnLateEventMaxMilliSeconds = " + ccapi::toString(warnLateEventMaxMilliSeconds) +
", enableCheckSequence = " + ccapi::toString(enableCheckSequence) +
", enableCheckOrderBookChecksum = " + ccapi::toString(enableCheckOrderBookChecksum) +
", enableCheckOrderBookCrossed = " + ccapi::toString(enableCheckOrderBookCrossed) +
", enableCheckPingPongWebsocketProtocolLevel = " + ccapi::toString(enableCheckPingPongWebsocketProtocolLevel) +
", enableCheckPingPongWebsocketApplicationLevel = " + ccapi::toString(enableCheckPingPongWebsocketApplicationLevel) +
", enableCheckHeartbeatFix = " + ccapi::toString(enableCheckHeartbeatFix) +
", pingWebsocketProtocolLevelIntervalMilliSeconds = " + ccapi::toString(pingWebsocketProtocolLevelIntervalMilliSeconds) +
", pongWebsocketProtocolLevelTimeoutMilliSeconds = " + ccapi::toString(pongWebsocketProtocolLevelTimeoutMilliSeconds) +
", pingWebsocketApplicationLevelIntervalMilliSeconds = " + ccapi::toString(pingWebsocketApplicationLevelIntervalMilliSeconds) +
", pongWebsocketApplicationLevelTimeoutMilliSeconds = " + ccapi::toString(pongWebsocketApplicationLevelTimeoutMilliSeconds) +
", heartbeatFixIntervalMilliSeconds = " + ccapi::toString(heartbeatFixIntervalMilliSeconds) +
", heartbeatFixTimeoutMilliSeconds = " + ccapi::toString(heartbeatFixTimeoutMilliSeconds) +
", maxEventQueueSize = " + ccapi::toString(maxEventQueueSize) + ", httpMaxNumRetry = " + ccapi::toString(httpMaxNumRetry) +
", httpMaxNumRedirect = " + ccapi::toString(httpMaxNumRedirect) +
", httpRequestTimeoutMilliSeconds = " + ccapi::toString(httpRequestTimeoutMilliSeconds) +
", httpConnectionPoolMaxSize = " + ccapi::toString(httpConnectionPoolMaxSize) +
", httpConnectionPoolIdleTimeoutMilliSeconds = " + ccapi::toString(httpConnectionPoolIdleTimeoutMilliSeconds) +
", enableOneHttpConnectionPerRequest = " + ccapi::toString(enableOneHttpConnectionPerRequest) + "]";
return output;
}
long warnLateEventMaxMilliSeconds{}; // used to print a warning log message if en event arrives late
bool enableCheckSequence{}; // used to check sequence number discontinuity
bool enableCheckOrderBookChecksum{}; // used to check order book checksum
bool enableCheckOrderBookCrossed{true}; // used to check order book cross, usually this should be set to true
bool enableCheckPingPongWebsocketProtocolLevel{true}; // used to check ping-pong health for exchange connections on websocket protocol level
bool enableCheckPingPongWebsocketApplicationLevel{true}; // used to check ping-pong health for exchange connections on websocket application level
bool enableCheckHeartbeatFix{true}; // used to check heartbeat health for exchange connections on FIX
long pingWebsocketProtocolLevelIntervalMilliSeconds{60000};
long pongWebsocketProtocolLevelTimeoutMilliSeconds{30000}; // should be less than pingWebsocketProtocolLevelIntervalMilliSeconds
long pingWebsocketApplicationLevelIntervalMilliSeconds{60000};
long pongWebsocketApplicationLevelTimeoutMilliSeconds{30000}; // should be less than pingWebsocketApplicationLevelIntervalMilliSeconds
long heartbeatFixIntervalMilliSeconds{60000};
long heartbeatFixTimeoutMilliSeconds{30000}; // should be less than heartbeatFixIntervalMilliSeconds
int maxEventQueueSize{0}; // if set to a positive integer, the event queue will throw an exception when overflown
int httpMaxNumRetry{1};
int httpMaxNumRedirect{1};
long httpRequestTimeoutMilliSeconds{10000};
int httpConnectionPoolMaxSize{1}; // used to set the maximal number of http connections to be kept in the pool (connections in the pool are idle)
long httpConnectionPoolIdleTimeoutMilliSeconds{0}; // used to purge the http connection pool if all connections in the
// pool have stayed idle for at least this amount of time
bool enableOneHttpConnectionPerRequest{}; // create a new http connection for each request
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_SESSION_OPTIONS_H_
@@ -0,0 +1,144 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_SUBSCRIPTION_H_
#define INCLUDE_CCAPI_CPP_CCAPI_SUBSCRIPTION_H_
#include <set>
#include <string>
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_util_private.h"
namespace ccapi {
class Subscription CCAPI_FINAL {
public:
Subscription() {}
Subscription(std::string exchange, std::string instrument, std::string field, std::string options = "", std::string correlationId = "",
std::map<std::string, std::string> credential = {})
: exchange(exchange), instrument(instrument), field(field), correlationId(correlationId), credential(credential) {
auto originalInstrumentSet = UtilString::splitToSet(instrument, ",");
std::copy_if(originalInstrumentSet.begin(), originalInstrumentSet.end(), std::inserter(this->instrumentSet, this->instrumentSet.end()),
[](const std::string& value) { return !value.empty(); });
auto originalFieldSet = UtilString::splitToSet(field, ",");
std::copy_if(originalFieldSet.begin(), originalFieldSet.end(), std::inserter(this->fieldSet, this->fieldSet.end()),
[](const std::string& value) { return !value.empty(); });
if (field == CCAPI_GENERIC_PUBLIC_SUBSCRIPTION) {
this->rawOptions = options;
} else {
std::vector<std::string> optionList;
if (!options.empty()) {
optionList = UtilString::split(options, "&");
}
this->optionMap[CCAPI_MARKET_DEPTH_MAX] = CCAPI_MARKET_DEPTH_MAX_DEFAULT;
this->optionMap[CCAPI_CONFLATE_INTERVAL_MILLISECONDS] = CCAPI_CONFLATE_INTERVAL_MILLISECONDS_DEFAULT;
this->optionMap[CCAPI_CONFLATE_GRACE_PERIOD_MILLISECONDS] = CCAPI_CONFLATE_GRACE_PERIOD_MILLISECONDS_DEFAULT;
this->optionMap[CCAPI_MARKET_DEPTH_RETURN_UPDATE] = CCAPI_MARKET_DEPTH_RETURN_UPDATE_DEFAULT;
for (const auto& option : optionList) {
auto optionKeyValue = UtilString::split(option, "=");
this->optionMap[optionKeyValue.at(0)] = optionKeyValue.at(1);
}
}
std::set<std::string> executionManagementSubscriptionFieldSet = {std::string(CCAPI_EM_ORDER_UPDATE), std::string(CCAPI_EM_PRIVATE_TRADE)};
if (field == CCAPI_GENERIC_PUBLIC_SUBSCRIPTION) {
this->serviceName = CCAPI_MARKET_DATA;
} else if (field == CCAPI_FIX || field == CCAPI_FIX_MARKET_DATA || field == CCAPI_FIX_EXECUTION_MANAGEMENT) {
this->serviceName = CCAPI_FIX;
} else if (std::includes(executionManagementSubscriptionFieldSet.begin(), executionManagementSubscriptionFieldSet.end(), this->fieldSet.begin(),
this->fieldSet.end())) {
this->serviceName = CCAPI_EXECUTION_MANAGEMENT;
} else if (field == CCAPI_MARKET_DEPTH || field == CCAPI_TRADE || field == CCAPI_AGG_TRADE) {
this->serviceName = CCAPI_MARKET_DATA;
}
CCAPI_LOGGER_TRACE("this->serviceName = " + this->serviceName);
if (this->correlationId.empty()) {
this->correlationId = UtilString::generateRandomString(CCAPI_CORRELATION_ID_GENERATED_LENGTH);
}
}
std::string toString() const {
std::map<std::string, std::string> shortCredential;
for (const auto& x : credential) {
shortCredential.insert(std::make_pair(x.first, UtilString::firstNCharacter(x.second, CCAPI_CREDENTIAL_DISPLAY_LENGTH)));
}
std::string output = "Subscription [exchange = " + exchange + ", instrument = " + instrument + ", field = " + field +
", optionMap = " + ccapi::toString(optionMap) + ", correlationId = " + correlationId +
", credential = " + ccapi::toString(shortCredential) + ", serviceName = " + serviceName +
", timeSent = " + UtilTime::getISOTimestamp(timeSent) + "]";
return output;
}
const std::string& getCorrelationId() const { return correlationId; }
const std::string& getExchange() const { return exchange; }
const std::string& getInstrument() const { return instrument; }
const std::string& getField() const { return field; }
const std::string& getRawOptions() const { return rawOptions; }
const std::map<std::string, std::string>& getOptionMap() const { return optionMap; }
const std::map<std::string, std::string>& getCredential() const { return credential; }
const std::string& getServiceName() const { return serviceName; }
const std::set<std::string>& getInstrumentSet() const { return instrumentSet; }
const std::set<std::string>& getFieldSet() const { return fieldSet; }
const std::string getSerializedOptions() const {
std::string output;
if (this->rawOptions.empty()) {
int i = 0;
for (const auto& option : this->optionMap) {
output += option.first;
output += "=";
output += option.second;
if (i < this->optionMap.size() - 1) {
output += "&";
}
++i;
}
} else {
output = this->rawOptions;
}
return output;
}
// 'getTimeSent' only works in C++. For other languages, please use 'getTimeSentISO'.
TimePoint getTimeSent() const { return timeSent; }
std::string getTimeSentISO() const { return UtilTime::getISOTimestamp(timeSent); }
std::pair<long long, long long> getTimeSentPair() const { return UtilTime::divide(timeSent); }
void setTimeSent(TimePoint timeSent) { this->timeSent = timeSent; }
enum class Status {
UNKNOWN,
SUBSCRIBING,
SUBSCRIBED,
UNSUBSCRIBING,
UNSUBSCRIBED,
};
static std::string statusToString(Status status) {
std::string output;
switch (status) {
case Status::UNKNOWN:
output = "UNKNOWN";
break;
case Status::SUBSCRIBING:
output = "SUBSCRIBING";
break;
case Status::SUBSCRIBED:
output = "SUBSCRIBED";
break;
case Status::UNSUBSCRIBING:
output = "UNSUBSCRIBING";
break;
case Status::UNSUBSCRIBED:
output = "UNSUBSCRIBED";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
return output;
}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
std::string exchange;
std::string instrument;
std::string field;
std::string rawOptions;
std::map<std::string, std::string> optionMap;
std::string correlationId;
std::map<std::string, std::string> credential;
std::string serviceName;
std::set<std::string> instrumentSet;
std::set<std::string> fieldSet;
TimePoint timeSent{std::chrono::seconds{0}};
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_SUBSCRIPTION_H_
+108
View File
@@ -0,0 +1,108 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_URL_H_
#define INCLUDE_CCAPI_CPP_CCAPI_URL_H_
#include <regex>
#include <string>
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_util_private.h"
namespace ccapi {
class Url CCAPI_FINAL {
public:
explicit Url(std::string urlStr) {
std::regex ex("^(.*:)//([A-Za-z0-9\\-\\.]+)(:[0-9]+)?(.*)$");
std::cmatch what;
if (std::regex_match(urlStr.c_str(), what, ex)) {
this->protocol = std::string(what[1].first, what[1].second);
this->host = std::string(what[2].first, what[2].second);
this->port = std::string(what[3].first, what[3].second);
this->target = std::string(what[4].first, what[4].second);
}
}
Url(std::string protocol, std::string host, std::string port, std::string target) : protocol(protocol), host(host), port(port), target(target) {}
std::string toString() const {
std::string output = "Url [protocol = " + protocol + ", host = " + host + ", port = " + port + ", target = " + target + "]";
return output;
}
static std::string urlEncode(const std::string &value) {
std::ostringstream escaped;
escaped.fill('0');
escaped << std::hex;
for (std::string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
std::string::value_type c = (*i);
// Keep alphanumeric and other accepted characters intact
if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
continue;
}
// Any other characters are percent-encoded
escaped << std::uppercase;
escaped << '%' << std::setw(2) << int((unsigned char)c);
escaped << std::nouppercase;
}
return escaped.str();
}
static std::string urlDecode(const std::string &value) {
std::string ret;
char ch;
int i, ii;
for (i = 0; i < value.length(); i++) {
if (static_cast<int>(value[i]) == 37) {
sscanf(value.substr(i + 1, 2).c_str(), "%x", &ii);
ch = static_cast<char>(ii);
ret += ch;
i = i + 2;
} else {
ret += value[i];
}
}
return (ret);
}
static std::map<std::string, std::string> convertQueryStringToMap(const std::string &input) {
std::map<std::string, std::string> output;
for (const auto &x : UtilString::split(input, "&")) {
auto y = UtilString::split(x, "=");
output.insert(std::make_pair(y.at(0), Url::urlDecode(y.at(1))));
}
return output;
}
static std::string convertMapToQueryString(const std::map<std::string, std::string> &input) {
std::string output;
for (const auto &x : input) {
output += x.first;
output += "=";
output += x.second;
output += "&";
}
if (!output.empty()) {
output.pop_back();
}
return output;
}
static std::string convertMapToFormUrlEncoded(const std::map<std::string, std::string> &input) {
std::string output;
int i = 0;
for (const auto &x : input) {
output += Url::urlEncode(x.first);
output += "=";
output += Url::urlEncode(x.second);
if (i < input.size() - 1) {
output += "&";
}
}
return output;
}
static std::map<std::string, std::string> convertFormUrlEncodedToMap(const std::string &input) {
std::map<std::string, std::string> output;
for (const auto &x : UtilString::split(input, "&")) {
auto y = UtilString::split(x, "=");
output.insert(std::make_pair(Url::urlDecode(y.at(0)), Url::urlDecode(y.at(1))));
}
return output;
}
std::string protocol;
std::string host;
std::string port;
std::string target; // should be url-encoded
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_URL_H_
+7
View File
@@ -0,0 +1,7 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_UTIL_H_
#define INCLUDE_CCAPI_CPP_CCAPI_UTIL_H_
#include <chrono>
namespace ccapi {
typedef std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds> TimePoint;
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_UTIL_H_
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,67 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_WS_CONNECTION_H_
#define INCLUDE_CCAPI_CPP_CCAPI_WS_CONNECTION_H_
#include <string>
#include "ccapi_cpp/ccapi_logger.h"
#include "ccapi_cpp/ccapi_subscription.h"
namespace wspp = websocketpp;
namespace ccapi {
class WsConnection CCAPI_FINAL {
public:
WsConnection(std::string url, std::string group, std::vector<Subscription> subscriptionList) : url(url), group(group), subscriptionList(subscriptionList) {
this->assignDummyId();
}
WsConnection() {}
void assignDummyId() {
this->id = this->url + "||" + this->group + "||" + ccapi::toString(this->subscriptionList);
this->hdl.reset();
}
std::string toString() const {
std::string output = "WsConnection [id = " + id + ", url = " + url + ", group = " + group + ", subscriptionList = " + ccapi::toString(subscriptionList) +
", status = " + statusToString(status) + ", headers = " + ccapi::toString(headers) + "]";
return output;
}
enum class Status {
UNKNOWN,
CONNECTING,
OPEN,
FAILED,
CLOSING,
CLOSED,
};
static std::string statusToString(Status status) {
std::string output;
switch (status) {
case Status::UNKNOWN:
output = "UNKNOWN";
break;
case Status::CONNECTING:
output = "CONNECTING";
break;
case Status::OPEN:
output = "OPEN";
break;
case Status::FAILED:
output = "FAILED";
break;
case Status::CLOSING:
output = "CLOSING";
break;
case Status::CLOSED:
output = "CLOSED";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
return output;
}
std::string id;
std::string url;
std::string group;
std::vector<Subscription> subscriptionList;
Status status{Status::UNKNOWN};
wspp::connection_hdl hdl = wspp::lib::weak_ptr<void>();
std::map<std::string, std::string> headers;
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_WS_CONNECTION_H_
@@ -0,0 +1,322 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#include <sys/stat.h>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include "boost/shared_ptr.hpp"
#include "ccapi_cpp/ccapi_event.h"
#include "ccapi_cpp/ccapi_hmac.h"
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/service/ccapi_service.h"
namespace ccapi {
class ExecutionManagementService : public Service {
public:
enum class JsonDataType {
STRING,
INTEGER,
BOOLEAN,
// DOUBLE, shouldn't be needed because double in a json response needs to parsed as string to preserve its precision
};
ExecutionManagementService(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: Service(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->requestOperationToMessageTypeMap = {
{Request::Operation::CREATE_ORDER, Message::Type::CREATE_ORDER},
{Request::Operation::CANCEL_ORDER, Message::Type::CANCEL_ORDER},
{Request::Operation::GET_ORDER, Message::Type::GET_ORDER},
{Request::Operation::GET_OPEN_ORDERS, Message::Type::GET_OPEN_ORDERS},
{Request::Operation::CANCEL_OPEN_ORDERS, Message::Type::CANCEL_OPEN_ORDERS},
{Request::Operation::GET_ACCOUNTS, Message::Type::GET_ACCOUNTS},
{Request::Operation::GET_ACCOUNT_BALANCES, Message::Type::GET_ACCOUNT_BALANCES},
{Request::Operation::GET_ACCOUNT_POSITIONS, Message::Type::GET_ACCOUNT_POSITIONS},
};
}
virtual ~ExecutionManagementService() {}
// 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);
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);
});
}
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
static std::map<std::string, std::string> convertHeaderStringToMap(const std::string& input) {
std::map<std::string, std::string> output;
if (!input.empty()) {
for (const auto& x : UtilString::split(input, "\r\n")) {
auto y = UtilString::split(x, ':');
output.insert(std::make_pair(UtilString::trim(y.at(0)), UtilString::trim(y.at(1))));
}
}
return output;
}
static std::string convertHeaderMapToString(const std::map<std::string, std::string>& input) {
std::string output;
int i = 0;
for (const auto& x : input) {
output += x.first;
output += ":";
output += x.second;
if (i < input.size() - 1) {
output += "\r\n";
}
++i;
}
return output;
}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
virtual std::vector<Message> convertTextMessageToMessageRest(const Request& request, const std::string& textMessage, const TimePoint& timeReceived) {
CCAPI_LOGGER_DEBUG("textMessage = " + textMessage);
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({request.getCorrelationId()});
std::vector<Element> elementList;
Request::Operation operation = request.getOperation();
message.setType(this->requestOperationToMessageTypeMap.at(operation));
auto castedOperation = static_cast<int>(operation);
if (castedOperation >= Request::operationTypeExecutionManagementOrder && castedOperation < Request::operationTypeExecutionManagementAccount) {
this->extractOrderInfoFromRequest(elementList, request, operation, document);
message.setElementList(elementList);
} else if (castedOperation >= Request::operationTypeExecutionManagementAccount) {
this->extractAccountInfoFromRequest(elementList, request, operation, document);
message.setElementList(elementList);
}
std::vector<Message> messageList;
messageList.emplace_back(std::move(message));
return messageList;
}
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)) {
event.setType(Event::Type::RESPONSE);
Message message;
message.setType(Message::Type::RESPONSE_ERROR);
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({request.getCorrelationId()});
Element element;
element.insert(CCAPI_HTTP_STATUS_CODE, "200");
element.insert(CCAPI_ERROR_MESSAGE, UtilString::trim(textMessage));
message.setElementList({element});
event.setMessageList({message});
} else {
event.setType(Event::Type::RESPONSE);
if (request.getOperation() == Request::Operation::GENERIC_PRIVATE_REQUEST) {
Message message;
message.setTimeReceived(timeReceived);
message.setType(Message::Type::GENERIC_PRIVATE_REQUEST);
Element element;
element.insert(CCAPI_HTTP_STATUS_CODE, std::to_string(statusCode));
element.insert(CCAPI_HTTP_BODY, textMessage);
message.setElementList({element});
const std::vector<std::string>& correlationIdList = {request.getCorrelationId()};
CCAPI_LOGGER_TRACE("correlationIdList = " + toString(correlationIdList));
message.setCorrelationIdList(correlationIdList);
event.addMessages({message});
} else {
const std::vector<Message>& messageList = this->convertTextMessageToMessageRest(request, textMessage, timeReceived);
event.addMessages(messageList);
}
}
if (!event.getMessageList().empty()) {
this->eventHandler(event, eventQueuePtr);
}
}
virtual void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) {
for (const auto& y : extractionFieldNameMap) {
auto it = x.FindMember(y.second.first.c_str());
if (it != x.MemberEnd() && !it->value.IsNull()) {
std::string value = y.second.second == JsonDataType::STRING ? it->value.GetString()
: y.second.second == JsonDataType::INTEGER ? std::string(it->value.GetString())
: y.second.second == JsonDataType::BOOLEAN ? std::to_string(static_cast<int>(it->value.GetBool()))
: "null";
if (y.first == CCAPI_EM_ORDER_SIDE) {
value = UtilString::toLower(value).rfind("buy", 0) == 0 ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL;
}
element.insert(y.first, value);
}
}
}
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 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;
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 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->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived);
}
void onOpen(wspp::connection_hdl hdl) override {
CCAPI_LOGGER_FUNCTION_ENTER;
Service::onOpen(hdl);
auto now = UtilTime::now();
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
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;
}
this->logonToExchange(wsConnection, now, credential);
}
void onClose(wspp::connection_hdl hdl) override {
CCAPI_LOGGER_FUNCTION_ENTER;
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
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(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);
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);
if (ec) {
that->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request");
}
});
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 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();
auto methodString = mapGetWithDefault(param, std::string(CCAPI_HTTP_METHOD));
CCAPI_LOGGER_TRACE("methodString = " + methodString);
auto headerString = mapGetWithDefault(param, std::string(CCAPI_HTTP_HEADERS));
CCAPI_LOGGER_TRACE("headerString = " + headerString);
auto path = mapGetWithDefault(param, std::string(CCAPI_HTTP_PATH));
CCAPI_LOGGER_TRACE("path = " + path);
auto queryString = mapGetWithDefault(param, std::string(CCAPI_HTTP_QUERY_STRING));
CCAPI_LOGGER_TRACE("queryString = " + queryString);
auto body = mapGetWithDefault(param, std::string(CCAPI_HTTP_BODY));
CCAPI_LOGGER_TRACE("body = " + body);
this->signReqeustForRestGenericPrivateRequest(req, request, methodString, headerString, path, queryString, body, now, credential);
req.method(this->convertHttpMethodStringToMethod(methodString));
if (!headerString.empty()) {
auto splitted = UtilString::split(headerString, "\r\n");
for (const auto& x : splitted) {
auto splitted_2 = UtilString::split(x, ':');
req.set(UtilString::trim(splitted_2.at(0)), UtilString::trim(splitted_2.at(1)));
}
}
auto target = path;
if (!queryString.empty()) {
target += "?" + queryString;
}
req.target(target);
if (!body.empty()) {
req.body() = body;
req.prepare_payload();
}
}
int64_t generateNonce(const TimePoint& now, int requestIndex = 0) {
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) {}
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,
const Request& request, int wsRequestId, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) {}
virtual void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) {}
virtual void extractAccountInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) {}
virtual std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription,
const TimePoint& now, const std::map<std::string, std::string>& credential) {
return {};
}
virtual 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) {}
std::string createOrderTarget;
std::string cancelOrderTarget;
std::string getOrderTarget;
std::string getOpenOrdersTarget;
std::string cancelOpenOrdersTarget;
std::string getAccountsTarget;
std::string getAccountBalancesTarget;
std::string getAccountPositionsTarget;
std::map<std::string, std::string> correlationIdByConnectionIdMap;
std::map<std::string, WsConnection> wsConnectionByCorrelationIdMap;
std::map<std::string, int> wsRequestIdByConnectionIdMap;
};
} /* namespace ccapi */
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_H_
@@ -0,0 +1,498 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_ASCENDEX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_ASCENDEX_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceAscendex : public ExecutionManagementService {
public:
ExecutionManagementServiceAscendex(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_ASCENDEX;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_ASCENDEX_API_KEY;
this->apiSecretName = CCAPI_ASCENDEX_API_SECRET;
this->apiAccountGroupName = CCAPI_ASCENDEX_API_ACCOUNT_GROUP;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiAccountGroupName});
this->createOrderTarget = "/api/pro/v1/cash/order";
this->cancelOrderTarget = "/api/pro/v1/cash/order";
this->getOrderTarget = "/api/pro/v1/cash/order/status";
this->getOpenOrdersTarget = "/api/pro/v1/cash/order/open";
this->cancelOpenOrdersTarget = "/api/pro/v1/cash/order/all";
this->getAccountBalancesTarget = "/api/pro/v1/cash/balance";
}
virtual ~ExecutionManagementServiceAscendex() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#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 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 {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("x-auth-timestamp").to_string();
preSignedText += "+";
auto splitted = UtilString::split(path, '/');
std::vector<std::string> subSplitted(splitted.begin() + 6, splitted.begin() + splitted.size());
preSignedText += UtilString::join(subSplitted, "/");
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText));
req.set("x-auth-signature", signature);
if (!body.empty()) {
req.body() = body;
req.prepare_payload();
}
}
void signRequest(http::request<http::string_body>& req, const std::string& apiPath, const std::map<std::string, std::string>& credential) {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("x-auth-timestamp").to_string();
preSignedText += "+";
preSignedText += apiPath;
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText));
req.set("x-auth-signature", signature);
}
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, "id"},
{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 ? "buy" : "sell";
}
if (value != "null") {
if (value == "true" || value == "false") {
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 += "instId=";
queryString += Url::urlEncode(symbolId);
queryString += "&";
}
void convertRequestForRest(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
req.set(beast::http::field::accept, "application/json");
req.set(beast::http::field::content_type, "application/json");
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("x-auth-key", apiKey);
req.set("x-auth-timestamp", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
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();
const auto& accountGroup = mapGetWithDefault(credential, this->apiAccountGroupName);
req.target("/" + accountGroup + this->createOrderTarget);
this->signRequest(req, "order", credential);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
if (param.find("time") == param.end()) {
document.AddMember("time", rj::Value(static_cast<int64_t>(std::stoll(req.base().at("x-auth-timestamp").to_string()))).Move(), allocator);
}
if (param.find("orderType") == param.end()) {
document.AddMember("orderType", 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();
} break;
case Request::Operation::CANCEL_ORDER: {
req.method(http::verb::delete_);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
const auto& accountGroup = mapGetWithDefault(credential, this->apiAccountGroupName);
req.target("/" + accountGroup + this->cancelOrderTarget);
this->signRequest(req, "order", credential);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
if (param.find("time") == param.end()) {
document.AddMember("time", rj::Value(static_cast<int64_t>(std::stoll(req.base().at("x-auth-timestamp").to_string()))).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();
} break;
case Request::Operation::GET_ORDER: {
req.method(http::verb::get);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
const auto& accountGroup = mapGetWithDefault(credential, this->apiAccountGroupName);
std::string queryString;
this->appendParam(queryString, param,
{
{CCAPI_EM_ORDER_ID, "orderId"},
});
req.target("/" + accountGroup + this->getOrderTarget + "?" + queryString);
this->signRequest(req, "order/status", 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();
const auto& accountGroup = mapGetWithDefault(credential, this->apiAccountGroupName);
if (!symbolId.empty()) {
this->appendSymbolId(queryString, symbolId);
}
if (queryString.back() == '&') {
queryString.pop_back();
}
std::string target("/" + accountGroup + this->getOpenOrdersTarget);
if (!queryString.empty()) {
target += "?" + queryString;
}
req.target(target);
this->signRequest(req, "order/open", credential);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
req.method(http::verb::delete_);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
const auto& accountGroup = mapGetWithDefault(credential, this->apiAccountGroupName);
req.target("/" + accountGroup + this->cancelOpenOrdersTarget);
this->signRequest(req, "order/all", credential);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(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();
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
req.method(http::verb::get);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
const auto& accountGroup = mapGetWithDefault(credential, this->apiAccountGroupName);
req.target("/" + accountGroup + this->getAccountBalancesTarget);
this->signRequest(req, "balance", credential);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void convertRequestForWebsocket(rj::Document& document, rj::Document::AllocatorType& allocator, const WsConnection& wsConnection, const Request& request,
int wsRequestId, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
document.SetObject();
document.AddMember("id", rj::Value(std::to_string(wsRequestId).c_str(), allocator).Move(), allocator);
switch (request.getOperation()) {
case Request::Operation::CREATE_ORDER: {
document.AddMember("op", rj::Value("req").Move(), allocator);
document.AddMember("action", rj::Value("place-Order").Move(), allocator);
document.AddMember("account", rj::Value("cash").Move(), allocator);
rj::Value args(rj::kObjectType);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(args, allocator, param);
if (param.find("time") == param.end()) {
args.AddMember("time", rj::Value(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()).Move(), allocator);
}
if (param.find("orderType") == param.end()) {
args.AddMember("orderType", rj::Value("limit").Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(args, allocator, symbolId);
}
document.AddMember("args", args, allocator);
} break;
case Request::Operation::CANCEL_ORDER: {
document.AddMember("op", rj::Value("req").Move(), allocator);
document.AddMember("action", rj::Value("cancel-Order").Move(), allocator);
document.AddMember("account", rj::Value("cash").Move(), allocator);
rj::Value args(rj::kObjectType);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(args, allocator, param);
if (param.find("time") == param.end()) {
args.AddMember("time", rj::Value(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()).Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(args, allocator, symbolId);
}
document.AddMember("args", args, allocator);
} break;
default:
this->convertRequestForWebsocketCustom(document, allocator, wsConnection, request, wsRequestId, now, symbolId, credential);
}
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
this->extractOrderInfoFromRequest(elementList, document);
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const rj::Value& value) {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("orderQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumFilledQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}};
auto itData = value.FindMember("data");
if (itData != value.MemberEnd()) {
const rj::Value& data = itData->value;
if (data.IsObject()) {
Element element;
if (data.FindMember("info") != data.MemberEnd()) {
this->extractOrderInfo(element, data["info"], extractionFieldNameMap);
} else {
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));
}
}
} else {
Element element;
this->extractOrderInfo(element, value, 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["asset"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["availableBalance"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["totalBalance"].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("cumFilledQty");
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)));
}
}
}
}
void subscribe(std::vector<Subscription>& subscriptionList) override {
if (this->shouldContinue.load()) {
for (auto& subscription : subscriptionList) {
wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(),
[that = shared_from_base<ExecutionManagementServiceAscendex>(), subscription]() mutable {
auto now = UtilTime::now();
subscription.setTimeSent(now);
auto credential = subscription.getCredential();
if (credential.empty()) {
credential = that->credentialDefault;
}
const auto& accountGroup = mapGetWithDefault(credential, that->apiAccountGroupName);
WsConnection wsConnection(that->baseUrl + "/" + accountGroup + "/api/pro/v1/stream", "", {subscription});
that->prepareConnect(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("op", rj::Value("auth").Move(), allocator);
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
int64_t t = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
document.AddMember("key", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
document.AddMember("t", rj::Value(t).Move(), allocator);
std::string signData = std::to_string(t) + "+stream";
std::string sign = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, signData));
document.AddMember("sig", rj::Value(sign.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()});
auto mIt = document.FindMember("m");
if (mIt != document.MemberEnd()) {
std::string m = mIt->value.GetString();
if (m == "order") {
auto itAction = document.FindMember("action");
if (itAction != document.MemberEnd()) {
std::string action = itAction->value.GetString();
event.setType(Event::Type::RESPONSE);
std::string status = document["status"].GetString();
if (status == "Err") {
message.setType(Message::Type::RESPONSE_ERROR);
Element element;
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
} else {
std::vector<Element> elementList;
if (action == "place-order") {
message.setType(Message::Type::CREATE_ORDER);
} else if (action == "cancel-order") {
message.setType(Message::Type::CANCEL_ORDER);
}
this->extractOrderInfoFromRequest(elementList, document["info"]);
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
} else {
const rj::Value& data = document["data"];
event.setType(Event::Type::SUBSCRIPTION_DATA);
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
std::string instrument = data["s"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(data["t"].GetString()))));
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::INTEGER)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("sd", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("p", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("q", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cfq", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("st", 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,
UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(data["cfq"].GetString())));
}
info.insert(CCAPI_EM_BASE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING, data["bab"].GetString());
info.insert(CCAPI_EM_BASE_ASSET_QUANTITY_TOTAL, data["btb"].GetString());
info.insert(CCAPI_EM_QUOTE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING, data["qab"].GetString());
info.insert(CCAPI_EM_QUOTE_ASSET_QUANTITY_TOTAL, data["qtb"].GetString());
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
} else if (m == "sub") {
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 (m == "auth") {
rj::Document document;
document.SetObject();
auto& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("sub").Move(), allocator);
document.AddMember("ch", rj::Value("order:cash").Move(), 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 if (m == "connected") {
std::string type = document["type"].GetString();
if (type == "unauth") {
ExecutionManagementService::onOpen(hdl);
}
}
}
event.setMessageList(messageList);
return event;
}
std::string apiAccountGroupName;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_ASCENDEX_H_
@@ -0,0 +1,40 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE
#ifndef CCAPI_BINANCE_CREATE_ORDER_PATH
#define CCAPI_BINANCE_CREATE_ORDER_PATH "/api/v3/order"
#endif
#include "ccapi_cpp/service/ccapi_execution_management_service_binance_base.h"
namespace ccapi {
class ExecutionManagementServiceBinance : public ExecutionManagementServiceBinanceBase {
public:
ExecutionManagementServiceBinance(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_BINANCE_API_KEY;
this->apiSecretName = CCAPI_BINANCE_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = CCAPI_BINANCE_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_BINANCE_LISTEN_KEY_PATH;
this->getAccountBalancesTarget = "/api/v3/account";
}
virtual ~ExecutionManagementServiceBinance() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_H_
@@ -0,0 +1,418 @@
#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
#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)
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceBinanceBase : public ExecutionManagementService {
public:
ExecutionManagementServiceBinanceBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->enableCheckPingPongWebsocketApplicationLevel = false;
this->pingListenKeyIntervalSeconds = 600;
}
virtual ~ExecutionManagementServiceBinanceBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& req, const Request& request, std::string& methodString,
std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
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-MBX-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.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&";
if (param.find("timeInForce") == param.end()) {
queryString += "timeInForce=GTC&";
}
}
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(this->isDerivatives ? "cumQuote" : "cummulativeQuoteQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
};
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[this->isDerivatives ? "assets" : "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());
elementList.emplace_back(std::move(element));
}
} break;
default:
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<ExecutionManagementServiceBinanceBase>()](const beast::error_code& ec) {
WsConnection thisWsConnection = wsConnection;
that->onFail_(thisWsConnection);
},
[wsConnection, that = shared_from_base<ExecutionManagementServiceBinanceBase>()](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);
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;
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;
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<ExecutionManagementServiceBinanceBase>()](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<ExecutionManagementServiceBinanceBase>()](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 event;
std::vector<Message> messageList;
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()) {
if (executionType == "TRADE" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll((this->isDerivatives ? document : data)["E"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_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_CLIENT_ORDER_ID, std::string(data["c"].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()));
}
}
{
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));
}
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll((this->isDerivatives ? document : data)["E"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_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("C");
if (it != data.MemberEnd() && !it->value.IsNull() && it->value.GetStringLength()) {
info.insert(CCAPI_EM_ORIGINAL_CLIENT_ORDER_ID, std::string(it->value.GetString()));
}
}
{
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));
}
}
}
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_BYBIT_H_
@@ -0,0 +1,39 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_COIN_FUTURES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_COIN_FUTURES_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_COIN_FUTURES
#include "ccapi_cpp/service/ccapi_execution_management_service_binance_derivatives_base.h"
namespace ccapi {
class ExecutionManagementServiceBinanceCoinFutures : public ExecutionManagementServiceBinanceDerivativesBase {
public:
ExecutionManagementServiceBinanceCoinFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_BINANCE_COIN_FUTURES_API_KEY;
this->apiSecretName = CCAPI_BINANCE_COIN_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = CCAPI_BINANCE_COIN_FUTURES_CREATE_ORDER_PATH;
this->cancelOrderTarget = "/dapi/v1/order";
this->getOrderTarget = "/dapi/v1/order";
this->getOpenOrdersTarget = "/dapi/v1/openOrders";
this->cancelOpenOrdersTarget = "/dapi/v1/allOpenOrders";
this->isDerivatives = true;
this->listenKeyTarget = CCAPI_BINANCE_COIN_FUTURES_LISTEN_KEY_PATH;
this->getAccountBalancesTarget = "/dapi/v1/account";
this->getAccountPositionsTarget = "/dapi/v1/account";
}
virtual ~ExecutionManagementServiceBinanceCoinFutures() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_COIN_FUTURES_H_
@@ -0,0 +1,59 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_DERIVATIVES_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_DERIVATIVES_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#if defined(CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES) || defined(CCAPI_ENABLE_EXCHANGE_BINANCE_COIN_FUTURES)
#include "ccapi_cpp/service/ccapi_execution_management_service_binance_base.h"
namespace ccapi {
class ExecutionManagementServiceBinanceDerivativesBase : public ExecutionManagementServiceBinanceBase {
public:
ExecutionManagementServiceBinanceDerivativesBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions,
SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->isDerivatives = true;
}
virtual ~ExecutionManagementServiceBinanceDerivativesBase() {}
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::GET_ACCOUNT_POSITIONS: {
this->prepareReq(req, credential);
req.method(http::verb::get);
std::string queryString;
this->appendParam(queryString, {});
this->signRequest(queryString, {}, now, credential);
req.target(this->getAccountPositionsTarget + "?" + queryString);
} break;
default:
ExecutionManagementServiceBinanceBase::convertRequestForRest(req, request, now, symbolId, credential);
}
}
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_POSITIONS: {
for (const auto& x : document["positions"].GetArray()) {
Element element;
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["positionSide"].GetString());
std::string positionAmt;
auto it = x.FindMember("positionAmt");
if (it != x.MemberEnd()) {
positionAmt = it->value.GetString();
} else {
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_LEVERAGE, x["leverage"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
default:
ExecutionManagementServiceBinanceBase::extractAccountInfoFromRequest(elementList, request, operation, document);
}
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_DERIVATIVES_BASE_H_
@@ -0,0 +1,37 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_US_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_US_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_US
#include "ccapi_cpp/service/ccapi_execution_management_service_binance_base.h"
namespace ccapi {
class ExecutionManagementServiceBinanceUs : public ExecutionManagementServiceBinanceBase {
public:
ExecutionManagementServiceBinanceUs(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_US;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_BINANCE_US_API_KEY;
this->apiSecretName = CCAPI_BINANCE_US_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = CCAPI_BINANCE_US_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_BINANCE_US_LISTEN_KEY_PATH;
this->getAccountBalancesTarget = "/api/v3/account";
}
virtual ~ExecutionManagementServiceBinanceUs() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_US_H_
@@ -0,0 +1,39 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_USDS_FUTURES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_USDS_FUTURES_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES
#include "ccapi_cpp/service/ccapi_execution_management_service_binance_derivatives_base.h"
namespace ccapi {
class ExecutionManagementServiceBinanceUsdsFutures : public ExecutionManagementServiceBinanceDerivativesBase {
public:
ExecutionManagementServiceBinanceUsdsFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_BINANCE_USDS_FUTURES_API_KEY;
this->apiSecretName = CCAPI_BINANCE_USDS_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = CCAPI_BINANCE_USDS_FUTURES_CREATE_ORDER_PATH;
this->cancelOrderTarget = "/fapi/v1/order";
this->getOrderTarget = "/fapi/v1/order";
this->getOpenOrdersTarget = "/fapi/v1/openOrders";
this->cancelOpenOrdersTarget = "/fapi/v1/allOpenOrders";
this->isDerivatives = true;
this->listenKeyTarget = CCAPI_BINANCE_USDS_FUTURES_LISTEN_KEY_PATH;
this->getAccountBalancesTarget = "/fapi/v2/account";
this->getAccountPositionsTarget = "/fapi/v2/account";
}
virtual ~ExecutionManagementServiceBinanceUsdsFutures() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BINANCE_USDS_FUTURES_H_
@@ -0,0 +1,459 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITFINEX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITFINEX_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_BITFINEX
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
public:
ExecutionManagementServiceBitfinex(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = CCAPI_BITFINEX_PRIVATE_URL_REST_BASE;
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_BITFINEX_API_KEY;
this->apiSecretName = CCAPI_BITFINEX_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = "/v2/auth/w/order/submit";
this->cancelOrderTarget = "/v2/auth/w/order/cancel";
this->getOrderTarget = "/v2/auth/r/orders/:Symbol/hist";
this->getOpenOrdersTarget = "/v2/auth/r/orders/:Symbol";
this->getAccountBalancesTarget = "/v2/auth/r/wallets";
this->getAccountPositionsTarget = "/v2/auth/r/positions";
}
virtual ~ExecutionManagementServiceBitfinex() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl, "{\"cid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec);
}
void 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 {
this->prepareReq(req, request, now, credential);
this->signRequest(req, path, body, credential);
}
void signRequest(http::request<http::string_body>& req, const std::string& path, const std::string& body,
const std::map<std::string, std::string>& credential) {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string preSignedText = "/api";
preSignedText += path;
preSignedText += req.base().at("bfx-nonce").to_string();
preSignedText += body;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA384, apiSecret, preSignedText, true);
req.set("bfx-signature", signature);
req.target(path);
req.body() = body;
req.prepare_payload();
}
void appendParam(const Request& request, 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_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "cid"},
{CCAPI_EM_ORDER_ID, "id"},
{CCAPI_EM_POSITION_LEVERAGE, "lev"},
}) {
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_QUANTITY && key != CCAPI_EM_ORDER_SIDE) {
if (key != "id" & key != "gid" && key != "cid" && key != "flags" && key != "lev") {
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
} else {
int64_t x = std::stoll(value);
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(x).Move(), allocator);
}
}
}
}
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 Request& request, const TimePoint& now, const std::map<std::string, std::string>& credential) {
req.set(beast::http::field::content_type, "application/json");
int64_t nonce = this->generateNonce(now, request.getIndex());
req.set("bfx-nonce", std::to_string(nonce));
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("bfx-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, request, 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();
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(request, document, allocator, param);
this->appendSymbolId(document, allocator, symbolId);
auto orderQuantity = mapGetWithDefault(param, std::string(CCAPI_EM_ORDER_QUANTITY));
auto orderSide = mapGetWithDefault(param, std::string(CCAPI_EM_ORDER_SIDE));
std::string amount = orderSide == CCAPI_EM_ORDER_SIDE_BUY ? orderQuantity : "-" + orderQuantity;
document.AddMember("amount", rj::Value(amount.c_str(), allocator).Move(), allocator);
if (param.find("type") == param.end()) {
document.AddMember("type", rj::Value("EXCHANGE LIMIT").Move(), allocator);
}
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
auto body = stringBuffer.GetString();
this->signRequest(req, this->createOrderTarget, body, credential);
} break;
case Request::Operation::CANCEL_ORDER: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(request, document, allocator, param);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
auto body = stringBuffer.GetString();
this->signRequest(req, this->cancelOrderTarget, body, credential);
} break;
case Request::Operation::GET_ORDER: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(request, document, allocator, param);
auto id = mapGetWithDefault(param, std::string(CCAPI_EM_ORDER_ID));
if (!id.empty()) {
rj::Value ids(rj::kArrayType);
for (const auto& x : UtilString::split(id, ",")) {
ids.PushBack(rj::Value(x.c_str(), allocator).Move(), allocator);
}
document.AddMember("id", ids, allocator);
}
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
auto body = stringBuffer.GetString();
this->signRequest(req,
symbolId.empty() ? UtilString::replaceFirstOccurrence(this->getOrderTarget, "/:Symbol", "")
: UtilString::replaceFirstOccurrence(this->getOrderTarget, ":Symbol", symbolId),
body, credential);
} break;
case Request::Operation::GET_OPEN_ORDERS: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(request, document, allocator, param);
auto id = mapGetWithDefault(param, std::string(CCAPI_EM_ORDER_ID));
if (!id.empty()) {
rj::Value ids(rj::kArrayType);
for (const auto& x : UtilString::split(id, ",")) {
ids.PushBack(rj::Value(x.c_str(), allocator).Move(), allocator);
}
document.AddMember("id", ids, allocator);
}
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
auto body = stringBuffer.GetString();
this->signRequest(req,
symbolId.empty() ? UtilString::replaceFirstOccurrence(this->getOpenOrdersTarget, "/:Symbol", "")
: UtilString::replaceFirstOccurrence(this->getOrderTarget, ":Symbol", symbolId),
body, credential);
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->signRequest(req, this->getAccountBalancesTarget, "", credential);
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->signRequest(req, this->getAccountPositionsTarget, "", credential);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void convertRequestForWebsocket(rj::Document& document, rj::Document::AllocatorType& allocator, const WsConnection& wsConnection, const Request& request,
int wsRequestId, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
switch (request.getOperation()) {
case Request::Operation::CREATE_ORDER: {
document.SetArray();
document.PushBack(rj::Value(0).Move(), allocator);
document.PushBack(rj::Value("on", allocator).Move(), allocator);
document.PushBack(rj::Value().Move(), allocator);
rj::Value inputDetails(rj::kObjectType);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(request, inputDetails, allocator, param);
this->appendSymbolId(inputDetails, allocator, symbolId);
auto orderQuantity = mapGetWithDefault(param, std::string(CCAPI_EM_ORDER_QUANTITY));
auto orderSide = mapGetWithDefault(param, std::string(CCAPI_EM_ORDER_SIDE));
std::string amount = orderSide == CCAPI_EM_ORDER_SIDE_BUY ? orderQuantity : "-" + orderQuantity;
inputDetails.AddMember("amount", rj::Value(amount.c_str(), allocator).Move(), allocator);
if (param.find("type") == param.end()) {
inputDetails.AddMember("type", rj::Value("EXCHANGE LIMIT").Move(), allocator);
}
document.PushBack(inputDetails, allocator);
} break;
case Request::Operation::CANCEL_ORDER: {
document.SetArray();
document.PushBack(rj::Value(0).Move(), allocator);
document.PushBack(rj::Value("oc", allocator).Move(), allocator);
document.PushBack(rj::Value().Move(), allocator);
rj::Value inputDetails(rj::kObjectType);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(request, inputDetails, allocator, param);
document.PushBack(inputDetails, allocator);
} break;
default:
this->convertRequestForWebsocketCustom(document, allocator, wsConnection, request, wsRequestId, now, symbolId, credential);
}
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
if (operation == Request::Operation::CREATE_ORDER || operation == Request::Operation::CANCEL_ORDER) {
Element element;
this->extractOrderInfo(element, document[4][0]);
elementList.emplace_back(std::move(element));
} else if (operation == Request::Operation::GET_ORDER) {
Element element;
this->extractOrderInfo(element, document[0]);
elementList.emplace_back(std::move(element));
} else if (operation == Request::Operation::GET_OPEN_ORDERS) {
for (const auto& x : document.GetArray()) {
Element element;
this->extractOrderInfo(element, x);
elementList.emplace_back(std::move(element));
}
}
}
void extractOrderInfoFromRequestForWebsocket(std::vector<Element>& elementList, const rj::Value& value) {
Element element;
this->extractOrderInfo(element, value);
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.GetArray()) {
Element element;
element.insert(CCAPI_EM_ACCOUNT_TYPE, x[0].GetString());
element.insert(CCAPI_EM_ASSET, x[1].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x[2].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x[4].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["instId"].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_COST, std::to_string(std::stod(x["avgPx"].GetString()) * std::stod(positionQuantity)));
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) {
element.insert(CCAPI_EM_ORDER_ID, x[0].GetString());
element.insert(CCAPI_EM_CLIENT_ORDER_ID, x[2].GetString());
element.insert(CCAPI_EM_ORDER_INSTRUMENT, x[3].GetString());
std::string originalAmount = x[7].GetString();
if (originalAmount.at(0) == '-') {
originalAmount.erase(0, 1);
element.insert(CCAPI_EM_ORDER_SIDE, CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_EM_ORDER_QUANTITY, originalAmount);
} else {
element.insert(CCAPI_EM_ORDER_SIDE, CCAPI_EM_ORDER_SIDE_BUY);
element.insert(CCAPI_EM_ORDER_QUANTITY, originalAmount);
}
std::string amount = x[6].GetString();
if (amount.at(0) == '-') {
amount.erase(0, 1);
element.insert(CCAPI_EM_ORDER_REMAINING_QUANTITY, amount);
} else {
element.insert(CCAPI_EM_ORDER_REMAINING_QUANTITY, amount);
}
element.insert(CCAPI_EM_ORDER_REMAINING_QUANTITY, x[6].GetString());
element.insert(CCAPI_EM_ORDER_STATUS, x[13].GetString());
element.insert(CCAPI_EM_ORDER_LIMIT_PRICE, x[16].GetString());
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(x[17].GetString()) * (std::stod(originalAmount) - std::stod(amount)))).toString());
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
std::vector<std::string> sendStringList;
rj::Document document;
document.SetObject();
auto& allocator = document.GetAllocator();
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
document.AddMember("event", rj::Value("auth").Move(), allocator);
document.AddMember("apiKey", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
int64_t nonce = this->generateNonce(now);
document.AddMember("authNonce", rj::Value(nonce).Move(), allocator);
std::string authPayload = "AUTH" + std::to_string(nonce);
document.AddMember("authPayload", rj::Value(authPayload.c_str(), allocator).Move(), allocator);
std::string authSig = Hmac::hmac(Hmac::ShaVersion::SHA384, apiSecret, authPayload, true);
document.AddMember("authSig", rj::Value(authSig.c_str(), allocator).Move(), allocator);
rj::Value filter(rj::kArrayType);
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
if (instrumentSet.empty()) {
filter.PushBack(rj::Value("trading").Move(), allocator);
} else {
for (const auto& instrument : instrumentSet) {
filter.PushBack(rj::Value(("trading-" + instrument).c_str(), allocator).Move(), allocator);
}
}
}
document.AddMember("filter", filter, 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 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 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.IsArray() && document.Size() >= 3 && std::string(document[0].GetString()) == "0") {
std::string type = document[1].GetString();
if ((type == CCAPI_BITFINEX_STREAM_TRADE_RAW_MESSAGE_TYPE) && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document[2];
std::string instrument = data[1].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(data[2].GetString())));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
if (type == "tu") {
element.insert(CCAPI_TRADE_ID, data[2].GetString());
}
std::string amount = data[4].GetString();
if (amount.at(0) == '-') {
amount.erase(0, 1);
element.insert(CCAPI_EM_ORDER_SIDE, CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, amount);
} else {
element.insert(CCAPI_EM_ORDER_SIDE, CCAPI_EM_ORDER_SIDE_BUY);
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, amount);
}
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data[5].GetString());
element.insert(CCAPI_IS_MAKER, std::string(data[8].GetString()).at(0) != '-' ? "1" : "0");
element.insert(CCAPI_EM_ORDER_INSTRUMENT, data[1].GetString());
element.insert(CCAPI_EM_ORDER_ID, data[3].GetString());
element.insert(CCAPI_EM_CLIENT_ORDER_ID, data[11].GetString());
if (type == "tu") {
std::string fee = data[9].GetString();
if (fee.at(0) == '-') {
fee.erase(0, 1);
} else {
fee.insert(0, 1, '-');
}
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, fee);
element.insert(CCAPI_EM_ORDER_FEE_ASSET, data[10].GetString());
}
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
} else if ((type == "on" || type == "ou" || type == "oc") && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document[2];
std::string instrument = data[3].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(data[5].GetString())));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
Element info;
this->extractOrderInfo(info, data);
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
} else if (type == "n") {
event.setType(Event::Type::RESPONSE);
const rj::Value& data = document[2];
std::string status = data[6].GetString();
if (status != "SUCCESS") {
message.setType(Message::Type::RESPONSE_ERROR);
Element element;
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
} else {
std::vector<Element> elementList;
std::string notificationType = data[1].GetString();
if (notificationType == "on-req") {
message.setType(Message::Type::CREATE_ORDER);
} else if (notificationType == "oc-req") {
message.setType(Message::Type::CANCEL_ORDER);
}
this->extractOrderInfoFromRequestForWebsocket(elementList, data[4]);
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
} else if (document.IsObject()) {
auto it = document.FindMember("event");
if (it != document.MemberEnd()) {
std::string eventStr = it->value.GetString();
if (eventStr == "auth") {
std::string status = document["status"].GetString();
event.setType(Event::Type::SUBSCRIPTION_STATUS);
message.setType(status == "OK" ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(status == "OK" ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
}
}
}
event.setMessageList(messageList);
return event;
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITFINEX_H_
@@ -0,0 +1,454 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITMEX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITMEX_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_BITMEX
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceBitmex : public ExecutionManagementService {
public:
ExecutionManagementServiceBitmex(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITMEX;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/realtime";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_BITMEX_API_KEY;
this->apiSecretName = CCAPI_BITMEX_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
std::string prefix = "/api/v1";
this->createOrderTarget = prefix + "/order";
this->cancelOrderTarget = prefix + "/order";
this->getOrderTarget = prefix + "/order";
this->getOpenOrdersTarget = prefix + "/order";
this->cancelOpenOrdersTarget = prefix + "/order/all";
this->getAccountBalancesTarget = prefix + "/user/margin";
this->getAccountPositionsTarget = prefix + "/position";
}
virtual ~ExecutionManagementServiceBitmex() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& req, const Request& request, std::string& methodString,
std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = methodString;
std::string target = path;
if (!queryString.empty()) {
target += "?" + queryString;
}
preSignedText += target;
preSignedText += req.base().at("api-expires").to_string();
preSignedText += body;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
if (!headerString.empty()) {
headerString += "\r\n";
}
headerString += "api-signature:" + 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 = std::string(req.method_string());
preSignedText += req.target().to_string();
preSignedText += req.base().at("api-expires").to_string();
preSignedText += body;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
req.set("api-signature", signature);
req.body() = body;
req.prepare_payload();
}
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 = {}) {
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";
}
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 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");
req.set("api-expires", std::to_string(std::chrono::duration_cast<std::chrono::seconds>(
(now + std::chrono::seconds(CCAPI_BITMEX_API_RECEIVE_WINDOW_SECONDS)).time_since_epoch())
.count()));
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("api-key", apiKey);
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,
{
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_ORDER_QUANTITY, "orderQty"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "clOrdID"},
});
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_);
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, "clOrdID"},
});
if (!queryString.empty()) {
queryString.pop_back();
}
req.target(this->cancelOrderTarget + "?" + queryString);
this->signRequest(req, "", 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();
if (!param.empty()) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param,
{
{CCAPI_EM_ORDER_ID, "orderID"},
{CCAPI_EM_CLIENT_ORDER_ID, "clOrdID"},
});
queryString += "filter=";
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
queryString += Url::urlEncode(stringBuffer.GetString());
queryString += "&";
}
if (!symbolId.empty()) {
this->appendSymbolId(queryString, symbolId);
}
if (!queryString.empty()) {
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("filter=");
queryString += Url::urlEncode("{\"open\": true}");
queryString += "&";
if (!symbolId.empty()) {
this->appendSymbolId(queryString, symbolId);
}
if (!queryString.empty()) {
queryString.pop_back();
}
req.target(this->getOrderTarget + "?" + queryString);
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->getAccountBalancesTarget;
auto asset = param.find(CCAPI_EM_ASSET) != param.end() ? param.at(CCAPI_EM_ASSET) : "";
target += "?currency=" + asset;
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();
auto target = this->getAccountPositionsTarget;
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("orderID", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdID", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("orderQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("ordStatus", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}};
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: {
Element element;
element.insert(CCAPI_EM_ACCOUNT_ID, document["account"].GetString());
element.insert(CCAPI_EM_ASSET, document["currency"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, document["availableMargin"].GetString());
elementList.emplace_back(std::move(element));
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
for (const auto& x : document.GetArray()) {
Element element;
element.insert(CCAPI_EM_ACCOUNT_ID, x["account"].GetString());
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
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_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("cumQty");
auto it2 = x.FindMember("avgPx");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))));
}
}
}
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("authKeyExpires").Move(), allocator);
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto expires =
std::chrono::duration_cast<std::chrono::seconds>((now + std::chrono::seconds(CCAPI_BITMEX_API_RECEIVE_WINDOW_SECONDS)).time_since_epoch()).count();
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string preSignedText = "GET";
preSignedText += "/realtime";
preSignedText += std::to_string(expires);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
rj::Value args(rj::kArrayType);
args.PushBack(rj::Value(apiKey.c_str(), allocator).Move(), allocator);
args.PushBack(rj::Value(expires).Move(), allocator);
args.PushBack(rj::Value(signature.c_str(), allocator).Move(), allocator);
document.AddMember("args", args, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
return sendStringList;
}
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
const TimePoint& timeReceived) override {
if (textMessage != "pong") {
Event event = this->createEvent(wsConnection.hdl, subscription, textMessage, document, timeReceived);
if (!event.getMessageList().empty()) {
this->eventHandler(event, nullptr);
}
}
}
Event createEvent(wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
const TimePoint& timeReceived) {
Event event;
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
if (document.FindMember("error") != document.MemberEnd()) {
auto it = document.FindMember("request");
if (it != document.MemberEnd()) {
if (std::string(it->value["op"].GetString()) == "authKeyExpires") {
event.setType(Event::Type::SUBSCRIPTION_STATUS);
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
}
}
} else {
if (document.FindMember("success") != document.MemberEnd()) {
auto it = document.FindMember("request");
if (it != document.MemberEnd()) {
if (std::string(it->value["op"].GetString()) == "authKeyExpires") {
event.setType(Event::Type::SUBSCRIPTION_STATUS);
message.setType(Message::Type::SUBSCRIPTION_STARTED);
Element element;
element.insert(CCAPI_INFO_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
rj::Value args(rj::kArrayType);
if (instrumentSet.empty()) {
for (const auto& field : fieldSet) {
if (field == CCAPI_EM_ORDER_UPDATE) {
args.PushBack(rj::Value("order").Move(), allocator);
} else if (field == CCAPI_EM_PRIVATE_TRADE) {
args.PushBack(rj::Value("execution").Move(), allocator);
}
}
} else {
for (const auto& instrument : instrumentSet) {
for (const auto& field : fieldSet) {
std::string arg;
if (field == CCAPI_EM_ORDER_UPDATE) {
arg = std::string("order:") + instrument;
} else if (field == CCAPI_EM_PRIVATE_TRADE) {
arg = std::string("execution:") + instrument;
}
args.PushBack(rj::Value(arg.c_str(), allocator).Move(), allocator);
}
}
}
document.AddMember("args", args, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<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 {
auto it = document.FindMember("table");
if (it != document.MemberEnd()) {
std::string table = it->value.GetString();
event.setType(Event::Type::SUBSCRIPTION_DATA);
auto it_2 = document.FindMember("action");
if (it_2 != document.MemberEnd()) {
std::string action = it_2->value.GetString();
if (action == "insert") {
for (const auto& x : document["data"].GetArray()) {
std::string instrument = std::string(x["symbol"].GetString());
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
message.setTime(UtilTime::parse(std::string(x["timestamp"].GetString())));
if (table == "execution" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
std::string execType = x["execType"].GetString();
if (execType == "Trade") {
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, std::string(x["trdMatchID"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["lastPx"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["lastQty"].GetString()));
element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "Buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_IS_MAKER, std::string(x["lastLiquidityInd"].GetString()) == "RemovedLiquidity" ? "0" : "1");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["orderID"].GetString()));
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdID"].GetString()));
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["commission"].GetString()));
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
} else if (table == "order" && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderID", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdID", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("orderQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("leavesQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("ordStatus", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
};
Element info;
this->extractOrderInfo(info, x, extractionFieldNameMap);
auto it = x.FindMember("avgPx");
if (it != x.MemberEnd() && !it->value.IsNull()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it->value.GetString()) * std::stod(x["cumQty"].GetString())));
}
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
}
}
}
}
}
event.setMessageList(messageList);
return event;
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITMEX_H_
@@ -0,0 +1,443 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITSTAMP_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITSTAMP_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_BITSTAMP
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
public:
ExecutionManagementServiceBitstamp(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITSTAMP;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_BITSTAMP_API_KEY;
this->apiSecretName = CCAPI_BITSTAMP_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
std::string prefix = "/api/v2";
this->createOrderTarget = prefix + "/{buy_or_sell}/{order_type}/{currency_pair}/";
this->cancelOrderTarget = prefix + "/cancel_order/";
this->getOrderTarget = prefix + "/order_status/";
this->getOpenOrdersTarget = prefix + "/open_orders/{currency_pair}/";
this->cancelOpenOrdersTarget = prefix + "/cancel_all_orders/{currency_pair}/";
this->getAccountBalancesTarget = prefix + "/balance/{currency_pair}/";
this->getWebSocketsTokenTarget = prefix + "/websockets_token/";
}
virtual ~ExecutionManagementServiceBitstamp() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
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 {
return body.find(R"("status": "error")") != std::string::npos || body.find(R"("status":"error")") != std::string::npos ||
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 {
if (!body.empty()) {
if (!headerString.empty()) {
headerString += "\r\n";
}
headerString += "Content-Type:application/x-www-form-urlencoded";
}
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string preSignedText = req.base().at("X-Auth").to_string();
preSignedText += methodString;
preSignedText += req.base().at(http::field::host).to_string();
preSignedText += req.target().to_string();
if (!body.empty()) {
preSignedText += "application/x-www-form-urlencoded";
}
preSignedText += req.base().at("X-Auth-Nonce").to_string();
preSignedText += req.base().at("X-Auth-Timestamp").to_string();
preSignedText += req.base().at("X-Auth-Version").to_string();
preSignedText += body;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
if (!headerString.empty()) {
headerString += "\r\n";
}
headerString += "X-Auth-Signature:" + signature;
}
void signRequest(http::request<http::string_body>& req, const std::string& body, const std::map<std::string, std::string>& credential) {
if (!body.empty()) {
req.set(beast::http::field::content_type, "application/x-www-form-urlencoded");
}
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string preSignedText = req.base().at("X-Auth").to_string();
preSignedText += std::string(req.method_string());
preSignedText += req.base().at(http::field::host).to_string();
preSignedText += req.target().to_string();
if (!body.empty()) {
preSignedText += req.base().at(beast::http::field::content_type).to_string();
}
preSignedText += req.base().at("X-Auth-Nonce").to_string();
preSignedText += req.base().at("X-Auth-Timestamp").to_string();
preSignedText += req.base().at("X-Auth-Version").to_string();
preSignedText += body;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
req.set("X-Auth-Signature", signature);
if (!body.empty()) {
req.body() = body;
req.prepare_payload();
}
}
void appendParam(std::string& body, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_EM_ORDER_QUANTITY, "amount"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "client_order_id"},
{CCAPI_EM_ORDER_ID, "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 != CCAPI_EM_ORDER_SIDE) {
body += Url::urlEncode(key);
body += "=";
body += Url::urlEncode(value);
body += "&";
}
}
}
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 {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("X-Auth", "BITSTAMP " + apiKey);
std::string nonce = UtilString::generateUuidV4();
req.set("X-Auth-Nonce", nonce);
req.set("X-Auth-Timestamp", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
req.set("X-Auth-Version", "v2");
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();
const std::string& orderSide = UtilString::toLower(param.at(CCAPI_EM_ORDER_SIDE));
std::string orderType;
if (param.find(CCAPI_EM_ORDER_TYPE) != param.end()) {
orderType = param.at(CCAPI_EM_ORDER_TYPE);
}
std::string target = this->createOrderTarget;
UtilString::replaceFirstOccurrence(target, "{buy_or_sell}", orderSide);
UtilString::replaceFirstOccurrence(target, "{order_type}", orderType);
UtilString::replaceFirstOccurrence(target, "{currency_pair}", symbolId);
UtilString::replaceFirstOccurrence(target, "//", "/");
req.target(target);
std::string body;
this->appendParam(body, param);
body.pop_back();
this->signRequest(req, body, credential);
} break;
case Request::Operation::CANCEL_ORDER: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->cancelOrderTarget);
std::string body;
this->appendParam(body, param);
body.pop_back();
this->signRequest(req, body, credential);
} break;
case Request::Operation::GET_ORDER: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->getOrderTarget);
std::string body;
this->appendParam(body, param);
body.pop_back();
this->signRequest(req, body, credential);
} break;
case Request::Operation::GET_OPEN_ORDERS: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
std::string target = this->getOpenOrdersTarget;
UtilString::replaceFirstOccurrence(target, "{currency_pair}", symbolId.empty() ? "all" : symbolId);
req.target(target);
this->signRequest(req, "", credential);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
std::string target = this->cancelOpenOrdersTarget;
UtilString::replaceFirstOccurrence(target, "{currency_pair}", symbolId);
UtilString::replaceFirstOccurrence(target, "//", "/");
req.target(target);
this->signRequest(req, "", credential);
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
std::string target = this->getAccountBalancesTarget;
UtilString::replaceFirstOccurrence(target, "{currency_pair}", symbolId);
UtilString::replaceFirstOccurrence(target, "//", "/");
req.target(target);
this->signRequest(req, "", credential);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("type");
if (it1 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_SIDE, std::string(it1->value.GetString()) == "0" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
}
}
}
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("id", JsonDataType::INTEGER)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::INTEGER)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("amount", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("amount_remaining", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("currency_pair", JsonDataType::STRING)},
};
if (operation == Request::Operation::CANCEL_OPEN_ORDERS) {
for (const auto& x : document["canceled"].GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
} else {
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: {
std::map<std::string, std::map<std::string, std::string>> balances;
for (auto itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr) {
const auto& splitted = UtilString::split(itr->name.GetString(), '_');
if (splitted.size() >= 2) {
const auto& type = splitted.at(1);
if (type == "available") {
balances[splitted.at(0)][CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING] = itr->value.GetString();
} else if (type == "balance") {
balances[splitted.at(0)][CCAPI_EM_QUANTITY_TOTAL] = itr->value.GetString();
}
}
}
for (const auto& kv1 : balances) {
Element element;
element.insert(CCAPI_EM_ASSET, UtilString::toUpper(kv1.first));
for (const auto& kv2 : kv1.second) {
element.insert(kv2.first, kv2.second);
}
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);
std::string target = this->getWebSocketsTokenTarget;
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-Auth", "BITSTAMP " + apiKey);
std::string nonce = UtilString::generateUuidV4();
req.set("X-Auth-Nonce", nonce);
req.set("X-Auth-Timestamp", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
req.set("X-Auth-Version", "v2");
std::string body;
this->signRequest(req, "", credential);
this->sendRequest(
req,
[wsConnection, that = shared_from_base<ExecutionManagementServiceBitstamp>()](const beast::error_code& ec) {
WsConnection thisWsConnection = wsConnection;
that->onFail_(thisWsConnection);
},
[wsConnection, that = shared_from_base<ExecutionManagementServiceBitstamp>()](const http::response<http::string_body>& res) {
WsConnection thisWsConnection = wsConnection;
int statusCode = res.result_int();
std::string body = res.body();
if (statusCode / 100 == 2) {
try {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
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;
that->connect(thisWsConnection);
that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({
{"token", token},
{"userId", userId},
});
}
return;
} catch (const std::runtime_error& e) {
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
}
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
std::vector<std::string> sendStringList;
for (const auto& field : fieldSet) {
for (const auto& instrument : instrumentSet) {
std::string name;
if (field == CCAPI_EM_ORDER_UPDATE) {
name = "private-my_orders_";
} else if (field == CCAPI_EM_PRIVATE_TRADE) {
name = "private-my_trades_";
}
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("bts:subscribe").Move(), allocator);
rj::Value data(rj::kObjectType);
data.AddMember("channel",
rj::Value((name + instrument + "-" + this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("userId")).c_str(), allocator).Move(),
allocator);
data.AddMember("auth", rj::Value(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("token").c_str(), allocator).Move(), allocator);
document.AddMember("data", data, 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 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 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("event")) {
std::string eventPayload = std::string(document["event"].GetString());
if (eventPayload == "order_created" || eventPayload == "order_changed" || eventPayload == "order_deleted") {
const rj::Value& data = document["data"];
std::string microtimestamp = data["microtimestamp"].GetString();
microtimestamp.insert(microtimestamp.size() - 6, ".");
message.setTime(UtilTime::makeTimePoint(UtilTime::divide(microtimestamp)));
std::string channel = std::string(document["channel"].GetString());
event.setType(Event::Type::SUBSCRIPTION_DATA);
std::string instrument = UtilString::split(channel.substr(std::string("private-my_orders_").length()), '-').at(0);
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
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("id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("amount", JsonDataType::STRING)},
};
Element info;
this->extractOrderInfo(info, data, extractionFieldNameMap);
info.insert(CCAPI_EM_ORDER_SIDE, std::string(data["order_type"].GetString()) == "0" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
info.insert(CCAPI_EM_ORDER_STATUS, eventPayload);
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 (eventPayload == "trade") {
const rj::Value& data = document["data"];
std::string microtimestamp = data["microtimestamp"].GetString();
microtimestamp.insert(microtimestamp.size() - 6, ".");
message.setTime(UtilTime::makeTimePoint(UtilTime::divide(microtimestamp)));
std::string channel = std::string(document["channel"].GetString());
event.setType(Event::Type::SUBSCRIPTION_DATA);
std::string instrument = UtilString::split(channel.substr(std::string("private-my_trades_").length()), '-').at(0);
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
Element info;
info.insert(CCAPI_TRADE_ID, data["id"].GetString());
info.insert(CCAPI_EM_ORDER_ID, data["order_id"].GetString());
{
auto it = data.FindMember("client_order_id");
if (it != data.MemberEnd()) {
info.insert(CCAPI_EM_CLIENT_ORDER_ID, it->value.GetString());
}
}
info.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, data["amount"].GetString());
info.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data["price"].GetString());
info.insert(CCAPI_EM_ORDER_FEE_QUANTITY, data["fee"].GetString());
info.insert(CCAPI_EM_ORDER_SIDE, std::string(data["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
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 (eventPayload == "bts:subscription_succeeded") {
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));
}
}
event.setMessageList(messageList);
return event;
}
std::string getWebSocketsTokenTarget;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BITSTAMP_H_
@@ -0,0 +1,412 @@
#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
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceBybit : public ExecutionManagementService {
public:
ExecutionManagementServiceBybit(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/ws";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
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";
}
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 = {}) {
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 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);
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;
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&";
}
}
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");
} 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(this->isDerivatives ? "cumQuote" : "cummulativeQuoteQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
};
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[this->isDerivatives ? "assets" : "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());
elementList.emplace_back(std::move(element));
}
} break;
default:
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 event;
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
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()));
}
}
{
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));
}
}
}
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_
@@ -0,0 +1,392 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_COINBASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_COINBASE_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_COINBASE
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceCoinbase : public ExecutionManagementService {
public:
ExecutionManagementServiceCoinbase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_COINBASE;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_COINBASE_API_KEY;
this->apiSecretName = CCAPI_COINBASE_API_SECRET;
this->apiPassphraseName = CCAPI_COINBASE_API_PASSPHRASE;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
this->createOrderTarget = "/orders";
this->cancelOrderTarget = "/orders/<id>";
this->getOrderTarget = "/orders/<id>";
this->getOpenOrdersTarget = "/orders";
this->cancelOpenOrdersTarget = "/orders";
this->getAccountsTarget = "/accounts";
this->getAccountBalancesTarget = "/accounts/<account-id>";
}
virtual ~ExecutionManagementServiceCoinbase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& req, const Request& request, std::string& methodString,
std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("CB-ACCESS-TIMESTAMP").to_string();
preSignedText += methodString;
std::string target = path;
if (!queryString.empty()) {
target += "?" + queryString;
}
preSignedText += target;
preSignedText += body;
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, UtilAlgorithm::base64Decode(apiSecret), preSignedText));
if (!headerString.empty()) {
headerString += "\r\n";
}
headerString += "CB-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("CB-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, UtilAlgorithm::base64Decode(apiSecret), preSignedText));
req.set("CB-ACCESS-SIGN", signature);
req.body() = body;
req.prepare_payload();
}
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, "client_oid"},
}) {
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";
}
document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
}
void appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
document.AddMember("product_id", rj::Value(symbolId.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 {
req.set(beast::http::field::content_type, "application/json");
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("CB-ACCESS-KEY", apiKey);
req.set("CB-ACCESS-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count()));
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
req.set("CB-ACCESS-PASSPHRASE", apiPassphrase);
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();
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() ? "client:" + param.at(CCAPI_EM_CLIENT_ORDER_ID)
: "";
auto target = std::regex_replace(this->cancelOrderTarget, std::regex("<id>"), id);
if (!symbolId.empty()) {
target += "?product_id=";
target += symbolId;
}
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();
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() ? "client:" + param.at(CCAPI_EM_CLIENT_ORDER_ID)
: "";
auto target = std::regex_replace(this->getOrderTarget, 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;
if (!symbolId.empty()) {
target += "?product_id=";
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 += "?product_id=";
target += symbolId;
}
req.target(target);
this->signRequest(req, "", credential);
} break;
case Request::Operation::GET_ACCOUNTS: {
req.method(http::verb::get);
req.target(this->getAccountsTarget);
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, {
{"<account-id>", 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("client_oid", 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("executed_value", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("product_id", JsonDataType::STRING)}};
if (operation == Request::Operation::CANCEL_ORDER) {
Element element;
element.insert(CCAPI_EM_ORDER_ID, document.GetString());
elementList.emplace_back(std::move(element));
} else if (operation == Request::Operation::CANCEL_OPEN_ORDERS) {
for (const auto& x : document.GetArray()) {
Element element;
element.insert(CCAPI_EM_ORDER_ID, x.GetString());
elementList.emplace_back(std::move(element));
}
} else {
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_ACCOUNTS: {
for (const auto& x : document.GetArray()) {
Element element;
element.insert(CCAPI_EM_ACCOUNT_ID, x["id"].GetString());
element.insert(CCAPI_EM_ASSET, x["currency"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["available"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
Element element;
element.insert(CCAPI_EM_ASSET, document["currency"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, document["available"].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 {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
auto timestamp = std::to_string(std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count());
auto preSignedText = timestamp;
preSignedText += "GET";
preSignedText += "/users/self/verify";
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, UtilAlgorithm::base64Decode(apiSecret), preSignedText));
std::vector<std::string> sendStringList;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("type", rj::Value("subscribe").Move(), allocator);
rj::Value channels(rj::kArrayType);
std::string channelId;
const auto& fieldSet = subscription.getFieldSet();
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
channelId = "full";
}
rj::Value channel(rj::kObjectType);
rj::Value symbolIds(rj::kArrayType);
const auto& instrumentSet = subscription.getInstrumentSet();
for (const auto& instrument : instrumentSet) {
const std::string& symbolId = instrument;
symbolIds.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
channel.AddMember("name", rj::Value(channelId.c_str(), allocator).Move(), allocator);
channel.AddMember("product_ids", symbolIds, allocator);
channels.PushBack(channel, allocator);
rj::Value heartbeatChannel(rj::kObjectType);
heartbeatChannel.AddMember("name", rj::Value("heartbeat").Move(), allocator);
rj::Value heartbeatSymbolIds(rj::kArrayType);
for (const auto& instrument : instrumentSet) {
const std::string& symbolId = instrument;
heartbeatSymbolIds.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
heartbeatChannel.AddMember("product_ids", heartbeatSymbolIds, allocator);
channels.PushBack(heartbeatChannel, allocator);
document.AddMember("channels", channels, allocator);
document.AddMember("signature", rj::Value(signature.c_str(), allocator).Move(), allocator);
document.AddMember("key", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
document.AddMember("passphrase", rj::Value(apiPassphrase.c_str(), allocator).Move(), allocator);
document.AddMember("timestamp", rj::Value(timestamp.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(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 event;
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
std::string type = document["type"].GetString();
if (this->websocketFullChannelTypeSet.find(type) != websocketFullChannelTypeSet.end()) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
if (document.FindMember("user_id") != document.MemberEnd()) {
std::string instrument = document["product_id"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
auto it = document.FindMember("time");
if (it != document.MemberEnd()) {
message.setTime(UtilTime::parse(std::string(it->value.GetString())));
} else {
auto it = document.FindMember("timestamp");
message.setTime(UtilTime::makeTimePoint(UtilTime::divide(std::string(it->value.GetString()))));
}
if (type == "match" && 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(document["trade_id"].GetString()));
std::string priceStr = document["price"].GetString();
std::string sizeStr = document["size"].GetString();
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, priceStr);
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, sizeStr);
std::string makerSide = document["side"].GetString();
if (document.FindMember("taker_user_id") != document.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_SIDE, makerSide == "buy" ? CCAPI_EM_ORDER_SIDE_SELL : CCAPI_EM_ORDER_SIDE_BUY);
element.insert(CCAPI_IS_MAKER, "0");
element.insert(CCAPI_EM_ORDER_ID, document["taker_order_id"].GetString());
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY,
UtilString::printDoubleScientific(std::stod(priceStr) * std::stod(sizeStr) * std::stod(document["taker_fee_rate"].GetString())));
} else if (document.FindMember("maker_user_id") != document.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_SIDE, makerSide == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_IS_MAKER, "1");
element.insert(CCAPI_EM_ORDER_ID, document["maker_order_id"].GetString());
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY,
UtilString::printDoubleScientific(std::stod(priceStr) * std::stod(sizeStr) * std::stod(document["maker_fee_rate"].GetString())));
}
element.insert(CCAPI_EM_ORDER_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.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("order_id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_oid", 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_REMAINING_QUANTITY, std::make_pair("remaining_size", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("type", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("product_id", JsonDataType::STRING)},
};
if (type == "change") {
extractionFieldNameMap.insert({CCAPI_EM_ORDER_QUANTITY, std::make_pair("new_size", JsonDataType::STRING)});
} else {
extractionFieldNameMap.insert({CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)});
}
Element info;
this->extractOrderInfo(info, document, extractionFieldNameMap);
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
} else if (type == "subscriptions") {
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));
}
event.setMessageList(messageList);
return event;
}
std::string apiPassphraseName;
std::set<std::string> websocketFullChannelTypeSet{"received", "open", "done", "match", "change", "activate"};
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_COINBASE_H_
@@ -0,0 +1,542 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_CRYPTOCOM_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_CRYPTOCOM_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_CRYPTOCOM
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
public:
ExecutionManagementServiceCryptocom(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_CRYPTOCOM;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/user";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_CRYPTOCOM_API_KEY;
this->apiSecretName = CCAPI_CRYPTOCOM_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->pathPrefix = "/v2/";
this->createOrderMethod = "private/create-order";
this->cancelOrderMethod = "private/cancel-order";
this->getOrderMethod = "private/get-order-detail";
this->getOpenOrdersMethod = "private/get-open-orders";
this->cancelOpenOrdersMethod = "private/cancel-all-orders";
this->getAccountBalancesMethod = "private/get-account-summary";
}
virtual ~ExecutionManagementServiceCryptocom() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& req, const Request& request, std::string& httpMethodString,
std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
req.set(beast::http::field::content_type, "application/json");
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
document.AddMember("api_key", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
std::string paramString;
auto itParams = document.FindMember("params");
if (itParams != document.MemberEnd()) {
const rj::Value& params = itParams->value;
std::map<std::string, std::string> sortedParams;
for (auto itr = params.MemberBegin(); itr != params.MemberEnd(); ++itr) {
sortedParams.insert({itr->name.GetString(), itr->value.GetString()});
}
for (const auto& x : sortedParams) {
paramString += x.first;
paramString += x.second;
}
}
std::string appMethod = document["method"].GetString();
std::string preSignedText(appMethod);
auto itId = document.FindMember("id");
if (itId != document.MemberEnd()) {
preSignedText += itId->value.GetString();
}
preSignedText += apiKey;
preSignedText += document["nonce"].GetString();
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
document.AddMember("sig", rj::Value(signature.c_str(), allocator).Move(), allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
body = stringBuffer.GetString();
}
void signRequest(http::request<http::string_body>& req, rj::Document& document, rj::Document::AllocatorType& allocator, int64_t requestId,
const std::string& appMethod, const std::map<std::string, std::string>& param, const TimePoint& now,
const std::map<std::string, std::string>& credential) {
std::string body;
this->signRequest(body, document, allocator, requestId, appMethod, param, now, credential);
req.body() = body;
req.prepare_payload();
req.target(this->pathPrefix + appMethod);
}
void signRequest(std::string& body, rj::Document& document, rj::Document::AllocatorType& allocator, int64_t requestId, const std::string& appMethod,
const std::map<std::string, std::string>& param, const TimePoint& now, const std::map<std::string, std::string>& credential) {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
document.AddMember("api_key", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
int64_t nonce = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
document.AddMember("nonce", rj::Value(nonce).Move(), allocator);
std::string paramsString;
for (const auto& kv : param) {
paramsString += kv.first;
paramsString += kv.second;
}
std::string preSignedText(appMethod);
preSignedText += std::to_string(requestId);
preSignedText += apiKey;
preSignedText += paramsString;
preSignedText += std::to_string(nonce);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
document.AddMember("sig", rj::Value(signature.c_str(), allocator).Move(), allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
body = stringBuffer.GetString();
}
void appendParam(rj::Document& document, rj::Document::AllocatorType& allocator, int64_t requestId, const std::string& appMethod,
const std::map<std::string, std::string>& param) {
document.AddMember("id", rj::Value(requestId).Move(), allocator);
document.AddMember("method", rj::Value(appMethod.c_str(), allocator).Move(), allocator);
rj::Value params(rj::kObjectType);
for (const auto& kv : param) {
auto key = kv.first;
auto value = kv.second;
if (value != "null") {
if (value == "true" || value == "false") {
params.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator);
} else {
params.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
}
}
document.AddMember("params", params, allocator);
}
void prepareReq(http::request<http::string_body>& req, const std::map<std::string, std::string>& param, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential, const std::string& appMethod,
const std::map<std::string, std::string> standardizationMap = {}) {
req.set(beast::http::field::content_type, "application/json");
req.method(http::verb::post);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
std::map<std::string, std::string> paramCopy;
for (const auto& kv : param) {
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
auto value = kv.second;
paramCopy.insert({key, value});
}
if (appMethod == this->createOrderMethod) {
if (paramCopy.find("type") == paramCopy.end()) {
paramCopy.insert({"type", "LIMIT"});
}
}
if (!symbolId.empty()) {
paramCopy.insert({"instrument_name", symbolId});
}
int64_t requestId = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
this->appendParam(document, allocator, requestId, appMethod, paramCopy);
this->signRequest(req, document, allocator, requestId, appMethod, paramCopy, now, credential);
}
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_PRIVATE_REQUEST: {
ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential);
} break;
case Request::Operation::CREATE_ORDER: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->prepareReq(req, param, now, symbolId, credential, this->createOrderMethod,
{
{CCAPI_EM_CLIENT_ORDER_ID, "client_oid"},
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_ORDER_QUANTITY, "quantity"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
});
} break;
case Request::Operation::CANCEL_ORDER: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->prepareReq(req, param, now, symbolId, credential, this->cancelOrderMethod,
{
{CCAPI_EM_ORDER_ID, "order_id"},
});
} break;
case Request::Operation::GET_ORDER: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->prepareReq(req, param, now, symbolId, credential, this->getOrderMethod,
{
{CCAPI_EM_ORDER_ID, "order_id"},
});
} break;
case Request::Operation::GET_OPEN_ORDERS: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->prepareReq(req, param, now, symbolId, credential, this->getOpenOrdersMethod);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->prepareReq(req, param, now, symbolId, credential, this->cancelOpenOrdersMethod);
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->prepareReq(req, param, now, symbolId, credential, this->getAccountBalancesMethod,
{
{CCAPI_EM_ASSET, "currency"},
});
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void convertRequestForWebsocket(rj::Document& document, rj::Document::AllocatorType& allocator, const WsConnection& wsConnection, const Request& request,
int wsRequestId, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
switch (request.getOperation()) {
case Request::Operation::CREATE_ORDER: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
std::map<std::string, std::string> paramCopy;
std::map<std::string, std::string> standardizationMap = {
{CCAPI_EM_CLIENT_ORDER_ID, "client_oid"},
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_ORDER_QUANTITY, "quantity"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
};
for (const auto& kv : param) {
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
auto value = kv.second;
paramCopy.insert({key, value});
}
if (paramCopy.find("type") == paramCopy.end()) {
paramCopy.insert({"type", "LIMIT"});
}
if (!symbolId.empty()) {
paramCopy.insert({"instrument_name", symbolId});
}
this->appendParam(document, allocator, wsRequestId, this->createOrderMethod, paramCopy);
int64_t nonce = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
document.AddMember("nonce", rj::Value(nonce).Move(), allocator);
} break;
case Request::Operation::CANCEL_ORDER: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
std::map<std::string, std::string> paramCopy;
std::map<std::string, std::string> standardizationMap = {
{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;
paramCopy.insert({key, value});
}
if (!symbolId.empty()) {
paramCopy.insert({"instrument_name", symbolId});
}
this->appendParam(document, allocator, wsRequestId, this->cancelOrderMethod, paramCopy);
int64_t nonce = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
document.AddMember("nonce", rj::Value(nonce).Move(), allocator);
} break;
default:
this->convertRequestForWebsocketCustom(document, allocator, wsConnection, request, wsRequestId, now, symbolId, credential);
}
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
this->extractOrderInfoFromRequest(elementList, operation, document);
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request::Operation operation, const rj::Document& document) {
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_oid", 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("cumulative_quantity", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cumulative_value", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("instrument_name", JsonDataType::STRING)},
};
if (operation == Request::Operation::CREATE_ORDER) {
Element element;
this->extractOrderInfo(element, document["result"], extractionFieldNameMap);
elementList.emplace_back(std::move(element));
} else if (operation == Request::Operation::GET_ORDER) {
Element element;
this->extractOrderInfo(element, document["result"]["order_info"], extractionFieldNameMap);
elementList.emplace_back(std::move(element));
} else if (operation == Request::Operation::GET_OPEN_ORDERS) {
for (const auto& x : document["result"]["order_list"].GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
} else if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
Element element;
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: {
Element element;
for (const auto& x : document["result"]["accounts"].GetArray()) {
if (std::string(x["balance"].GetString()) == "0") {
continue;
}
element.insert(CCAPI_EM_ASSET, x["currency"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["available"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["balance"].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::vector<std::string> sendStringList;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
int64_t requestId = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
std::string appMethod = "public/auth";
std::map<std::string, std::string> param;
this->appendParam(document, allocator, requestId, appMethod, param);
std::string body;
this->signRequest(body, document, allocator, requestId, appMethod, param, now, credential);
sendStringList.push_back(body);
return sendStringList;
}
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
const TimePoint& timeReceived) override {
Event event = this->createEvent(wsConnection, subscription, textMessage, document, timeReceived);
if (!event.getMessageList().empty()) {
this->eventHandler(event, nullptr);
}
}
Event createEvent(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
const TimePoint& timeReceived) {
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();
std::string method = document["method"].GetString();
auto itCode = document.FindMember("code");
auto itResult = document.FindMember("result");
if (method == "subscribe") {
if (itResult == document.MemberEnd()) {
if (itCode != document.MemberEnd()) {
std::string code = itCode->value.GetString();
if (code != "0") {
event.setType(Event::Type::SUBSCRIPTION_STATUS);
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
} else {
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 {
const rj::Value& result = itResult->value;
std::string exchangeSubscriptionId = result["subscription"].GetString();
std::smatch match;
std::string instrument;
std::string field;
if (std::regex_search(exchangeSubscriptionId, match, std::regex("user\\.order\\.(.+)"))) {
instrument = match[1].str();
field = CCAPI_EM_ORDER_UPDATE;
} else if (std::regex_search(exchangeSubscriptionId, match, std::regex("user\\.trade\\.(.+)"))) {
instrument = match[1].str();
field = CCAPI_EM_PRIVATE_TRADE;
}
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
if (field == CCAPI_EM_PRIVATE_TRADE && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
for (const auto& x : result["data"].GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["create_time"].GetString()))));
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, std::string(x["trade_id"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["traded_price"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["traded_quantity"].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["liquidity_indicator"].GetString()) == "MAKER" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["order_id"].GetString()));
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fee"].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 && 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("order_id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_oid", 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("cumulative_quantity", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cumulative_value", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("instrument_name", JsonDataType::STRING)},
};
for (const auto& x : result["data"].GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["update_time"].GetString()))));
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 (method == "private/create-order" || method == "private/cancel-order") {
if (itCode != document.MemberEnd()) {
event.setType(Event::Type::RESPONSE);
std::string code = itCode->value.GetString();
if (code != "0") {
message.setType(Message::Type::RESPONSE_ERROR);
Element element;
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
} else {
std::vector<Element> elementList;
Request::Operation operation;
if (method == "private/create-order") {
message.setType(Message::Type::CREATE_ORDER);
operation = Request::Operation::CREATE_ORDER;
} else if (method == "private/cancel-order") {
message.setType(Message::Type::CANCEL_ORDER);
operation = Request::Operation::CANCEL_ORDER;
}
this->extractOrderInfoFromRequest(elementList, operation, document);
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
} 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");
}
}
} else if (method == "public/auth") {
if (itCode != document.MemberEnd()) {
std::string code = itCode->value.GetString();
if (code != "0") {
event.setType(Event::Type::AUTHORIZATION_STATUS);
message.setType(Message::Type::AUTHORIZATION_FAILURE);
Element element;
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
} else {
event.setType(Event::Type::AUTHORIZATION_STATUS);
message.setType(Message::Type::AUTHORIZATION_SUCCESS);
Element element;
element.insert(CCAPI_INFO_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
int64_t requestId = std::chrono::duration_cast<std::chrono::nanoseconds>(timeReceived.time_since_epoch()).count();
document.AddMember("id", rj::Value(requestId).Move(), allocator);
document.AddMember("method", rj::Value("subscribe").Move(), allocator);
rj::Value channels(rj::kArrayType);
if (instrumentSet.empty()) {
for (const auto& field : fieldSet) {
std::string exchangeSubscriptionId;
if (field == CCAPI_EM_ORDER_UPDATE) {
exchangeSubscriptionId = "user.order.";
} else if (field == CCAPI_EM_PRIVATE_TRADE) {
exchangeSubscriptionId = "user.trade.";
}
channels.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
}
} else {
for (const auto& instrument : instrumentSet) {
for (const auto& field : fieldSet) {
std::string exchangeSubscriptionId;
if (field == CCAPI_EM_ORDER_UPDATE) {
exchangeSubscriptionId = "user.order." + instrument;
} else if (field == CCAPI_EM_PRIVATE_TRADE) {
exchangeSubscriptionId = "user.trade." + instrument;
}
channels.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
}
}
}
rj::Value params(rj::kObjectType);
params.AddMember("channels", channels, allocator);
document.AddMember("params", params, allocator);
int64_t nonce = std::chrono::duration_cast<std::chrono::milliseconds>(timeReceived.time_since_epoch()).count();
document.AddMember("nonce", rj::Value(nonce).Move(), allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.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");
}
}
}
}
event.setMessageList(messageList);
return event;
}
std::string pathPrefix;
std::string createOrderMethod;
std::string cancelOrderMethod;
std::string getOrderMethod;
std::string getOpenOrdersMethod;
std::string cancelOpenOrdersMethod;
std::string getAccountBalancesMethod;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_CRYPTOCOM_H_
@@ -0,0 +1,516 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_DERIBIT_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_DERIBIT_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceDeribit : public ExecutionManagementService {
public:
ExecutionManagementServiceDeribit(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_DERIBIT;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/api/v2";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->clientIdName = CCAPI_DERIBIT_CLIENT_ID;
this->clientSecretName = CCAPI_DERIBIT_CLIENT_SECRET;
this->setupCredential({this->clientIdName, this->clientSecretName});
this->restTarget = "/api/v2";
this->createOrderBuyTarget = "/private/buy";
this->createOrderSellTarget = "/private/sell";
this->cancelOrderTarget = "/private/cancel";
this->getOrderTarget = "/private/get_order_state";
this->getOpenOrdersTarget = "/private/get_open_orders_by_instrument";
this->cancelOpenOrdersTarget = "/private/cancel_all_by_instrument";
this->getAccountBalancesTarget = "/private/get_account_summary";
this->getAccountPositionsTarget = "/private/get_positions";
}
virtual ~ExecutionManagementServiceDeribit() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
void onOpen(wspp::connection_hdl hdl) override {
ExecutionManagementService::onOpen(hdl);
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
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/set_heartbeat",
{
{"interval", "10"},
});
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string msg = stringBuffer.GetString();
ErrorCode ec;
this->send(hdl, msg, wspp::frame::opcode::text, ec);
if (ec) {
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request");
}
}
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& req, const Request& request, std::string& httpMethodString,
std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
std::string authorizationHeader("deri-hmac-sha256 id=");
authorizationHeader += mapGetWithDefault(credential, this->clientIdName);
authorizationHeader += ",ts=";
std::string ts = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count());
authorizationHeader += ts;
authorizationHeader += ",sig=";
std::string nonce = ts;
auto requestData = httpMethodString;
requestData += "\n";
std::string target = path;
if (!queryString.empty()) {
target += "?" + queryString;
}
requestData += target;
requestData += "\n";
requestData += body;
requestData += "\n";
std::string stringToSign = ts;
stringToSign += "\n";
stringToSign += nonce;
stringToSign += "\n";
stringToSign += requestData;
auto clientSecret = mapGetWithDefault(credential, this->clientSecretName);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, clientSecret, stringToSign, true);
authorizationHeader += signature;
authorizationHeader += ",nonce=";
authorizationHeader += nonce;
headerString += "\r\nAuthorization:" + authorizationHeader;
}
void signRequest(http::request<http::string_body>& req, const std::string& body, const TimePoint& now, const std::map<std::string, std::string>& credential) {
std::string authorizationHeader("deri-hmac-sha256 id=");
authorizationHeader += mapGetWithDefault(credential, this->clientIdName);
authorizationHeader += ",ts=";
std::string ts = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count());
authorizationHeader += ts;
authorizationHeader += ",sig=";
std::string nonce = ts;
auto requestData = std::string(req.method_string());
requestData += "\n";
requestData += req.target().to_string();
requestData += "\n";
requestData += body;
requestData += "\n";
std::string stringToSign = ts;
stringToSign += "\n";
stringToSign += nonce;
stringToSign += "\n";
stringToSign += requestData;
auto clientSecret = mapGetWithDefault(credential, this->clientSecretName);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, clientSecret, stringToSign, true);
authorizationHeader += signature;
authorizationHeader += ",nonce=";
authorizationHeader += nonce;
req.set(http::field::authorization, authorizationHeader);
}
void appendParam(rj::Document& document, rj::Document::AllocatorType& allocator, int64_t requestId, const std::string& appMethod,
const std::map<std::string, std::string>& param, const std::map<std::string, std::string> standardizationMap = {}) {
document.AddMember("jsonrpc", rj::Value("2.0").Move(), allocator);
document.AddMember("id", rj::Value(requestId).Move(), allocator);
document.AddMember("method", rj::Value(appMethod.c_str(), allocator).Move(), allocator);
rj::Value params(rj::kObjectType);
for (const auto& kv : param) {
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
if (key != CCAPI_EM_ORDER_SIDE) {
auto value = kv.second;
if (value != "null") {
if (value == "true" || value == "false") {
params.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator);
} else {
params.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
}
}
}
document.AddMember("params", params, allocator);
}
void appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
document["params"].AddMember("instrument_name", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
void prepareReq(http::request<http::string_body>& req, const std::map<std::string, std::string>& param, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential, const std::string& jsonrpcMethod,
const std::map<std::string, std::string> standardizationMap = {}) {
int64_t requestId = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
req.set(beast::http::field::content_type, "application/json");
req.method(http::verb::post);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, requestId, jsonrpcMethod, param, standardizationMap);
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();
req.target(this->restTarget);
this->signRequest(req, body, now, credential);
}
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_PRIVATE_REQUEST: {
ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential);
} break;
case Request::Operation::CREATE_ORDER: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
std::string side = mapGetWithDefault(param, std::string(CCAPI_EM_ORDER_SIDE));
std::string jsonrpcMethod;
if (side == CCAPI_EM_ORDER_SIDE_BUY) {
jsonrpcMethod = this->createOrderBuyTarget;
} else if (side == CCAPI_EM_ORDER_SIDE_SELL) {
jsonrpcMethod = this->createOrderSellTarget;
}
this->prepareReq(req, param, now, symbolId, credential, jsonrpcMethod,
{
{CCAPI_EM_ORDER_QUANTITY, "amount"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
});
} break;
case Request::Operation::CANCEL_ORDER: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->prepareReq(req, param, now, symbolId, credential, this->cancelOrderTarget,
{
{CCAPI_EM_ORDER_ID, "order_id"},
});
} break;
case Request::Operation::GET_ORDER: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->prepareReq(req, param, now, symbolId, credential, this->getOrderTarget,
{
{CCAPI_EM_ORDER_ID, "order_id"},
});
} break;
case Request::Operation::GET_OPEN_ORDERS: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->prepareReq(req, param, now, symbolId, credential, this->getOpenOrdersTarget);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->prepareReq(req, param, now, symbolId, credential, this->cancelOpenOrdersTarget);
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->prepareReq(req, param, now, symbolId, credential, this->getAccountBalancesTarget,
{
{CCAPI_EM_ASSET, "currency"},
});
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->prepareReq(req, param, now, symbolId, credential, this->getAccountPositionsTarget,
{
{CCAPI_EM_ASSET, "currency"},
});
} 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_ORDER_SIDE, std::make_pair("direction", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("amount", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filled_amount", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("order_state", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("instrument_name", JsonDataType::STRING)}};
if (operation == Request::Operation::CREATE_ORDER) {
Element element;
this->extractOrderInfo(element, document["result"]["order"], extractionFieldNameMap);
elementList.emplace_back(std::move(element));
} else if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::GET_ORDER) {
Element element;
this->extractOrderInfo(element, document["result"], extractionFieldNameMap);
elementList.emplace_back(std::move(element));
} else if (operation == Request::Operation::GET_OPEN_ORDERS) {
for (const auto& x : document["result"].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: {
Element element;
const rj::Value& result = document["result"];
element.insert(CCAPI_EM_ASSET, result["currency"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, result["margin_balance"].GetString());
elementList.emplace_back(std::move(element));
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
for (const auto& x : document["result"].GetArray()) {
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_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("filled_amount");
auto it2 = x.FindMember("average_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))));
}
}
}
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();
rj::Document::AllocatorType& allocator = document.GetAllocator();
int64_t requestId = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
std::string clientId = mapGetWithDefault(credential, this->clientIdName);
std::string ts = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count());
std::string nonce = ts;
std::string stringToSign = ts + "\n" + nonce + "\n";
auto clientSecret = mapGetWithDefault(credential, this->clientSecretName);
std::string signature = Hmac::hmac(Hmac::ShaVersion::SHA256, clientSecret, stringToSign, true);
this->appendParam(document, allocator, requestId, "public/auth",
{
{"grant_type", "client_signature"},
{"client_id", clientId},
{"timestamp", ts},
{"signature", signature},
{"nonce", nonce},
});
this->authorizationJsonrpcIdSetByConnectionIdMap[wsConnection.id].insert(requestId);
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 rj::Document& document,
const TimePoint& timeReceived) override {
Event event = this->createEvent(wsConnection, subscription, textMessage, document, timeReceived);
if (!event.getMessageList().empty()) {
this->eventHandler(event, nullptr);
}
}
Event createEvent(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
const TimePoint& timeReceived) {
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();
auto it = document.FindMember("id");
if (document.FindMember("error") != document.MemberEnd()) {
const rj::Value& error = document["error"];
if (error.FindMember("code") != error.MemberEnd() && std::string(error["code"].GetString()) != "0") {
int64_t requestId = std::stoll(it->value.GetString());
if (this->authorizationJsonrpcIdSetByConnectionIdMap.at(wsConnection.id).find(requestId) !=
this->authorizationJsonrpcIdSetByConnectionIdMap.at(wsConnection.id).end()) {
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));
if (it != document.MemberEnd()) {
this->authorizationJsonrpcIdSetByConnectionIdMap.at(wsConnection.id).erase(std::stoll(it->value.GetString()));
}
}
}
} else {
auto itResult = document.FindMember("result");
if (itResult != document.MemberEnd()) {
int64_t requestId = std::stoll(it->value.GetString());
if (itResult->value.IsObject()) {
if (this->authorizationJsonrpcIdSetByConnectionIdMap.at(wsConnection.id).find(requestId) !=
this->authorizationJsonrpcIdSetByConnectionIdMap.at(wsConnection.id).end()) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("jsonrpc", rj::Value("2.0").Move(), allocator);
document.AddMember("method", rj::Value("private/subscribe").Move(), allocator);
int64_t requestId = std::chrono::duration_cast<std::chrono::nanoseconds>(timeReceived.time_since_epoch()).count();
document.AddMember("id", rj::Value(requestId).Move(), allocator);
this->subscriptionJsonrpcIdSetByConnectionIdMap[wsConnection.id].insert(requestId);
rj::Value channels(rj::kArrayType);
for (const auto& instrument : instrumentSet) {
for (const auto& field : fieldSet) {
std::string exchangeSubscriptionId;
if (field == CCAPI_EM_ORDER_UPDATE) {
exchangeSubscriptionId = "user.orders." + instrument + ".raw";
} else if (field == CCAPI_EM_PRIVATE_TRADE) {
exchangeSubscriptionId = "user.trades." + instrument + ".raw";
}
channels.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
}
}
rj::Value params(rj::kObjectType);
params.AddMember("channels", channels, allocator);
document.AddMember("params", params, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.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");
}
if (it != document.MemberEnd()) {
this->authorizationJsonrpcIdSetByConnectionIdMap.at(wsConnection.id).erase(std::stoll(it->value.GetString()));
}
}
} else if (itResult->value.IsArray()) {
if (this->subscriptionJsonrpcIdSetByConnectionIdMap.at(wsConnection.id).find(requestId) !=
this->subscriptionJsonrpcIdSetByConnectionIdMap.at(wsConnection.id).end()) {
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));
if (it != document.MemberEnd()) {
this->subscriptionJsonrpcIdSetByConnectionIdMap.at(wsConnection.id).erase(std::stoll(it->value.GetString()));
}
}
}
} else if (document.FindMember("method") != document.MemberEnd()) {
std::string method = document["method"].GetString();
if (method == "subscription") {
const rj::Value& params = document["params"];
std::string exchangeSubscriptionId = params["channel"].GetString();
std::smatch match;
std::string instrument;
std::string field;
if (std::regex_search(exchangeSubscriptionId, match, std::regex("user\\.orders\\.(.+)\\.raw"))) {
instrument = match[1].str();
field = CCAPI_EM_ORDER_UPDATE;
} else if (std::regex_search(exchangeSubscriptionId, match, std::regex("user\\.trades\\.(.+)\\.raw"))) {
instrument = match[1].str();
field = CCAPI_EM_PRIVATE_TRADE;
}
if (instrumentSet.find(instrument) != instrumentSet.end()) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
if (field == CCAPI_EM_PRIVATE_TRADE && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
for (const auto& x : params["data"].GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["timestamp"].GetString()))));
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, std::string(x["trade_id"].GetString()));
element.insert(CCAPI_SEQUENCE_NUMBER, std::string(x["trade_seq"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["price"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["amount"].GetString()));
element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["direction"].GetString()) == "Buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_IS_MAKER, std::string(x["liquidity"].GetString()) == "M" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["order_id"].GetString()));
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fee"].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 && 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("order_id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("direction", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("amount", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filled_amount", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("order_state", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
};
const rj::Value& x = params["data"];
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["last_update_timestamp"].GetString()))));
Element info;
this->extractOrderInfo(info, x, extractionFieldNameMap);
auto it1 = x.FindMember("filled_amount");
auto it2 = x.FindMember("average_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))));
}
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
} else if (method == "heartbeat") {
std::string type = document["params"]["type"].GetString();
if (type == "test_request") {
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/test", {});
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string msg = stringBuffer.GetString();
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");
}
}
}
}
}
event.setMessageList(messageList);
return event;
}
void onClose(wspp::connection_hdl hdl) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
this->subscriptionJsonrpcIdSetByConnectionIdMap.erase(wsConnection.id);
this->authorizationJsonrpcIdSetByConnectionIdMap.erase(wsConnection.id);
ExecutionManagementService::onClose(hdl);
}
std::map<std::string, std::set<int64_t>> subscriptionJsonrpcIdSetByConnectionIdMap;
std::map<std::string, std::set<int64_t>> authorizationJsonrpcIdSetByConnectionIdMap;
std::string restTarget;
std::string clientIdName;
std::string clientSecretName;
std::string createOrderBuyTarget;
std::string createOrderSellTarget;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_DERIBIT_H_
@@ -0,0 +1,230 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_ERISX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_ERISX_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_ERISX
#include "ccapi_cpp/ccapi_jwt.h"
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceErisx : public ExecutionManagementService {
public:
ExecutionManagementServiceErisx(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_ERISX;
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_ERISX_API_KEY;
this->apiSecretName = CCAPI_ERISX_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
std::string prefix = "/rest-api";
this->createOrderTarget = prefix + "/new-order-single";
this->cancelOrderTarget = prefix + "/cancel-order-single";
this->getOrderTarget = prefix + "/order/{partyID}/{orderID}";
this->getOpenOrdersTarget = prefix + "/order-mass-status";
this->cancelOpenOrdersTarget = prefix + "/cancel-all";
}
virtual ~ExecutionManagementServiceErisx() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
bool doesHttpBodyContainError(const Request& request, 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;
}
void signRequest(http::request<http::string_body>& req, const TimePoint& now, const std::map<std::string, std::string>& credential) {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
rj::Document tokenPayloadDocument;
tokenPayloadDocument.SetObject();
rj::Document::AllocatorType& tokenPayloadAllocator = tokenPayloadDocument.GetAllocator();
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
tokenPayloadDocument.AddMember("sub", rj::Value(apiKey.c_str(), tokenPayloadAllocator).Move(), tokenPayloadAllocator);
tokenPayloadDocument.AddMember("iat", rj::Value(UtilTime::getUnixTimestamp(now)).Move(), tokenPayloadAllocator);
rj::StringBuffer tokenPayloadStringBuffer;
rj::Writer<rj::StringBuffer> tokenPayloadWriter(tokenPayloadStringBuffer);
tokenPayloadDocument.Accept(tokenPayloadWriter);
auto token = Jwt::generate(Hmac::ShaVersion::SHA256, apiSecret, tokenPayloadStringBuffer.GetString());
req.set("Authorization", "Bearer " + token);
}
void setBody(http::request<http::string_body>& req, rj::Document& document, rj::Document::AllocatorType& allocator,
const std::map<std::string, std::string>& param, const TimePoint& now) {
if (param.find("transactionTime") == param.end()) {
document.AddMember("transactionTime", rj::Value(UtilTime::convertTimePointToFIXTime(now).c_str(), allocator).Move(), allocator);
}
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
req.body() = stringBuffer.GetString();
req.prepare_payload();
}
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 = {}) {
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";
}
document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
}
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 substituteParam(std::string& target, const std::map<std::string, std::string>& param, const std::map<std::string, std::string> standardizationMap = {}) {
for (const auto& kv : param) {
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
auto value = kv.second;
target = target.replace(target.find(key), key.length(), value);
}
}
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");
switch (request.getOperation()) {
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,
{
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_ORDER_QUANTITY, "orderQty"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "clOrdID"},
{CCAPI_EM_PARTY_ID, "partyID"},
});
this->appendSymbolId(document, allocator, symbolId);
if (param.find("ordType") == param.end()) {
document.AddMember("ordType", rj::Value("LIMIT").Move(), allocator);
}
if (param.find("currency") == param.end()) {
if (symbolId.find("/") != std::string::npos) {
document.AddMember("currency", rj::Value(UtilString::split(symbolId, "/").at(0).c_str(), allocator).Move(), allocator);
}
}
this->setBody(req, document, allocator, param, now);
this->signRequest(req, now, credential);
} break;
case Request::Operation::CANCEL_ORDER: {
req.method(http::verb::post);
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,
{
{CCAPI_EM_ORDER_ID, "orderID"},
{CCAPI_EM_ORIGINAL_CLIENT_ORDER_ID, "origClOrdID"},
{CCAPI_EM_CLIENT_ORDER_ID, "clOrdID"},
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_PARTY_ID, "partyID"},
});
if (param.find("ordType") == param.end()) {
document.AddMember("ordType", rj::Value("LIMIT").Move(), allocator);
}
this->appendSymbolId(document, allocator, symbolId);
this->setBody(req, document, allocator, param, now);
this->signRequest(req, now, credential);
} break;
case Request::Operation::GET_ORDER: {
req.method(http::verb::get);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
std::string target = this->getOrderTarget;
this->substituteParam(target, param,
{
{CCAPI_EM_ORDER_ID, "{orderID}"},
{CCAPI_EM_PARTY_ID, "{partyID}"},
});
req.target(target);
this->signRequest(req, now, credential);
} break;
case Request::Operation::GET_OPEN_ORDERS: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->getOpenOrdersTarget);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param,
{
{CCAPI_EM_PARTY_ID, "partyID"},
});
this->setBody(req, document, allocator, param, now);
this->signRequest(req, now, credential);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
req.method(http::verb::post);
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,
{
{CCAPI_EM_PARTY_ID, "partyID"},
});
this->setBody(req, document, allocator, param, now);
this->signRequest(req, 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 {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderID", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdID", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("orderQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("ordStatus", JsonDataType::STRING)}};
if (operation == Request::Operation::GET_OPEN_ORDERS) {
for (const auto& x : document["orderStatuses"].GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
} else 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 {}
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("cumQty");
auto it2 = x.FindMember("avgPrice");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
}
}
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_ERISX_H_
@@ -0,0 +1,69 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_FTX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_FTX_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_FTX
#include "ccapi_cpp/service/ccapi_execution_management_service_ftx_base.h"
namespace ccapi {
class ExecutionManagementServiceFtx : public ExecutionManagementServiceFtxBase {
public:
ExecutionManagementServiceFtx(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_FTX;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_FTX_API_KEY;
this->apiSecretName = CCAPI_FTX_API_SECRET;
this->apiSubaccountName = CCAPI_FTX_API_SUBACCOUNT;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiSubaccountName});
this->getAccountPositionsTarget = "/api/positions";
this->ftx = "FTX";
}
virtual ~ExecutionManagementServiceFtx() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
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::GET_ACCOUNT_POSITIONS: {
this->prepareReq(req, now, credential);
req.method(http::verb::get);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
auto target = this->getAccountPositionsTarget;
req.target(target);
this->signRequest(req, "", credential);
} break;
default:
ExecutionManagementServiceFtxBase::convertRequestForRest(req, request, now, symbolId, credential);
}
}
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_POSITIONS: {
for (const auto& x : document["result"].GetArray()) {
Element element;
element.insert(CCAPI_INSTRUMENT, x["future"].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, x["cost"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
default:
ExecutionManagementServiceFtxBase::extractAccountInfoFromRequest(elementList, request, operation, document);
}
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_FTX_H_
@@ -0,0 +1,412 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_FTX_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_FTX_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#if defined(CCAPI_ENABLE_EXCHANGE_FTX) || defined(CCAPI_ENABLE_EXCHANGE_FTX_US)
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
public:
ExecutionManagementServiceFtxBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->createOrderTarget = "/api/orders";
this->cancelOrderTarget = "/api/orders";
this->getOrderTarget = "/api/orders";
this->getOpenOrdersTarget = "/api/orders";
this->cancelOpenOrdersTarget = "/api/orders";
this->getAccountsTarget = "/api/subaccounts";
this->getAccountBalancesTarget = "/api/wallet/balances";
}
virtual ~ExecutionManagementServiceFtxBase() {}
#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 preSignedText = req.base().at(this->ftx + "-TS").to_string();
preSignedText += methodString;
std::string target = path;
if (!queryString.empty()) {
target += "?" + queryString;
}
preSignedText += target;
preSignedText += body;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
if (!headerString.empty()) {
headerString += "\r\n";
}
headerString += this->ftx + "-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(this->ftx + "-TS").to_string();
preSignedText += std::string(req.method_string());
preSignedText += req.target().to_string();
preSignedText += body;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
req.set(this->ftx + "-SIGN", signature);
req.body() = body;
req.prepare_payload();
}
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_LIMIT_PRICE, "price"},
{CCAPI_EM_ORDER_QUANTITY, "size"},
{CCAPI_EM_ORDER_TYPE, "type"},
{CCAPI_EM_CLIENT_ORDER_ID, "clientId"},
}) {
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 == "type" && value == "market") {
document.AddMember("price", rj::Value(rj::Type::kNullType), allocator);
}
if (value != "null") {
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_2(rj::Document& document, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {}) {
for (const auto& kv : param) {
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
auto value = kv.second;
if (value != "null") {
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 appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
document.AddMember("market", 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(this->ftx + "-KEY", apiKey);
req.set(this->ftx + "-TS", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
auto apiSubaccountName = mapGetWithDefault(credential, this->apiSubaccountName);
if (!apiSubaccountName.empty()) {
req.set(this->ftx + "-SUBACCOUNT", Url::urlEncode(apiSubaccountName));
}
}
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);
if (param.find("type") == param.end()) {
document.AddMember("type", rj::Value("limit").Move(), allocator);
}
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();
auto 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);
} break;
case Request::Operation::GET_ORDER: {
req.method(http::verb::get);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
auto 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->getOrderTarget + "/" + id : this->getOrderTarget + "/by_client_id/" + id);
this->signRequest(req, "", credential);
} break;
case Request::Operation::GET_OPEN_ORDERS: {
req.method(http::verb::get);
auto target = this->getOpenOrdersTarget;
if (!symbolId.empty()) {
target += "?market=";
target += Url::urlEncode(symbolId);
}
req.target(target);
this->signRequest(req, "", credential);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
req.method(http::verb::delete_);
auto target = this->cancelOpenOrdersTarget;
req.target(target);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam_2(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_ACCOUNTS: {
req.method(http::verb::get);
req.target(this->getAccountsTarget);
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) : "";
if (!accountId.empty()) {
target = "/api/subaccounts/{nickname}/balances";
this->substituteParam(target, {
{"{nickname}", Url::urlEncode(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("clientId", 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("filledSize", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("market", JsonDataType::STRING)},
};
const auto& result = document["result"];
if (result.IsArray()) {
for (const auto& x : result.GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
} else if (result.IsObject()) {
Element element;
this->extractOrderInfo(element, 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_ACCOUNTS: {
for (const auto& x : document["result"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ACCOUNT_ID, x["nickname"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
for (const auto& x : document["result"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, x["coin"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["total"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["free"].GetString());
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("filledSize");
auto it2 = x.FindMember("avgFillPrice");
if (it1 != x.MemberEnd() && !it1->value.IsNull() && it2 != x.MemberEnd() && !it2->value.IsNull()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
}
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
std::vector<std::string> sendStringList;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("login").Move(), allocator);
rj::Document args;
args.SetObject();
rj::Document::AllocatorType& allocatorArgs = args.GetAllocator();
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto subaccount = mapGetWithDefault(credential, this->apiSubaccountName);
std::string ts = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count());
args.AddMember("key", rj::Value(apiKey.c_str(), allocatorArgs).Move(), allocatorArgs);
std::string signData = ts + "websocket_login";
std::string sign = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, signData, true);
args.AddMember("sign", rj::Value(sign.c_str(), allocatorArgs).Move(), allocatorArgs);
rj::Value timeRj;
timeRj.SetInt64(std::stoll(ts));
args.AddMember("time", rj::Value(timeRj, allocatorArgs).Move(), allocatorArgs);
if (!subaccount.empty()) {
args.AddMember("subaccount", rj::Value(subaccount.c_str(), allocatorArgs).Move(), allocatorArgs);
}
document.AddMember("args", rj::Value(args, allocator).Move(), allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
const auto& fieldSet = subscription.getFieldSet();
for (const auto& field : subscription.getFieldSet()) {
std::string channelId;
if (field == CCAPI_EM_ORDER_UPDATE) {
channelId = "orders";
} else if (field == CCAPI_EM_PRIVATE_TRADE) {
channelId = "fills";
}
rj::Document documentSubscribe;
documentSubscribe.SetObject();
rj::Document::AllocatorType& allocatorSubscribe = documentSubscribe.GetAllocator();
documentSubscribe.AddMember("op", rj::Value("subscribe").Move(), allocatorSubscribe);
documentSubscribe.AddMember("channel", rj::Value(channelId.c_str(), allocatorSubscribe).Move(), allocatorSubscribe);
rj::StringBuffer stringBufferSubscribe;
rj::Writer<rj::StringBuffer> writerSubscribe(stringBufferSubscribe);
documentSubscribe.Accept(writerSubscribe);
std::string sendStringSubscribe = stringBufferSubscribe.GetString();
sendStringList.push_back(sendStringSubscribe);
}
return sendStringList;
}
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 event;
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
std::string type = document["type"].GetString();
if (type == "update") {
std::string channel = std::string(document["channel"].GetString());
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"];
std::string instrument = data["market"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
if (channel == "fills" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
message.setTime(UtilTime::parse(std::string(data["time"].GetString()), "%FT%T%Ez"));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, std::string(data["tradeId"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(data["price"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(data["size"].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()) == "maker" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(data["orderId"].GetString()));
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(data["fee"].GetString()));
{
auto it = data.FindMember("clientOrderId");
if (it != data.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 (channel == "orders" && 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("id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientId", 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_REMAINING_QUANTITY, std::make_pair("remainingSize", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filledSize", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("market", JsonDataType::STRING)},
};
Element info;
this->extractOrderInfo(info, data, extractionFieldNameMap);
{
auto it1 = data.FindMember("filledSize");
auto it2 = data.FindMember("avgFillPrice");
if (it1 != data.MemberEnd() && !it1->value.IsNull() && it2 != data.MemberEnd() && !it2->value.IsNull()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
}
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
} else if (type == "subscribed") {
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));
}
event.setMessageList(messageList);
return event;
}
std::string apiSubaccountName;
std::string ftx;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_FTX_BASE_H_
@@ -0,0 +1,32 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_FTX_US_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_FTX_US_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_FTX_US
#include "ccapi_cpp/service/ccapi_execution_management_service_ftx_base.h"
namespace ccapi {
class ExecutionManagementServiceFtxUs : public ExecutionManagementServiceFtxBase {
public:
ExecutionManagementServiceFtxUs(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_FTX_US;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_FTX_US_API_KEY;
this->apiSecretName = CCAPI_FTX_US_API_SECRET;
this->apiSubaccountName = CCAPI_FTX_US_API_SUBACCOUNT;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiSubaccountName});
this->ftx = "FTXUS";
}
virtual ~ExecutionManagementServiceFtxUs() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_FTX_US_H_
@@ -0,0 +1,41 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_GATEIO_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_GATEIO_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_GATEIO
#include "ccapi_cpp/service/ccapi_execution_management_service_gateio_base.h"
namespace ccapi {
class ExecutionManagementServiceGateio : public ExecutionManagementServiceGateioBase {
public:
ExecutionManagementServiceGateio(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v4/";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_GATEIO_API_KEY;
this->apiSecretName = CCAPI_GATEIO_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
std::string prefix = "/api/v4";
this->createOrderTarget = prefix + "/spot/orders";
this->cancelOrderTarget = prefix + "/spot/orders/{order_id}";
this->getOrderTarget = prefix + "/spot/orders/{order_id}";
this->getOpenOrdersTarget = prefix + "/spot/orders";
this->cancelOpenOrdersTarget = prefix + "/spot/orders";
this->getAccountsTarget = prefix + "/spot/accounts";
this->symbolName = "currency_pair";
this->websocketChannelUserTrades = "spot.usertrades";
this->websocketChannelOrders = "spot.orders";
this->amountName = "amount";
}
virtual ~ExecutionManagementServiceGateio() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_GATEIO_H_
@@ -0,0 +1,434 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_GATEIO_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_GATEIO_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#if defined(CCAPI_ENABLE_EXCHANGE_GATEIO) || defined(CCAPI_ENABLE_EXCHANGE_GATEIO_PERPETUAL_FUTURES)
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceGateioBase : public ExecutionManagementService {
public:
ExecutionManagementServiceGateioBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~ExecutionManagementServiceGateioBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& req, const Request& request, std::string& methodString,
std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string preSignedText = methodString;
preSignedText += "\n";
preSignedText += path;
preSignedText += "\n";
preSignedText += queryString;
preSignedText += "\n";
preSignedText += UtilAlgorithm::computeHash(UtilAlgorithm::ShaVersion::SHA512, body, true);
preSignedText += "\n";
preSignedText += req.base().at("TIMESTAMP").to_string();
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA512, apiSecret, preSignedText, true);
if (!headerString.empty()) {
headerString += "\r\n";
}
headerString += "SIGN:" + signature;
}
void signRequest(http::request<http::string_body>& req, const std::string& path, const std::string& queryString, const std::string& body,
const std::map<std::string, std::string>& credential) {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string preSignedText = std::string(req.method_string());
preSignedText += "\n";
preSignedText += path;
preSignedText += "\n";
preSignedText += queryString;
preSignedText += "\n";
preSignedText += UtilAlgorithm::computeHash(UtilAlgorithm::ShaVersion::SHA512, body, true);
preSignedText += "\n";
preSignedText += req.base().at("TIMESTAMP").to_string();
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA512, apiSecret, preSignedText, true);
req.set("SIGN", signature);
req.target(queryString.empty() ? path : path + "?" + queryString);
req.body() = body;
req.prepare_payload();
}
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 += this->symbolName;
queryString += "=";
queryString += Url::urlEncode(symbolId);
queryString += "&";
}
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) {
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 (value != "null") {
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(rj::Document& document, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param) {
this->appendParam(document, allocator, param,
{
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_ORDER_QUANTITY, this->amountName},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "text"},
{CCAPI_EM_ORDER_TYPE, "type"},
{CCAPI_EM_ACCOUNT_TYPE, "account"},
});
}
void appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
document.AddMember(rj::Value(symbolName.c_str(), allocator).Move(), rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
void substituteParamSettle(std::string& target, const std::map<std::string, std::string>& param, const std::string& symbolId) {
this->substituteParam(target, param,
{
{"settle", "{settle}"},
{CCAPI_MARGIN_ASSET, "{settle}"},
});
std::string settle;
if (UtilString::endsWith(symbolId, "_USD")) {
settle = "btc";
} else if (UtilString::endsWith(symbolId, "_USDT")) {
settle = "usdt";
}
this->substituteParam(target, {
{"{settle}", settle},
});
}
void prepareReq(http::request<http::string_body>& req, const TimePoint& now, const std::map<std::string, std::string>& credential) {
req.set("Accept", "application/json");
req.set(beast::http::field::content_type, "application/json");
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("KEY", apiKey);
req.set("TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::seconds>(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, 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();
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();
std::string path = this->createOrderTarget;
if (this->isDerivatives) {
this->substituteParamSettle(path, param, symbolId);
}
this->signRequest(req, path, "", body, credential);
} break;
case Request::Operation::CANCEL_ORDER: {
req.method(http::verb::delete_);
std::map<std::string, std::string> param = request.getFirstParamWithDefault();
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)
: "";
std::string path = this->cancelOrderTarget;
this->substituteParam(path, {
{"{order_id}", id},
});
param.erase(CCAPI_EM_ORDER_ID);
param.erase(CCAPI_EM_CLIENT_ORDER_ID);
param.erase("order_id");
std::string queryString;
this->appendParam(queryString, param,
{
{CCAPI_EM_ACCOUNT_ID, "account"},
});
this->appendSymbolId(queryString, symbolId);
queryString.pop_back();
if (this->isDerivatives) {
this->substituteParamSettle(path, param, symbolId);
}
this->signRequest(req, path, queryString, "", credential);
} break;
case Request::Operation::GET_ORDER: {
req.method(http::verb::get);
std::map<std::string, std::string> param = request.getFirstParamWithDefault();
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)
: "";
std::string path = this->getOrderTarget;
this->substituteParam(path, {
{"{order_id}", id},
});
param.erase(CCAPI_EM_ORDER_ID);
param.erase(CCAPI_EM_CLIENT_ORDER_ID);
param.erase("order_id");
std::string queryString;
this->appendParam(queryString, param,
{
{CCAPI_EM_ACCOUNT_ID, "account"},
});
this->appendSymbolId(queryString, symbolId);
queryString.pop_back();
if (this->isDerivatives) {
this->substituteParamSettle(path, param, symbolId);
}
this->signRequest(req, path, queryString, "", credential);
} break;
case Request::Operation::GET_OPEN_ORDERS: {
req.method(http::verb::get);
std::string queryString;
std::map<std::string, std::string> param = request.getFirstParamWithDefault();
param["status"] = "open";
this->appendParam(queryString, param,
{
{CCAPI_EM_ACCOUNT_ID, "account"},
});
this->appendSymbolId(queryString, symbolId);
queryString.pop_back();
std::string path = this->getOpenOrdersTarget;
if (this->isDerivatives) {
this->substituteParamSettle(path, param, symbolId);
}
this->signRequest(req, path, queryString, "", credential);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
req.method(http::verb::delete_);
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_EM_ACCOUNT_ID, "account"},
});
this->appendSymbolId(queryString, symbolId);
queryString.pop_back();
std::string path = this->getOpenOrdersTarget;
if (this->isDerivatives) {
this->substituteParamSettle(path, param, symbolId);
}
this->signRequest(req, path, queryString, "", credential);
} break;
case Request::Operation::GET_ACCOUNTS: {
req.method(http::verb::get);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
std::string queryString;
this->appendParam(queryString, param,
{
{CCAPI_EM_ASSET, "currency"},
});
if (!queryString.empty()) {
queryString.pop_back();
}
std::string path = this->getAccountsTarget;
if (this->isDerivatives) {
this->substituteParamSettle(path, param, symbolId);
}
this->signRequest(req, path, queryString, "", credential);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
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_ACCOUNTS: {
for (const auto& x : document.GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, x["currency"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["available"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
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("text", 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(this->amountName, JsonDataType::STRING)},
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("left", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filled_total", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair(this->symbolName, JsonDataType::STRING)},
};
if (operation == Request::Operation::GET_OPEN_ORDERS || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
for (const auto& x : document.GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
} else {
Element element;
this->extractOrderInfo(element, document, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
}
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;
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
int time = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
for (const auto& field : fieldSet) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("time", rj::Value(time).Move(), allocator);
std::string channel;
if (field == CCAPI_EM_PRIVATE_TRADE) {
channel = this->websocketChannelUserTrades;
} else if (field == CCAPI_EM_ORDER_UPDATE) {
channel = this->websocketChannelOrders;
}
document.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator);
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
rj::Value payload(rj::kArrayType);
if (instrumentSet.empty()) {
payload.PushBack(rj::Value("!all").Move(), allocator);
} else {
for (const auto& instrument : instrumentSet) {
payload.PushBack(rj::Value(instrument.c_str(), allocator).Move(), allocator);
}
}
document.AddMember("payload", payload, allocator);
rj::Value auth(rj::kObjectType);
auth.AddMember("method", rj::Value("api_key").Move(), allocator);
auth.AddMember("KEY", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
std::string preSignedText = "channel=" + channel + "&event=subscribe&time=" + std::to_string(time);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA512, apiSecret, preSignedText, true);
auth.AddMember("SIGN", rj::Value(signature.c_str(), allocator).Move(), allocator);
document.AddMember("auth", auth, 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 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 event;
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
std::string eventType = document["event"].GetString();
if (eventType == "update") {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
std::string channel = document["channel"].GetString();
std::string field;
if (channel == this->websocketChannelUserTrades) {
field = CCAPI_EM_PRIVATE_TRADE;
} else if (channel == this->websocketChannelOrders) {
field = CCAPI_EM_ORDER_UPDATE;
}
if (fieldSet.find(field) != fieldSet.end()) {
for (const auto& x : document["result"].GetArray()) {
std::string instrument = x[this->symbolName.c_str()].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
if (field == CCAPI_EM_PRIVATE_TRADE) {
Message message;
message.setTime(UtilTime::makeTimePointMilli(UtilTime::divideMilli(x["create_time_ms"].GetString())));
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, std::string(x["id"].GetString()));
element.insert(CCAPI_EM_ORDER_ID, x["order_id"].GetString());
element.insert(CCAPI_EM_CLIENT_ORDER_ID, x["text"].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_ORDER_LAST_EXECUTED_PRICE, x["price"].GetString());
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, x[this->amountName.c_str()].GetString());
std::string takerSide = x["side"].GetString();
element.insert(CCAPI_IS_MAKER, std::string(x["role"].GetString()) == "maker" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
} else if (field == CCAPI_EM_ORDER_UPDATE) {
Message message;
message.setTime(UtilTime::makeTimePointMilli(UtilTime::divideMilli(x["update_time_ms"].GetString())));
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
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("id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("text", 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(this->amountName, JsonDataType::STRING)},
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("left", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filled_total", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("event", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair(this->symbolName, 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 (eventType == "subscribe") {
bool hasError = document.HasMember("error") && !document["error"].IsNull();
event.setType(Event::Type::SUBSCRIPTION_STATUS);
message.setType(hasError ? Message::Type::SUBSCRIPTION_FAILURE : Message::Type::SUBSCRIPTION_STARTED);
Element element;
element.insert(hasError ? CCAPI_ERROR_MESSAGE : CCAPI_INFO_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
}
event.setMessageList(messageList);
return event;
}
bool isDerivatives{};
std::string symbolName;
std::string websocketChannelUserTrades;
std::string websocketChannelOrders;
std::string amountName;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_GATEIO_BASE_H_
@@ -0,0 +1,107 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_GATEIO_PERPETUAL_FUTURES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_GATEIO_PERPETUAL_FUTURES_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_GATEIO_PERPETUAL_FUTURES
#include "ccapi_cpp/service/ccapi_execution_management_service_gateio_base.h"
namespace ccapi {
class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagementServiceGateioBase {
public:
ExecutionManagementServiceGateioPerpetualFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY;
this->apiSecretName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
std::string prefix = "/api/v4";
this->createOrderTarget = prefix + "/futures/{settle}/orders";
this->cancelOrderTarget = prefix + "/futures/{settle}/orders/{order_id}";
this->getOrderTarget = prefix + "/futures/{settle}/orders/{order_id}";
this->getOpenOrdersTarget = prefix + "/futures/{settle}/orders";
this->cancelOpenOrdersTarget = prefix + "/futures/{settle}/orders";
this->getAccountsTarget = prefix + "/futures/{settle}/accounts";
this->getAccountPositionsTarget = prefix + "/futures/{settle}/positions";
this->symbolName = "contract";
this->websocketChannelUserTrades = "futures.usertrades";
this->websocketChannelOrders = "futures.orders";
this->isDerivatives = true;
this->amountName = "size";
}
virtual ~ExecutionManagementServiceGateioPerpetualFutures() {}
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::GET_ACCOUNT_POSITIONS: {
this->prepareReq(req, now, credential);
req.method(http::verb::get);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
std::string queryString;
this->appendParam(queryString, param,
{
{CCAPI_EM_ASSET, "currency"},
});
if (!queryString.empty()) {
queryString.pop_back();
}
this->signRequest(req, this->getAccountsTarget, queryString, "", credential);
} break;
default:
ExecutionManagementServiceGateioBase::convertRequestForRest(req, request, now, symbolId, credential);
}
}
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_POSITIONS: {
for (const auto& x : document.GetArray()) {
Element element;
element.insert(CCAPI_INSTRUMENT, x["contract"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString());
element.insert(CCAPI_EM_POSITION_COST, std::to_string(std::stod(x["entry_price"].GetString()) * std::stod(x["size"].GetString())));
elementList.emplace_back(std::move(element));
}
} break;
default:
ExecutionManagementServiceGateioBase::extractAccountInfoFromRequest(elementList, request, operation, document);
}
}
void subscribe(std::vector<Subscription>& subscriptionList) override {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_DEBUG("this->baseUrl = " + this->baseUrl);
if (this->shouldContinue.load()) {
for (auto& subscription : subscriptionList) {
wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(),
[that = shared_from_base<ExecutionManagementServiceGateioPerpetualFutures>(), subscription]() mutable {
auto now = UtilTime::now();
subscription.setTimeSent(now);
const auto& instrumentSet = subscription.getInstrumentSet();
auto it = instrumentSet.begin();
if (it != instrumentSet.end()) {
std::string settle;
std::string symbolId = *it;
if (UtilString::endsWith(symbolId, "_USD")) {
settle = "btc";
} else if (UtilString::endsWith(symbolId, "_USDT")) {
settle = "usdt";
}
WsConnection wsConnection(that->baseUrl + settle, "", {subscription});
that->prepareConnect(wsConnection);
}
});
}
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_GATEIO_PERPETUAL_FUTURES_H_
@@ -0,0 +1,406 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_GEMINI_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_GEMINI_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_GEMINI
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceGemini : public ExecutionManagementService {
public:
ExecutionManagementServiceGemini(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_GEMINI;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v1/order/events";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_GEMINI_API_KEY;
this->apiSecretName = CCAPI_GEMINI_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = "/v1/order/new";
this->cancelOrderTarget = "/v1/order/cancel";
this->getOrderTarget = "/v1/order/status";
this->getOpenOrdersTarget = "/v1/orders";
this->cancelOpenOrdersTarget = "/v1/order/cancel/session";
this->getAccountsTarget = "/v1/account/list";
this->getAccountBalancesTarget = "/v1/balances";
}
virtual ~ExecutionManagementServiceGemini() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& req, const Request& request, std::string& methodString,
std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
auto headerMap = ExecutionManagementService::convertHeaderStringToMap(headerString);
auto base64Payload = mapGetWithDefault(headerMap, std::string("X-GEMINI-PAYLOAD"));
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA384, apiSecret, base64Payload, true);
if (!headerString.empty()) {
headerString += "\r\n";
}
headerString += "X-GEMINI-SIGNATURE:" + signature;
}
void signRequest(http::request<http::string_body>& req, rj::Document& document, rj::Document::AllocatorType& allocator,
const std::map<std::string, std::string>& param, const TimePoint& now, const std::map<std::string, std::string>& credential, int64_t nonce) {
document.AddMember("request", rj::Value(req.target().to_string().c_str(), allocator).Move(), allocator);
document.AddMember("nonce", rj::Value(nonce).Move(), allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
auto body = stringBuffer.GetString();
this->signRequest(req, body, credential);
}
void signRequest(http::request<http::string_body>& req, const std::string& body, const std::map<std::string, std::string>& credential) {
auto base64Payload = UtilAlgorithm::base64Encode(body);
req.set("X-GEMINI-PAYLOAD", base64Payload);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA384, apiSecret, base64Payload, true);
req.set("X-GEMINI-SIGNATURE", signature);
}
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 = {}) {
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 == "order_id") {
document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(static_cast<int64_t>(std::stoll(value))).Move(), allocator);
} else {
document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
}
}
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 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 {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("Content-Length", "0");
req.set("Content-Type", "text/plain");
req.set("X-GEMINI-APIKEY", apiKey);
req.set("Cache-Control", "no-cache");
int64_t nonce = this->generateNonce(now, request.getIndex());
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,
{
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_ORDER_QUANTITY, "amount"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "client_order_id"},
});
this->appendSymbolId(document, allocator, symbolId);
if (param.find("type") == param.end()) {
document.AddMember("type", rj::Value("exchange limit").Move(), allocator);
}
this->signRequest(req, document, allocator, param, now, credential, nonce);
} break;
case Request::Operation::CANCEL_ORDER: {
req.method(http::verb::post);
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,
{
{CCAPI_EM_ORDER_ID, "order_id"},
});
this->signRequest(req, document, allocator, param, now, credential, nonce);
} break;
case Request::Operation::GET_ORDER: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->getOrderTarget);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param,
{
{CCAPI_EM_ORDER_ID, "order_id"},
{CCAPI_EM_CLIENT_ORDER_ID, "client_order_id"},
{CCAPI_EM_ACCOUNT_ID, "account"},
});
this->signRequest(req, document, allocator, param, now, credential, nonce);
} break;
case Request::Operation::GET_OPEN_ORDERS: {
req.method(http::verb::post);
req.target(this->getOpenOrdersTarget);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, {},
{
{CCAPI_EM_ACCOUNT_ID, "account"},
});
this->signRequest(req, document, allocator, {}, now, credential, nonce);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
req.method(http::verb::post);
req.target(this->cancelOpenOrdersTarget);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, {},
{
{CCAPI_EM_ACCOUNT_ID, "account"},
});
this->signRequest(req, document, allocator, {}, now, credential, nonce);
} break;
case Request::Operation::GET_ACCOUNTS: {
req.method(http::verb::post);
req.target(this->getAccountsTarget);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->signRequest(req, document, allocator, {}, now, credential, nonce);
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
req.method(http::verb::post);
req.target(this->getAccountBalancesTarget);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, {},
{
{CCAPI_EM_ACCOUNT_ID, "account"},
});
this->signRequest(req, document, allocator, {}, now, credential, nonce);
} 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("original_amount", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("executed_amount", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}};
if (operation == Request::Operation::CANCEL_OPEN_ORDERS) {
for (const auto& x : document["details"]["cancelledOrders"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ORDER_ID, std::string(x.GetString()));
elementList.emplace_back(std::move(element));
}
} else 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_ACCOUNTS: {
for (const auto& x : document.GetArray()) {
Element element;
element.insert(CCAPI_EM_ACCOUNT_ID, x["account"].GetString());
element.insert(CCAPI_EM_ACCOUNT_TYPE, x["type"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
for (const auto& x : document.GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, x["currency"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["available"].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("executed_amount");
auto it2 = x.FindMember("avg_execution_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
}
}
{
auto it = x.FindMember("is_live");
if (it != x.MemberEnd()) {
element.insert("is_live", it->value.GetBool() ? "true" : "false");
}
}
{
auto it = x.FindMember("is_cancelled");
if (it != x.MemberEnd()) {
element.insert("is_cancelled", it->value.GetBool() ? "true" : "false");
}
}
}
void prepareConnect(WsConnection& wsConnection) override {
auto now = UtilTime::now();
auto subscription = wsConnection.subscriptionList.at(0);
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
auto credential = wsConnection.subscriptionList.at(0).getCredential();
if (credential.empty()) {
credential = this->credentialDefault;
}
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
wsConnection.url += "?heartbeat=true";
if (fieldSet == std::set<std::string>({CCAPI_EM_PRIVATE_TRADE})) {
wsConnection.url += "&eventTypeFilter=fill";
}
if (!instrumentSet.empty()) {
for (const auto& instrument : instrumentSet) {
wsConnection.url += "&symbolFilter=" + instrument;
}
}
wsConnection.url += "&apiSessionFilter=" + apiKey;
wsConnection.headers.insert({"X-GEMINI-APIKEY", apiKey});
int64_t nonce = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
std::string payload = R"({"request":"/v1/order/events","nonce":)" + std::to_string(nonce) + "}";
auto base64Payload = UtilAlgorithm::base64Encode(payload);
wsConnection.headers.insert({"X-GEMINI-PAYLOAD", base64Payload});
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA384, apiSecret, base64Payload, true);
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,
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 event;
std::vector<Message> messageList;
if (document.IsObject()) {
std::string type = document["type"].GetString();
if (type == "subscription_ack") {
event.setType(Event::Type::SUBSCRIPTION_STATUS);
Message message;
message.setType(Message::Type::SUBSCRIPTION_STARTED);
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
Element element;
element.insert(CCAPI_INFO_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
}
} else if (document.IsArray()) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
for (const auto& x : document.GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
std::string type = x["type"].GetString();
if (this->websocketOrderUpdateTypeSet.find(type) != websocketOrderUpdateTypeSet.end()) {
std::string instrument = std::string(x["symbol"].GetString());
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
auto it = x.FindMember("timestampms");
if (it != x.MemberEnd()) {
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(it->value.GetString()))));
}
if (type == "fill" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
const rj::Value& fill = x["fill"];
element.insert(CCAPI_TRADE_ID, fill["trade_id"].GetString());
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, fill["price"].GetString());
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, fill["amount"].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(fill["liquidity"].GetString()) == "Taker" ? "0" : "1");
element.insert(CCAPI_EM_ORDER_ID, x["order_id"].GetString());
element.insert(CCAPI_EM_CLIENT_ORDER_ID, x["client_order_id"].GetString());
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, fill["fee"].GetString());
element.insert(CCAPI_EM_ORDER_FEE_ASSET, fill["fee_currency"].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.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("original_amount", JsonDataType::STRING)},
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("remaining_amount", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("executed_amount", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
};
Element info;
this->extractOrderInfo(info, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("executed_amount");
auto it2 = x.FindMember("avg_execution_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
}
}
{
auto it = x.FindMember("is_live");
if (it != x.MemberEnd()) {
info.insert("is_live", it->value.GetBool() ? "1" : "0");
}
}
{
auto it = x.FindMember("is_cancelled");
if (it != x.MemberEnd()) {
info.insert("is_cancelled", it->value.GetBool() ? "1" : "0");
}
}
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::set<std::string> websocketOrderUpdateTypeSet{"accepted", "rejected", "booked", "fill", "cancelled", "cancel_rejected", "closed"};
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_GEMINI_H_
@@ -0,0 +1,411 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI
#include "ccapi_cpp/service/ccapi_execution_management_service_huobi_base.h"
namespace ccapi {
class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBase {
public:
ExecutionManagementServiceHuobi(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceHuobiBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v2";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_HUOBI_API_KEY;
this->apiSecretName = CCAPI_HUOBI_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = "/v1/order/orders/place";
this->cancelOrderTarget = "/v1/order/orders/{order-id}/submitcancel";
this->cancelOrderByClientOrderIdTarget = "/v1/order/orders/submitCancelClientOrder";
this->getOrderTarget = "/v1/order/orders/{order-id}";
this->getOrderByClientOrderIdTarget = "/v1/order/orders/getClientOrder";
this->getOpenOrdersTarget = "/v1/order/openOrders";
this->cancelOpenOrdersTarget = "/v1/order/orders/batchCancelOpenOrders";
this->getAccountsTarget = "/v1/account/accounts";
this->getAccountBalancesTarget = "/v1/account/accounts/{account-id}/balance";
}
virtual ~ExecutionManagementServiceHuobi() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
bool doesHttpBodyContainError(const Request& request, 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");
}
void appendSymbolId(std::map<std::string, std::string>& queryParamMap, const std::string& symbolId) {
ExecutionManagementServiceHuobiBase::appendSymbolId(queryParamMap, symbolId, "symbol");
}
void convertReqDetail(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential, std::map<std::string, std::string>& queryParamMap) override {
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();
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param,
{
{CCAPI_EM_ORDER_SIDE, "type"},
{CCAPI_EM_ORDER_QUANTITY, "amount"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "client-order-id"},
{CCAPI_EM_ACCOUNT_ID, "account-id"},
});
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, this->createOrderTarget, queryParamMap, credential);
} break;
case Request::Operation::CANCEL_ORDER: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
auto shouldUseOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end();
std::string id = shouldUseOrderId ? param.at(CCAPI_EM_ORDER_ID)
: param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? "client:" + param.at(CCAPI_EM_CLIENT_ORDER_ID)
: "";
auto target =
shouldUseOrderId ? std::regex_replace(this->cancelOrderTarget, std::regex("\\{order\\-id\\}"), id) : this->cancelOrderByClientOrderIdTarget;
if (!shouldUseOrderId) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param,
{
{CCAPI_EM_CLIENT_ORDER_ID, "client-order-id"},
});
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, target, queryParamMap, credential);
} break;
case Request::Operation::GET_ORDER: {
req.method(http::verb::get);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
auto shouldUseOrderId = param.find(CCAPI_EM_ORDER_ID) != param.end();
std::string id = shouldUseOrderId ? param.at(CCAPI_EM_ORDER_ID)
: param.find(CCAPI_EM_CLIENT_ORDER_ID) != param.end() ? param.at(CCAPI_EM_CLIENT_ORDER_ID)
: "";
auto target = shouldUseOrderId ? std::regex_replace(this->getOrderTarget, std::regex("\\{order\\-id\\}"), id) : this->getOrderByClientOrderIdTarget;
req.target(target);
if (!shouldUseOrderId) {
ExecutionManagementServiceHuobiBase::appendParam(queryParamMap, param,
{
{CCAPI_EM_ACCOUNT_ID, "account-id"},
});
queryParamMap.insert(std::make_pair("clientOrderId", Url::urlEncode(id)));
}
this->signRequest(req, target, queryParamMap, credential);
} break;
case Request::Operation::GET_OPEN_ORDERS: {
req.method(http::verb::get);
ExecutionManagementServiceHuobiBase::appendParam(queryParamMap, {},
{
{CCAPI_EM_ACCOUNT_ID, "account-id"},
});
if (!symbolId.empty()) {
this->appendSymbolId(queryParamMap, symbolId);
}
this->signRequest(req, this->getOpenOrdersTarget, queryParamMap, credential);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param,
{
{CCAPI_EM_ACCOUNT_ID, "account-id"},
});
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, this->cancelOpenOrdersTarget, queryParamMap, credential);
} break;
case Request::Operation::GET_ACCOUNTS: {
req.method(http::verb::get);
this->signRequest(req, this->getAccountsTarget, queryParamMap, credential);
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
req.method(http::verb::get);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
auto accountId = mapGetWithDefault(param, std::string(CCAPI_EM_ACCOUNT_ID));
auto target = std::regex_replace(this->getAccountBalancesTarget, std::regex("\\{account\\-id\\}"), accountId);
this->signRequest(req, target, queryParamMap, 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::INTEGER)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client-order-id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("type", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("amount", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filled-amount", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("filled-cash-amount", 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) {
Element element;
element.insert(CCAPI_EM_ORDER_ID, std::string(data.GetString()));
elementList.emplace_back(std::move(element));
} else 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 {
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_ACCOUNT_ID, std::string(x["id"].GetString()));
element.insert(CCAPI_EM_ACCOUNT_TYPE, x["type"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
for (const auto& x : data["list"].GetArray()) {
if (std::string(x["type"].GetString()) == "trade") {
Element element;
element.insert(CCAPI_EM_ASSET, x["currency"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["balance"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["balance"].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 {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now, "%FT%T");
std::string signature;
std::string queryString;
std::map<std::string, std::string> queryParamMap;
queryParamMap.insert(std::make_pair("accessKey", apiKey));
queryParamMap.insert(std::make_pair("signatureMethod", "HmacSHA256"));
queryParamMap.insert(std::make_pair("signatureVersion", "2.1"));
queryParamMap.insert(std::make_pair("timestamp", Url::urlEncode(timestamp)));
this->createSignature(signature, queryString, "GET", this->hostRest, "/ws/v2", queryParamMap, credential);
std::vector<std::string> sendStringList;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("action", rj::Value("req").Move(), allocator);
document.AddMember("ch", rj::Value("auth").Move(), allocator);
rj::Value params(rj::kObjectType);
params.AddMember("authType", rj::Value("api").Move(), allocator);
params.AddMember("accessKey", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
params.AddMember("signatureMethod", rj::Value("HmacSHA256").Move(), allocator);
params.AddMember("signatureVersion", rj::Value("2.1").Move(), allocator);
params.AddMember("timestamp", rj::Value(timestamp.c_str(), allocator).Move(), allocator);
params.AddMember("signature", rj::Value(signature.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 onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
const TimePoint& timeReceived) override {
std::string actionStr = document["action"].GetString();
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
if (actionStr == "req") {
std::string chStr = document["ch"].GetString();
if (chStr == "auth") {
int code = std::stoi(document["code"].GetString());
if (code == 200) {
std::set<std::string> symbols;
if (instrumentSet.empty()) {
symbols = {"*"};
} else {
symbols = instrumentSet;
}
for (const auto& symbol : symbols) {
for (const auto& field : fieldSet) {
rj::Document document;
document.SetObject();
auto& allocator = document.GetAllocator();
document.AddMember("action", rj::Value("sub").Move(), allocator);
std::string ch;
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
ch = "orders#" + symbol;
} else if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
ch = "trade.clearing#" + symbol;
}
document.AddMember("ch", rj::Value(ch.c_str(), allocator).Move(), 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->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, textMessage, {subscription.getCorrelationId()});
}
}
} else if (actionStr == "ping") {
rj::StringBuffer stringBufferSubscribe;
rj::Writer<rj::StringBuffer> writerSubscribe(stringBufferSubscribe);
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
std::string toReplace("ping");
sendString.replace(sendString.find(toReplace), toReplace.length(), "pong");
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, "pong");
}
} else {
Event event = this->createEvent(subscription, textMessage, document, actionStr, 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& actionStr,
const TimePoint& timeReceived) {
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 (actionStr == "push") {
event.setType(Event::Type::SUBSCRIPTION_DATA);
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
std::string ch = document["ch"].GetString();
if (ch.rfind("orders#", 0) == 0 && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
const rj::Value& data = document["data"];
std::string instrument = data["symbol"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
auto it = data.FindMember("lastActTime");
if (it == data.MemberEnd()) {
it = data.FindMember("orderCreateTime");
if (it == data.MemberEnd()) {
it = data.FindMember("tradeTime");
}
}
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(it->value.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("clientOrderId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("type", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("orderPrice", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("orderSize", JsonDataType::STRING)},
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("remainAmt", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("execAmt", 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, data, extractionFieldNameMap);
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);
}
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
} else if (ch.rfind("trade.clearing#", 0) == 0 && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
const rj::Value& data = document["data"];
std::string instrument = data["symbol"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(data["tradeTime"].GetString())));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, std::string(data["tradeId"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, data["tradePrice"].GetString());
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, data["tradeVolume"].GetString());
element.insert(CCAPI_EM_ORDER_SIDE, std::string(data["orderSide"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_IS_MAKER, data["aggressor"].GetBool() ? "0" : "1");
element.insert(CCAPI_EM_ORDER_ID, std::string(data["orderId"].GetString()));
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(data["clientOrderId"].GetString()));
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(data["transactFee"].GetString()));
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(data["feeCurrency"].GetString()));
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
} else if (actionStr == "sub") {
int code = std::stoi(document["code"].GetString());
if (code == 200) {
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));
}
}
event.setMessageList(messageList);
return event;
}
std::string cancelOrderByClientOrderIdTarget;
std::string getOrderByClientOrderIdTarget;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_H_
@@ -0,0 +1,120 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#if defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceHuobiBase : public ExecutionManagementService {
public:
ExecutionManagementServiceHuobiBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~ExecutionManagementServiceHuobiBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
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;
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 appendParam(rj::Document& document, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {}) {
for (const auto& kv : param) {
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
auto value = kv.second;
if (this->isDerivatives) {
if (key == "direction") {
value = UtilString::toLower(value);
}
} else {
if (key == "type") {
value = (value == CCAPI_EM_ORDER_SIDE_BUY || value == "buy-limit") ? "buy-limit" : "sell-limit";
}
}
document.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
}
void appendParam(std::map<std::string, std::string>& queryParamMap, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {}) {
for (const auto& kv : param) {
queryParamMap.insert(std::make_pair(standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first,
Url::urlEncode(kv.second)));
}
}
void appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId, const std::string symbolIdCalled) {
document.AddMember(rj::Value(symbolIdCalled.c_str(), allocator).Move(), rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
void appendSymbolId(std::map<std::string, std::string>& queryParamMap, const std::string& symbolId, const std::string symbolIdCalled) {
queryParamMap.insert(std::make_pair(symbolIdCalled, Url::urlEncode(symbolId)));
}
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);
std::map<std::string, std::string> queryParamMap;
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)));
this->convertReqDetail(req, request, now, symbolId, credential, queryParamMap);
}
virtual void convertReqDetail(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential, std::map<std::string, std::string>& queryParamMap) {}
bool isDerivatives{};
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_BASE_H_
@@ -0,0 +1,39 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_COIN_SWAP_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_COIN_SWAP_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP
#include "ccapi_cpp/service/ccapi_execution_management_service_huobi_derivatives_base.h"
namespace ccapi {
class ExecutionManagementServiceHuobiCoinSwap : public ExecutionManagementServiceHuobiDerivativesBase {
public:
ExecutionManagementServiceHuobiCoinSwap(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_HUOBI_COIN_SWAP_API_KEY;
this->apiSecretName = CCAPI_HUOBI_COIN_SWAP_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = CCAPI_HUOBI_COIN_SWAP_CREATE_ORDER_PATH;
this->cancelOrderTarget = CCAPI_HUOBI_COIN_SWAP_CANCEL_ORDER_PATH;
this->getOrderTarget = CCAPI_HUOBI_COIN_SWAP_GET_ORDER_PATH;
this->getOpenOrdersTarget = CCAPI_HUOBI_COIN_SWAP_GET_OPEN_ORDERS_PATH;
this->getAccountBalancesTarget = CCAPI_HUOBI_COIN_SWAP_GET_ACCOUNT_BALANCES_PATH;
this->getAccountPositionsTarget = CCAPI_HUOBI_COIN_SWAP_GET_ACCOUNT_POSITIONS_PATH;
this->authenticationPath = "/swap-api/v1/swap_order";
this->orderDataTopic = CCAPI_HUOBI_COIN_SWAP_SUBSCRIBE_ORDER_DATA_TOPIC;
this->matchOrderDataTopic = CCAPI_HUOBI_COIN_SWAP_SUBSCRIBE_MATCH_ORDER_DATA_TOPIC;
}
virtual ~ExecutionManagementServiceHuobiCoinSwap() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_COIN_SWAP_H_
@@ -0,0 +1,405 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_DERIVATIVES_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_DERIVATIVES_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#if defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)
#include "ccapi_cpp/ccapi_decimal.h"
#include "ccapi_cpp/service/ccapi_execution_management_service_huobi_base.h"
namespace ccapi {
class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagementServiceHuobiBase {
public:
ExecutionManagementServiceHuobiDerivativesBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions,
SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceHuobiBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->isDerivatives = true;
// this->convertNumberToStringInJsonRegex = std::regex("(\\[|,|\":)\\s?(-?\\d+\\.?\\d*[eE]?-?\\d*)");
this->needDecompressWebsocketMessage = true;
ErrorCode ec = this->inflater.init(false, 31);
if (ec) {
CCAPI_LOGGER_FATAL(ec.message());
}
}
virtual ~ExecutionManagementServiceHuobiDerivativesBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
bool doesHttpBodyContainError(const Request& request, 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");
}
void appendSymbolId(std::map<std::string, std::string>& queryParamMap, const std::string& symbolId) {
ExecutionManagementServiceHuobiBase::appendSymbolId(queryParamMap, symbolId, "contract_code");
}
void convertReqDetail(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential, std::map<std::string, std::string>& queryParamMap) override {
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();
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param,
{
{CCAPI_EM_ORDER_SIDE, "direction"},
{CCAPI_EM_ORDER_QUANTITY, "volume"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "client_order_id"},
{CCAPI_EM_ORDER_LEVERAGE, "lever_rate"},
});
if (param.find("offset") == param.end()) {
document.AddMember("offset", rj::Value("open").Move(), allocator);
}
if (param.find("lever_rate") == param.end()) {
document.AddMember("lever_rate", rj::Value("1").Move(), allocator);
}
if (param.find("order_price_type") == param.end()) {
document.AddMember("order_price_type", rj::Value("limit").Move(), allocator);
}
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, this->createOrderTarget, queryParamMap, credential);
} break;
case Request::Operation::CANCEL_ORDER: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param,
{
{CCAPI_EM_ORDER_ID, "order_id"},
{CCAPI_EM_CLIENT_ORDER_ID, "client_order_id"},
});
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, this->cancelOrderTarget, queryParamMap, credential);
} break;
case Request::Operation::GET_ORDER: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param,
{
{CCAPI_EM_ORDER_ID, "order_id"},
{CCAPI_EM_CLIENT_ORDER_ID, "client_order_id"},
});
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, this->getOrderTarget, queryParamMap, credential);
} break;
case Request::Operation::GET_OPEN_ORDERS: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
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, this->getOpenOrdersTarget, queryParamMap, credential);
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
req.method(http::verb::post);
this->signRequest(req, this->getAccountBalancesTarget, queryParamMap, credential);
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
req.method(http::verb::post);
this->signRequest(req, this->getAccountPositionsTarget, queryParamMap, 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("direction", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("volume", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("trade_volume", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("contract_code", JsonDataType::STRING)}};
const rj::Value& data = document["data"];
if (operation == Request::Operation::CREATE_ORDER) {
Element element;
ExecutionManagementServiceHuobiDerivativesBase::extractOrderInfo(element, data, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
} else if (operation == Request::Operation::CANCEL_ORDER) {
Element element;
element.insert(CCAPI_EM_ORDER_ID, std::string(data["successes"].GetString()));
elementList.emplace_back(std::move(element));
} else if (operation == Request::Operation::GET_ORDER) {
Element element;
ExecutionManagementServiceHuobiDerivativesBase::extractOrderInfo(element, data[0], extractionFieldNameMap);
elementList.emplace_back(std::move(element));
} else if (operation == Request::Operation::GET_OPEN_ORDERS) {
for (const auto& x : data["orders"].GetArray()) {
Element element;
ExecutionManagementServiceHuobiDerivativesBase::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 {
const auto& data = document["data"];
switch (request.getOperation()) {
case Request::Operation::GET_ACCOUNT_BALANCES: {
Element element;
auto it = data[0].FindMember("margin_asset");
element.insert(CCAPI_EM_ASSET, it != data[0].MemberEnd() ? it->value.GetString() : data[0]["symbol"].GetString());
auto marginAvailable = Decimal(data[0]["margin_balance"].GetString())
.subtract(Decimal(data[0]["margin_position"].GetString()))
.subtract(Decimal(data[0]["margin_frozen"].GetString()))
.toString();
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, marginAvailable);
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["contract_code"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["direction"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["available"].GetString());
element.insert(CCAPI_EM_POSITION_COST, x["cost_open"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["lever_rate"].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("trade_volume");
auto it2 = x.FindMember("trade_avg_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))));
}
}
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now, "%FT%T");
std::string signature;
std::string queryString;
std::map<std::string, std::string> queryParamMap;
queryParamMap.insert(std::make_pair("AccessKeyId", apiKey));
queryParamMap.insert(std::make_pair("SignatureMethod", "HmacSHA256"));
queryParamMap.insert(std::make_pair("SignatureVersion", "2"));
queryParamMap.insert(std::make_pair("Timestamp", Url::urlEncode(timestamp)));
this->createSignature(signature, queryString, "GET", this->hostRest, this->authenticationPath, queryParamMap, credential);
std::vector<std::string> sendStringList;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("auth").Move(), allocator);
document.AddMember("type", rj::Value("api").Move(), allocator);
document.AddMember("AccessKeyId", rj::Value(apiKey.c_str(), allocator).Move(), allocator);
document.AddMember("SignatureMethod", rj::Value("HmacSHA256").Move(), allocator);
document.AddMember("SignatureVersion", rj::Value("2").Move(), allocator);
document.AddMember("Timestamp", rj::Value(timestamp.c_str(), allocator).Move(), allocator);
document.AddMember("Signature", 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);
return sendStringList;
}
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
const TimePoint& timeReceived) override {
std::string op = document["op"].GetString();
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
if (op == "auth") {
std::string errCode = document["err-code"].GetString();
if (errCode == "0") {
for (const auto& instrument : instrumentSet) {
for (const auto& field : fieldSet) {
rj::Document document;
document.SetObject();
auto& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("sub").Move(), allocator);
std::string topic;
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
topic = this->orderDataTopic + "." + instrument;
} else if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
topic = this->matchOrderDataTopic + "." + instrument;
}
document.AddMember("topic", rj::Value(topic.c_str(), allocator).Move(), 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->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, textMessage, {subscription.getCorrelationId()});
}
} else if (op == "ping") {
rj::StringBuffer stringBufferSubscribe;
rj::Writer<rj::StringBuffer> writerSubscribe(stringBufferSubscribe);
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
std::string toReplace("ping");
sendString.replace(sendString.find(toReplace), toReplace.length(), "pong");
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, "pong");
}
} else {
Event event = this->createEvent(subscription, textMessage, document, op, 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& op,
const TimePoint& timeReceived) {
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 (op == "notify") {
event.setType(Event::Type::SUBSCRIPTION_DATA);
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
std::string topic = document["topic"].GetString();
if (topic.rfind(this->orderDataTopic + ".", 0) == 0 && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
std::string instrument = document["contract_code"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(document["ts"].GetString())));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("order_id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("direction", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("volume", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("trade_volume", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("contract_code", JsonDataType::STRING)},
};
Element info;
this->extractOrderInfo(info, document, extractionFieldNameMap);
{
auto it1 = document.FindMember("trade_volume");
auto it2 = document.FindMember("trade_avg_price");
if (it1 != document.MemberEnd() && it2 != document.MemberEnd()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
}
}
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
} else if (topic.rfind(this->matchOrderDataTopic + ".", 0) == 0 && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
std::string instrument = document["contract_code"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
std::string orderSide = std::string(document["direction"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL;
std::string positionSide = document["offset"].GetString();
std::string orderId = document["order_id"].GetString();
std::string clientOrderId;
auto it = document.FindMember("client_order_id");
if (!it->value.IsNull()) {
clientOrderId = it->value.GetString();
}
for (const auto& x : document["trade"].GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(x["created_at"].GetString())));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, std::string(x["trade_id"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, x["trade_price"].GetString());
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, x["trade_volume"].GetString());
element.insert(CCAPI_EM_ORDER_SIDE, orderSide);
element.insert(CCAPI_EM_POSITION_SIDE, positionSide);
element.insert(CCAPI_IS_MAKER, std::string(x["role"].GetString()) == "maker" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, orderId);
if (!clientOrderId.empty()) {
element.insert(CCAPI_EM_CLIENT_ORDER_ID, clientOrderId);
}
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
} else if (op == "sub") {
auto it = document.FindMember("err-code");
if (it != document.MemberEnd() && std::string(it->value.GetString()) != "0") {
event.setType(Event::Type::SUBSCRIPTION_STATUS);
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
} else {
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));
}
}
event.setMessageList(messageList);
return event;
}
std::string authenticationPath;
std::string orderDataTopic;
std::string matchOrderDataTopic;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_DERIVATIVES_BASE_H_
@@ -0,0 +1,39 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_USDT_SWAP_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_USDT_SWAP_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP
#include "ccapi_cpp/service/ccapi_execution_management_service_huobi_derivatives_base.h"
namespace ccapi {
class ExecutionManagementServiceHuobiUsdtSwap : public ExecutionManagementServiceHuobiDerivativesBase {
public:
ExecutionManagementServiceHuobiUsdtSwap(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_HUOBI_USDT_SWAP_API_KEY;
this->apiSecretName = CCAPI_HUOBI_USDT_SWAP_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = CCAPI_HUOBI_USDT_SWAP_CREATE_ORDER_PATH;
this->cancelOrderTarget = CCAPI_HUOBI_USDT_SWAP_CANCEL_ORDER_PATH;
this->getOrderTarget = CCAPI_HUOBI_USDT_SWAP_GET_ORDER_PATH;
this->getOpenOrdersTarget = CCAPI_HUOBI_USDT_SWAP_GET_OPEN_ORDERS_PATH;
this->getAccountBalancesTarget = CCAPI_HUOBI_USDT_SWAP_GET_ACCOUNT_BALANCES_PATH;
this->getAccountPositionsTarget = CCAPI_HUOBI_USDT_SWAP_GET_ACCOUNT_POSITIONS_PATH;
this->authenticationPath = "/linear-swap-notification";
this->orderDataTopic = CCAPI_HUOBI_USDT_SWAP_SUBSCRIBE_ORDER_DATA_TOPIC;
this->matchOrderDataTopic = CCAPI_HUOBI_USDT_SWAP_SUBSCRIBE_MATCH_ORDER_DATA_TOPIC;
}
virtual ~ExecutionManagementServiceHuobiUsdtSwap() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_HUOBI_USDT_SWAP_H_
@@ -0,0 +1,464 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KRAKEN_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KRAKEN_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
#include "openssl/evp.h"
namespace ccapi {
class ExecutionManagementServiceKraken : public ExecutionManagementService {
public:
ExecutionManagementServiceKraken(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN;
this->baseUrl = CCAPI_KRAKEN_URL_WS_BASE_PRIVATE;
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_KRAKEN_API_KEY;
this->apiSecretName = CCAPI_KRAKEN_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
std::string prefix = "/0/private";
this->createOrderTarget = prefix + "/AddOrder";
this->cancelOrderTarget = prefix + "/CancelOrder";
this->getOrderTarget = prefix + "/QueryOrders";
this->getOpenOrdersTarget = prefix + "/OpenOrders";
this->cancelOpenOrdersTarget = prefix + "/CancelAll";
this->getAccountBalancesTarget = prefix + "/Balance";
this->getAccountPositionsTarget = prefix + "/OpenPositions";
this->getWebSocketsTokenTarget = prefix + "/GetWebSocketsToken";
}
virtual ~ExecutionManagementServiceKraken() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl, "{\"reqid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec);
}
bool doesHttpBodyContainError(const Request& request, 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 {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto noncePlusBody = req.base().at("Nonce").to_string() + body;
auto target = path;
if (!queryString.empty()) {
target += queryString;
}
std::string preSignedText = target;
std::string noncePlusBodySha256 = UtilAlgorithm::computeHash(UtilAlgorithm::ShaVersion::SHA256, noncePlusBody);
preSignedText += noncePlusBodySha256;
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA512, UtilAlgorithm::base64Decode(apiSecret), preSignedText));
if (!headerString.empty()) {
headerString += "\r\n";
}
headerString += "API-Sign:" + signature;
}
void signRequest(http::request<http::string_body>& req, const std::string& body, const std::map<std::string, std::string>& credential,
const std::string& nonce) {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto noncePlusBody = nonce + body;
std::string preSignedText = req.target().to_string();
std::string noncePlusBodySha256 = UtilAlgorithm::computeHash(UtilAlgorithm::ShaVersion::SHA256, noncePlusBody);
preSignedText += noncePlusBodySha256;
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA512, UtilAlgorithm::base64Decode(apiSecret), preSignedText));
req.set("API-Sign", signature);
req.body() = body;
req.prepare_payload();
}
void appendParam(std::string& body, const std::map<std::string, std::string>& param, const std::string& nonce,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_EM_ORDER_SIDE, "type"},
{CCAPI_EM_ORDER_QUANTITY, "volume"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "userref"},
{CCAPI_EM_ORDER_TYPE, "ordertype"},
{CCAPI_EM_ORDER_LEVERAGE, "leverage"},
{CCAPI_EM_ORDER_ID, "txid"},
}) {
body += "nonce=";
body += nonce;
body += "&";
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 == "type") {
value = (value == CCAPI_EM_ORDER_SIDE_BUY || value == "buy") ? "buy" : "sell";
}
body += Url::urlEncode(key);
body += "=";
body += Url::urlEncode(value);
body += "&";
}
}
void appendSymbolId(std::string& body, const std::string& symbolId) {
body += "pair=";
body += Url::urlEncode(symbolId);
body += "&";
}
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/x-www-form-urlencoded; charset=utf-8");
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("API-Key", apiKey);
std::string nonce = std::to_string(this->generateNonce(now, request.getIndex()));
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);
std::string body;
this->appendParam(body, param, nonce);
if (param.find(CCAPI_EM_ORDER_TYPE) == param.end() && param.find("ordertype") == param.end()) {
body += "ordertype=limit&";
}
this->appendSymbolId(body, symbolId);
body.pop_back();
this->signRequest(req, body, credential, nonce);
} break;
case Request::Operation::CANCEL_ORDER: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->cancelOrderTarget);
std::string body;
this->appendParam(body, param, nonce,
{
{CCAPI_EM_CLIENT_ORDER_ID, "txid"},
{CCAPI_EM_ORDER_ID, "txid"},
});
body.pop_back();
this->signRequest(req, body, credential, nonce);
} break;
case Request::Operation::GET_ORDER: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->getOrderTarget);
std::string body;
this->appendParam(body, param, nonce);
body.pop_back();
this->signRequest(req, body, credential, nonce);
} break;
case Request::Operation::GET_OPEN_ORDERS: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->getOpenOrdersTarget);
std::string body;
this->appendParam(body, param, nonce);
body.pop_back();
this->signRequest(req, body, credential, nonce);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->cancelOpenOrdersTarget);
std::string body;
this->appendParam(body, param, nonce);
body.pop_back();
this->signRequest(req, body, credential, nonce);
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->getAccountBalancesTarget);
std::string body;
this->appendParam(body, param, nonce);
body.pop_back();
this->signRequest(req, body, credential, nonce);
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->getAccountPositionsTarget);
std::string body;
this->appendParam(body, param, nonce);
body.pop_back();
this->signRequest(req, body, credential, nonce);
} 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_CLIENT_ORDER_ID, std::make_pair("userref", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("vol", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("vol_exec", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
};
if (operation == Request::Operation::CREATE_ORDER) {
for (const auto& x : document["result"]["txid"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ORDER_ID, x.GetString());
elementList.emplace_back(std::move(element));
}
} else if (operation == Request::Operation::GET_ORDER || operation == Request::Operation::GET_OPEN_ORDERS) {
const rj::Value& orders = operation == Request::Operation::GET_ORDER ? document["result"] : document["result"]["open"];
for (auto itr = orders.MemberBegin(); itr != orders.MemberEnd(); ++itr) {
Element element;
this->extractOrderInfo(element, itr->value, extractionFieldNameMap);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionMoreFieldNameMap = {
{CCAPI_EM_ORDER_SIDE, std::make_pair("type", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("pair", JsonDataType::STRING)}};
this->extractOrderInfo(element, itr->value["descr"], extractionMoreFieldNameMap);
auto it1 = itr->value.FindMember("vol_exec");
auto it2 = itr->value.FindMember("price");
if (it1 != itr->value.MemberEnd() && it2 != itr->value.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
}
element.insert(CCAPI_EM_ORDER_ID, itr->name.GetString());
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: {
auto resultItr = document.FindMember("result");
if (resultItr != document.MemberEnd()) {
const rj::Value& result = resultItr->value;
for (auto itr = result.MemberBegin(); itr != result.MemberEnd(); ++itr) {
Element element;
element.insert(CCAPI_EM_ASSET, itr->name.GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, itr->value.GetString());
elementList.emplace_back(std::move(element));
}
}
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
auto resultItr = document.FindMember("result");
if (resultItr != document.MemberEnd()) {
const rj::Value& result = resultItr->value;
for (auto itr = result.MemberBegin(); itr != result.MemberEnd(); ++itr) {
Element element;
element.insert(CCAPI_INSTRUMENT, itr->value["pair"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY,
Decimal(itr->value["vol"].GetString()).subtract(Decimal(itr->value["vol_closed"].GetString())).toString());
element.insert(CCAPI_EM_POSITION_COST, itr->value["cost"].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);
std::string target = this->getWebSocketsTokenTarget;
req.target(target);
auto credential = wsConnection.subscriptionList.at(0).getCredential();
if (credential.empty()) {
credential = this->credentialDefault;
}
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("API-Key", apiKey);
req.set(beast::http::field::content_type, "application/x-www-form-urlencoded; charset=utf-8");
std::string body;
std::string nonce = std::to_string(this->generateNonce(now));
this->appendParam(body, {}, nonce);
body.pop_back();
this->signRequest(req, body, credential, nonce);
this->sendRequest(
req,
[wsConnection, that = shared_from_base<ExecutionManagementServiceKraken>()](const beast::error_code& ec) {
WsConnection thisWsConnection = wsConnection;
that->onFail_(thisWsConnection);
},
[wsConnection, that = shared_from_base<ExecutionManagementServiceKraken>()](const http::response<http::string_body>& res) {
WsConnection thisWsConnection = wsConnection;
int statusCode = res.result_int();
std::string body = res.body();
if (statusCode / 100 == 2) {
try {
rj::Document document;
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;
that->connect(thisWsConnection);
that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({
{"token", token},
});
}
return;
} catch (const std::runtime_error& e) {
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
}
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
const auto& fieldSet = subscription.getFieldSet();
std::vector<std::string> sendStringList;
for (const auto& field : fieldSet) {
std::string name;
if (field == CCAPI_EM_ORDER_UPDATE) {
name = "openOrders";
} else if (field == CCAPI_EM_PRIVATE_TRADE) {
name = "ownTrades";
}
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
rj::Value subscription(rj::kObjectType);
subscription.AddMember("name", rj::Value(name.c_str(), allocator).Move(), allocator);
subscription.AddMember("token", rj::Value(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("token").c_str(), allocator).Move(), allocator);
document.AddMember("subscription", subscription, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
}
return sendStringList;
}
void 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 event;
std::vector<Message> messageList;
if (document.IsArray() && document.Size() == 3) {
std::string channelName = document[1].GetString();
if (channelName == "ownTrades" || channelName == "openOrders") {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
if (channelName == "ownTrades" && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
for (const auto& x : document[0].GetArray()) {
for (auto itr = x.MemberBegin(); itr != x.MemberEnd(); ++itr) {
std::string instrument = itr->value["pair"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
Message message;
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
auto timePair = UtilTime::divide(std::string(itr->value["time"].GetString()));
auto tp = TimePoint(std::chrono::duration<int64_t>(timePair.first));
tp += std::chrono::nanoseconds(timePair.second);
message.setTime(tp);
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, itr->value["price"].GetString());
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, itr->value["vol"].GetString());
element.insert(CCAPI_EM_ORDER_SIDE, std::string(itr->value["type"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_EM_ORDER_ID, std::string(itr->value["ordertxid"].GetString()));
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(itr->value["fee"].GetString()));
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
}
if (channelName == "openOrders" && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
Message message;
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
message.setTime(timeReceived);
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
std::vector<Element> elementList;
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("userref", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("vol", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("vol_exec", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
};
for (const auto& x : document[0].GetArray()) {
for (auto itr = x.MemberBegin(); itr != x.MemberEnd(); ++itr) {
if (itr->value.HasMember("descr")) {
const rj::Value& descr = itr->value["descr"];
std::string instrument = descr["pair"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
Element element;
this->extractOrderInfo(element, itr->value, extractionFieldNameMap);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionMoreFieldNameMap = {
{CCAPI_EM_ORDER_SIDE, std::make_pair("type", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("pair", JsonDataType::STRING)}};
this->extractOrderInfo(element, descr, extractionMoreFieldNameMap);
auto it1 = itr->value.FindMember("vol_exec");
auto it2 = itr->value.FindMember("avg_price");
if (it1 != itr->value.MemberEnd() && it2 != itr->value.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
}
element.insert(CCAPI_EM_ORDER_ID, itr->name.GetString());
elementList.emplace_back(std::move(element));
}
} else {
Element element;
this->extractOrderInfo(element, itr->value, extractionFieldNameMap);
auto it1 = itr->value.FindMember("vol_exec");
auto it2 = itr->value.FindMember("avg_price");
if (it1 != itr->value.MemberEnd() && it2 != itr->value.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
}
element.insert(CCAPI_EM_ORDER_ID, itr->name.GetString());
elementList.emplace_back(std::move(element));
}
}
}
if (!elementList.empty()) {
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
} else if (document.IsObject() && document.HasMember("event")) {
std::string eventPayload = std::string(document["event"].GetString());
if (eventPayload == "heartbeat") {
} else if (eventPayload == "subscriptionStatus") {
std::string status = document["status"].GetString();
if (status == "subscribed" || status == "error") {
event.setType(Event::Type::SUBSCRIPTION_STATUS);
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setType(status == "subscribed" ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(status == "subscribed" ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
}
}
}
event.setMessageList(messageList);
return event;
}
std::string getWebSocketsTokenTarget;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KRAKEN_H_
@@ -0,0 +1,407 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KRAKEN_FUTURES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KRAKEN_FUTURES_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN_FUTURES
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
#include "openssl/evp.h"
namespace ccapi {
class ExecutionManagementServiceKrakenFutures : public ExecutionManagementService {
public:
ExecutionManagementServiceKrakenFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v1";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_KRAKEN_FUTURES_API_KEY;
this->apiSecretName = CCAPI_KRAKEN_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
std::string prefix("/derivatives/api/v3");
std::string prefix_2("/api/v3");
this->createOrderTarget = prefix + "/sendorder";
this->createOrderPath = prefix_2 + "/sendorder";
this->cancelOrderTarget = prefix + "/cancelorder";
this->cancelOrderPath = prefix_2 + "/cancelorder";
this->getOpenOrdersTarget = prefix + "/openorders";
this->getOpenOrdersPath = prefix_2 + "/openorders";
this->cancelOpenOrdersTarget = prefix + "/cancelallorders";
this->cancelOpenOrdersPath = prefix_2 + "/cancelallorders";
this->getAccountsTarget = prefix + "/accounts";
this->getAccountsPath = prefix_2 + "/accounts";
this->getAccountPositionsTarget = prefix + "/openpositions";
this->getAccountPositionsPath = prefix_2 + "/openpositions";
}
virtual ~ExecutionManagementServiceKrakenFutures() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
bool doesHttpBodyContainError(const Request& request, 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 {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string preSignedText = queryString;
preSignedText += req.base().at("Nonce").to_string();
;
preSignedText += path;
std::string preSignedTextSha256 = UtilAlgorithm::computeHash(UtilAlgorithm::ShaVersion::SHA256, preSignedText);
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA512, UtilAlgorithm::base64Decode(apiSecret), preSignedTextSha256));
if (!headerString.empty()) {
headerString += "\r\n";
}
headerString += "Authent:" + signature;
}
void signRequest(http::request<http::string_body>& req, const std::string& path, const std::string& postData,
const std::map<std::string, std::string>& credential, const std::string& nonce) {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string preSignedText = postData;
preSignedText += nonce;
preSignedText += path;
std::string preSignedTextSha256 = UtilAlgorithm::computeHash(UtilAlgorithm::ShaVersion::SHA256, preSignedText);
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA512, UtilAlgorithm::base64Decode(apiSecret), preSignedTextSha256));
req.set("Authent", signature);
}
std::string generateNonce(const TimePoint& now, int requestIndex) {
int64_t nonce = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count() + requestIndex;
return std::to_string(nonce);
}
void appendParam(std::string& postData, 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, "limitPrice"},
{CCAPI_EM_ORDER_ID, "order_id"},
{CCAPI_EM_CLIENT_ORDER_ID, "cliOrdId"},
{CCAPI_EM_ORDER_TYPE, "orderType"},
}) {
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";
}
postData += Url::urlEncode(key);
postData += "=";
postData += Url::urlEncode(value);
postData += "&";
}
}
void appendSymbolId(std::string& postData, const std::string& symbolId) {
postData += "symbol=";
postData += Url::urlEncode(symbolId);
postData += "&";
}
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 {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("APIKey", apiKey);
std::string nonce = this->generateNonce(now, request.getIndex());
req.set("Nonce", nonce);
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();
std::string postData;
this->appendParam(postData, param);
if (param.find(CCAPI_EM_ORDER_TYPE) == param.end() && param.find("orderType") == param.end()) {
postData += "orderType=lmt&";
}
this->appendSymbolId(postData, symbolId);
postData.pop_back();
req.target(this->createOrderTarget + "?" + postData);
this->signRequest(req, this->createOrderPath, postData, credential, nonce);
} break;
case Request::Operation::CANCEL_ORDER: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
std::string postData;
this->appendParam(postData, param);
postData.pop_back();
req.target(this->cancelOrderTarget + "?" + postData);
this->signRequest(req, this->cancelOrderPath, postData, credential, nonce);
} break;
case Request::Operation::GET_OPEN_ORDERS: {
req.method(http::verb::post);
std::string postData;
req.target(this->getOpenOrdersTarget);
this->signRequest(req, this->getOpenOrdersPath, postData, credential, nonce);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
req.method(http::verb::post);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
std::string postData;
if (!symbolId.empty()) {
this->appendSymbolId(postData, symbolId);
postData.pop_back();
}
if (!postData.empty()) {
req.target(this->cancelOpenOrdersTarget + "?" + postData);
} else {
req.target(this->cancelOpenOrdersTarget);
}
this->signRequest(req, this->cancelOpenOrdersPath, postData, credential, nonce);
} break;
case Request::Operation::GET_ACCOUNTS: {
req.method(http::verb::post);
std::string postData;
req.target(this->getAccountsTarget);
this->signRequest(req, this->getAccountsPath, postData, credential, nonce);
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
req.method(http::verb::post);
std::string postData;
req.target(this->getAccountPositionsTarget);
this->signRequest(req, this->getAccountPositionsPath, postData, credential, nonce);
} 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("cliOrdId", 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("limitPrice", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filled", JsonDataType::STRING)},
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("unfilledSize", 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::CREATE_ORDER || operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
const rj::Value& sendStatus = document[operation == Request::Operation::CREATE_ORDER ? "sendStatus" : "cancelStatus"];
if (sendStatus.FindMember("orderEvents") != sendStatus.MemberEnd()) {
for (const auto& x : sendStatus["orderEvents"].GetArray()) {
Element element;
this->extractOrderInfo(element, x["order"], extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
} else {
Element element;
element.insert(CCAPI_EM_ORDER_STATUS, sendStatus["status"].GetString());
elementList.emplace_back(std::move(element));
}
} else if (operation == Request::Operation::GET_OPEN_ORDERS) {
for (const auto& x : document["openOrders"].GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
if (element.getValue(CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY).empty()) {
auto it = x.FindMember("filledSize");
if (it != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, it->value.GetString());
}
}
if (element.getValue(CCAPI_EM_ORDER_ID).empty()) {
auto it = x.FindMember("order_id");
if (it != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_ID, it->value.GetString());
}
}
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_ACCOUNTS: {
auto resultItr = document.FindMember("accounts");
if (resultItr != document.MemberEnd()) {
const rj::Value& result = resultItr->value;
for (auto itr = result.MemberBegin(); itr != result.MemberEnd(); ++itr) {
std::string id = itr->name.GetString();
const rj::Value& result_2 = itr->value;
std::string type = result_2["type"].GetString();
for (auto itr_2 = result_2["balances"].MemberBegin(); itr_2 != result_2["balances"].MemberEnd(); ++itr_2) {
Element element;
element.insert(CCAPI_EM_ACCOUNT_ID, id);
element.insert(CCAPI_EM_ACCOUNT_TYPE, type);
element.insert(CCAPI_EM_ASSET, itr_2->name.GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, itr_2->value.GetString());
elementList.emplace_back(std::move(element));
}
}
}
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
for (const auto& x : document["openPositions"].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_COST,
Decimal(UtilString::printDoubleScientific(std::stod(x["price"].GetString()) * std::stod(x["size"].GetString()))).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("event", rj::Value("challenge").Move(), allocator);
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
document.AddMember("api_key", rj::Value(apiKey.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(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
const TimePoint& timeReceived) override {
Event event = this->createEvent(wsConnection.hdl, subscription, textMessage, document, timeReceived);
if (!event.getMessageList().empty()) {
this->eventHandler(event, nullptr);
}
}
Event createEvent(wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, const rj::Document& document,
const TimePoint& timeReceived) {
Event event;
std::vector<Message> messageList;
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()) {
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_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));
}
}
}
}
} else {
std::string eventType = document["event"].GetString();
if (eventType == "challenge") {
auto credential = subscription.getCredential();
if (credential.empty()) {
credential = this->credentialDefault;
}
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string challengeToSign = document["message"].GetString();
std::string challengeToSignSha256 = UtilAlgorithm::computeHash(UtilAlgorithm::ShaVersion::SHA256, challengeToSign);
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";
}
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;
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 (eventType == "subscribed" || eventType == "error") {
event.setType(Event::Type::SUBSCRIPTION_STATUS);
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setType(eventType == "subscribed" ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(eventType == "subscribed" ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
}
}
event.setMessageList(messageList);
return event;
}
std::string createOrderPath;
std::string cancelOrderPath;
std::string getOpenOrdersPath;
std::string cancelOpenOrdersPath;
std::string getAccountsPath;
std::string getAccountPositionsPath;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KRAKEN_FUTURES_H_
@@ -0,0 +1,483 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_H_
#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"
namespace ccapi {
class ExecutionManagementServiceKucoin : public ExecutionManagementService {
public:
ExecutionManagementServiceKucoin(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(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 {
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_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->createOrderTarget = "/api/v1/orders";
this->cancelOrderTarget = "/api/v1/orders/<id>";
this->getOrderTarget = "/api/v1/orders/<id>";
this->getOpenOrdersTarget = "/api/v1/orders";
this->cancelOpenOrdersTarget = "/api/v1/orders";
this->getAccountsTarget = "/api/v1/accounts";
this->getAccountBalancesTarget = "/api/v1/accounts/<accountId>";
}
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"];
switch (request.getOperation()) {
case Request::Operation::GET_ACCOUNTS: {
for (const auto& x : data.GetArray()) {
Element element;
element.insert(CCAPI_EM_ACCOUNT_ID, x["id"].GetString());
element.insert(CCAPI_EM_ACCOUNT_TYPE, x["type"].GetString());
element.insert(CCAPI_EM_ASSET, x["currency"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["balance"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["available"].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["balance"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, data["available"].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 = "/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
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_H_
@@ -0,0 +1,479 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_KUCOIN_FUTURES_H_
#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"
namespace ccapi {
class ExecutionManagementServiceKucoinFutures : public ExecutionManagementService {
public:
ExecutionManagementServiceKucoinFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(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 {
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_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";
}
virtual ~ExecutionManagementServiceKrakenFutures() {}
#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_AVAILABLE_FOR_TRADING, data["availableBalance"].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_
@@ -0,0 +1,511 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKEX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKEX_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_OKEX
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceOkex : public ExecutionManagementService {
public:
ExecutionManagementServiceOkex(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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
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;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName, this->apiXSimulatedTradingName});
this->createOrderTarget = "/api/v5/trade/order";
this->cancelOrderTarget = "/api/v5/trade/cancel-order";
this->getOrderTarget = "/api/v5/trade/order";
this->getOpenOrdersTarget = "/api/v5/trade/orders-pending";
this->getAccountBalancesTarget = "/api/v5/account/balance";
this->getAccountPositionsTarget = "/api/v5/account/positions";
}
virtual ~ExecutionManagementServiceOkex() {}
#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 Request& request, 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 {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("OK-ACCESS-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 += "OK-ACCESS-SIGN:" + signature;
}
void signRequest(http::request<http::string_body>& req, const std::string& body, const std::map<std::string, std::string>& credential) {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("OK-ACCESS-TIMESTAMP").to_string();
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("OK-ACCESS-SIGN", signature);
req.body() = body;
req.prepare_payload();
}
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, "sz"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "px"},
{CCAPI_EM_CLIENT_ORDER_ID, "clOrdId"},
{CCAPI_SYMBOL_ID, "instId"},
{CCAPI_EM_ORDER_ID, "ordId"},
}) {
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 = {}) {
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("instId", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
void appendSymbolId(std::string& queryString, const std::string& symbolId) {
queryString += "instId=";
queryString += Url::urlEncode(symbolId);
queryString += "&";
}
void convertRequestForRest(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
req.set(beast::http::field::content_type, "application/json");
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("OK-ACCESS-KEY", apiKey);
std::string timeStr = UtilTime::getISOTimestamp(now);
req.set("OK-ACCESS-TIMESTAMP", timeStr.substr(0, timeStr.length() - 7) + "Z");
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
req.set("OK-ACCESS-PASSPHRASE", apiPassphrase);
auto apiXSimulatedTrading = mapGetWithDefault(credential, this->apiXSimulatedTradingName);
if (apiXSimulatedTrading == "1") {
req.set("x-simulated-trading", "1");
}
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.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(document, allocator, param);
if (param.find("tdMode") == param.end()) {
document.AddMember("tdMode", rj::Value("cash").Move(), allocator);
}
if (param.find("ordType") == param.end()) {
document.AddMember("ordType", 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();
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(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, "instId"},
});
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, "instId"},
});
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 convertRequestForWebsocket(rj::Document& document, rj::Document::AllocatorType& allocator, const WsConnection& wsConnection, const Request& request,
int wsRequestId, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
document.SetObject();
document.AddMember("id", rj::Value(std::to_string(wsRequestId).c_str(), allocator).Move(), allocator);
switch (request.getOperation()) {
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);
if (param.find("tdMode") == param.end()) {
arg.AddMember("tdMode", rj::Value("cash").Move(), allocator);
}
if (param.find("ordType") == param.end()) {
arg.AddMember("ordType", rj::Value("limit").Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(arg, allocator, symbolId);
}
args.PushBack(arg, allocator);
document.AddMember("args", args, allocator);
} break;
case Request::Operation::CANCEL_ORDER: {
document.AddMember("op", rj::Value("cancel-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);
if (!symbolId.empty()) {
this->appendSymbolId(arg, allocator, symbolId);
}
args.PushBack(arg, allocator);
document.AddMember("args", args, allocator);
} break;
default:
this->convertRequestForWebsocketCustom(document, allocator, wsConnection, request, wsRequestId, now, symbolId, credential);
}
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
this->extractOrderInfoFromRequest(elementList, document);
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const rj::Document& document) {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{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("instId", 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["instId"].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_COST, std::to_string(std::stod(x["avgPx"].GetString()) * std::stod(positionQuantity)));
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, std::to_string(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 rj::Document& document,
const TimePoint& timeReceived) override {
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("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);
message.setCorrelationIdList({subscription.getCorrelationId()});
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});
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);
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["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()) {
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));
}
}
} 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));
}
}
}
}
} 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 apiPassphraseName;
std::string apiXSimulatedTradingName;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_OKEX_H_
@@ -0,0 +1,597 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_H_
#ifdef CCAPI_ENABLE_SERVICE_FIX
#include "ccapi_cpp/service/ccapi_service.h"
#include "hffix.hpp"
namespace hff = hffix;
namespace ccapi {
template <class T>
class FixService : public Service {
public:
FixService(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: Service(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~FixService() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
static std::string printableString(const char* s, size_t n) {
std::string output(s, n);
std::replace(output.begin(), output.end(), '\x01', '^');
return output;
}
static std::string printableString(const std::string& s) {
std::string output(s);
std::replace(output.begin(), output.end(), '\x01', '^');
return output;
}
void setHostFixFromUrlFix(std::string& aHostFix, std::string& aPortFix, const std::string& baseUrlFix) {
auto hostPort = this->extractHostFromUrl(baseUrlFix);
aHostFix = hostPort.first;
aPortFix = hostPort.second;
}
void subscribeByFix(Subscription& subscription) override {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_DEBUG("this->baseUrlFix = " + this->baseUrlFix);
if (this->shouldContinue.load()) {
wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), [that = shared_from_base<FixService>(), subscription]() {
auto now = UtilTime::now();
auto thatSubscription = subscription;
thatSubscription.setTimeSent(now);
that->connect(thatSubscription);
});
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void onFail(std::shared_ptr<FixConnection<T>> fixConnectionPtr, const std::string& errorMessage) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_ERROR("errorMessage = " + errorMessage);
this->clearStates(fixConnectionPtr);
this->onFail_(fixConnectionPtr, errorMessage);
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void onFail(std::shared_ptr<FixConnection<T>> fixConnectionPtr, const ErrorCode& ec, const std::string& what) {
CCAPI_LOGGER_FUNCTION_ENTER;
this->onFail(fixConnectionPtr, what + ": " + ec.message() + ", category: " + ec.category().name());
CCAPI_LOGGER_FUNCTION_EXIT;
}
void clearStates(std::shared_ptr<FixConnection<T>> fixConnectionPtr) {
CCAPI_LOGGER_INFO("clear states for fixConnectionPtr " + toString(*fixConnectionPtr));
auto& connectionId = fixConnectionPtr->id;
this->readMessageBufferByConnectionIdMap.erase(connectionId);
this->readMessageBufferReadLengthByConnectionIdMap.erase(connectionId);
this->writeMessageBufferByConnectionIdMap.erase(connectionId);
this->writeMessageBufferWrittenLengthByConnectionIdMap.erase(connectionId);
this->fixConnectionPtrByIdMap.erase(connectionId);
this->sequenceSentByConnectionIdMap.erase(connectionId);
this->credentialByConnectionIdMap.erase(connectionId);
auto urlBase = fixConnectionPtr->url;
this->connectNumRetryOnFailByConnectionUrlMap.erase(urlBase);
}
void onFail_(std::shared_ptr<FixConnection<T>> fixConnectionPtr, const std::string& errorMessage) {
fixConnectionPtr->status = FixConnection<T>::Status::FAILED;
this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, errorMessage, {fixConnectionPtr->subscription.getCorrelationId()});
auto urlBase = fixConnectionPtr->url;
CCAPI_LOGGER_TRACE("urlBase = " + urlBase);
CCAPI_LOGGER_TRACE("this->connectNumRetryOnFailByConnectionUrlMap = " + toString(this->connectNumRetryOnFailByConnectionUrlMap));
long seconds = std::round(UtilAlgorithm::exponentialBackoff(1, 1, 2, std::min(this->connectNumRetryOnFailByConnectionUrlMap[urlBase], 6)));
CCAPI_LOGGER_INFO("about to set timer for " + toString(seconds) + " seconds");
if (this->connectRetryOnFailTimerByConnectionIdMap.find(fixConnectionPtr->id) != this->connectRetryOnFailTimerByConnectionIdMap.end()) {
this->connectRetryOnFailTimerByConnectionIdMap.at(fixConnectionPtr->id)->cancel();
}
this->connectRetryOnFailTimerByConnectionIdMap[fixConnectionPtr->id] = this->serviceContextPtr->tlsClientPtr->set_timer(
seconds * 1000, [fixConnectionPtr, that = shared_from_base<FixService>(), urlBase](ErrorCode const& ec) {
if (that->fixConnectionPtrByIdMap.find(fixConnectionPtr->id) == that->fixConnectionPtrByIdMap.end()) {
if (ec) {
CCAPI_LOGGER_ERROR("fixConnectionPtr = " + toString(*fixConnectionPtr) + ", connect retry on fail timer error: " + ec.message());
that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
} else {
CCAPI_LOGGER_INFO("about to retry");
that->connect(fixConnectionPtr->subscription);
that->connectNumRetryOnFailByConnectionUrlMap[urlBase] += 1;
}
}
});
}
std::shared_ptr<T> createStreamFix(std::shared_ptr<net::io_context> iocPtr, std::shared_ptr<net::ssl::context> ctxPtr, const std::string& host);
void connect(Subscription& subscription) {
std::string aHostFix = this->hostFix;
std::string aPortFix = this->portFix;
std::string field = subscription.getField();
if (field == CCAPI_FIX_MARKET_DATA) {
aHostFix = this->hostFixMarketData;
aPortFix = this->portFixMarketData;
} else if (field == CCAPI_FIX_EXECUTION_MANAGEMENT) {
aHostFix = this->hostFixExecutionManagement;
aPortFix = this->portFixExecutionManagement;
}
std::shared_ptr<T> streamPtr(nullptr);
try {
streamPtr = this->createStreamFix(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr, aHostFix);
} catch (const beast::error_code& ec) {
CCAPI_LOGGER_TRACE("fail");
this->onError(Event::Type::FIX_STATUS, Message::Type::FIX_FAILURE, ec, "create stream", {subscription.getCorrelationId()});
return;
}
std::shared_ptr<FixConnection<T>> fixConnectionPtr(new FixConnection<T>(aHostFix, aPortFix, subscription, streamPtr));
fixConnectionPtr->status = FixConnection<T>::Status::CONNECTING;
CCAPI_LOGGER_TRACE("before async_connect");
T& stream = *streamPtr;
beast::get_lowest_layer(stream).async_connect(field == CCAPI_FIX_MARKET_DATA ? this->tcpResolverResultsFixMarketData
: field == CCAPI_FIX_EXECUTION_MANAGEMENT ? this->tcpResolverResultsFixExecutionManagement
: this->tcpResolverResultsFix,
beast::bind_front_handler(&FixService::onConnect_3, shared_from_base<FixService>(), fixConnectionPtr));
CCAPI_LOGGER_TRACE("after async_connect");
}
void onConnect_3(std::shared_ptr<FixConnection<T>> fixConnectionPtr, beast::error_code ec, tcp::resolver::results_type::endpoint_type) {
// CCAPI_LOGGER_TRACE("async_connect callback start");
// auto now = UtilTime::now();
// if (ec) {
// CCAPI_LOGGER_TRACE("fail");
// this->onFail(fixConnectionPtr, ec, "connect");
// return;
// }
// CCAPI_LOGGER_TRACE("fixConnectionPtr = " + toString(*fixConnectionPtr));
// CCAPI_LOGGER_TRACE("connected");
// T& stream = *fixConnectionPtr->streamPtr;
// if (this->useSsl) {
// CCAPI_LOGGER_TRACE("before async_handshake");
// stream.async_handshake(ssl::stream_base::client, beast::bind_front_handler(&FixService::onHandshake_3, shared_from_base<FixService>(),
// fixConnectionPtr)); CCAPI_LOGGER_TRACE("after async_handshake");
// } else {
// this->start(fixConnectionPtr);
// }
}
void onHandshake_3(std::shared_ptr<FixConnection<T>> fixConnectionPtr, beast::error_code ec) {
CCAPI_LOGGER_TRACE("async_handshake callback start");
auto now = UtilTime::now();
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onFail(fixConnectionPtr, ec, "handshake");
return;
}
CCAPI_LOGGER_TRACE("handshaked");
this->start(fixConnectionPtr, now);
}
void start(std::shared_ptr<FixConnection<T>> fixConnectionPtr, const TimePoint& now) {
auto& connectionId = fixConnectionPtr->id;
fixConnectionPtr->status = FixConnection<T>::Status::OPEN;
CCAPI_LOGGER_INFO("connection " + toString(*fixConnectionPtr) + " established");
this->connectNumRetryOnFailByConnectionUrlMap[fixConnectionPtr->url] = 0;
{
Event event;
event.setType(Event::Type::SESSION_STATUS);
Message message;
message.setTimeReceived(now);
message.setType(Message::Type::SESSION_CONNECTION_UP);
message.setCorrelationIdList({fixConnectionPtr->subscription.getCorrelationId()});
Element element(true);
element.insert(CCAPI_CONNECTION_ID, connectionId);
message.setElementList({element});
event.setMessageList({message});
this->eventHandler(event, nullptr);
}
this->fixConnectionPtrByIdMap.insert({connectionId, fixConnectionPtr});
auto nowFixTimeStr = UtilTime::convertTimePointToFIXTime(now);
auto credential = fixConnectionPtr->subscription.getCredential();
if (credential.empty()) {
credential = this->credentialDefault;
}
this->credentialByConnectionIdMap[connectionId] = credential;
auto& readMessageBuffer = this->readMessageBufferByConnectionIdMap[connectionId];
auto& readMessageBufferReadLength = this->readMessageBufferReadLengthByConnectionIdMap[connectionId];
CCAPI_LOGGER_TRACE("about to start read");
CCAPI_LOGGER_TRACE("readMessageBufferReadLength = " + toString(readMessageBufferReadLength));
this->startRead_3(fixConnectionPtr, readMessageBuffer.data() + readMessageBufferReadLength,
std::min(readMessageBuffer.size() - readMessageBufferReadLength, this->readMessageChunkSize));
std::map<int, std::string> logonOptionMap;
for (const auto& x : fixConnectionPtr->subscription.getOptionMap()) {
if (UtilString::isNumber(x.first)) {
logonOptionMap.insert({std::stoi(x.first), x.second});
}
}
auto param = this->createLogonParam(connectionId, nowFixTimeStr, logonOptionMap);
this->writeMessage(fixConnectionPtr, nowFixTimeStr, {param});
}
void startRead_3(std::shared_ptr<FixConnection<T>> fixConnectionPtr, void* data, size_t requestedNumBytesToRead) {
T& stream = *fixConnectionPtr->streamPtr;
CCAPI_LOGGER_TRACE("before async_read");
CCAPI_LOGGER_TRACE("requestedNumBytesToRead = " + toString(requestedNumBytesToRead));
stream.async_read_some(boost::asio::buffer(data, requestedNumBytesToRead),
beast::bind_front_handler(&FixService::onRead_3, shared_from_base<FixService>(), fixConnectionPtr));
CCAPI_LOGGER_TRACE("after async_read");
}
void onRead_3(std::shared_ptr<FixConnection<T>> fixConnectionPtr, const boost::system::error_code& ec, std::size_t n) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_TRACE("n = " + toString(n));
auto now = UtilTime::now();
auto nowFixTimeStr = UtilTime::convertTimePointToFIXTime(now);
if (ec) {
CCAPI_LOGGER_TRACE("fail");
Event event;
event.setType(Event::Type::SESSION_STATUS);
Message message;
message.setTimeReceived(now);
message.setType(Message::Type::SESSION_CONNECTION_DOWN);
message.setCorrelationIdList({fixConnectionPtr->subscription.getCorrelationId()});
Element element(true);
auto& connectionId = fixConnectionPtr->id;
element.insert(CCAPI_CONNECTION_ID, connectionId);
message.setElementList({element});
event.setMessageList({message});
this->eventHandler(event, nullptr);
this->onFail(fixConnectionPtr, ec, "read");
return;
}
if (fixConnectionPtr->status != FixConnection<T>::Status::OPEN) {
CCAPI_LOGGER_WARN("should not process remaining message on closing");
return;
}
auto& connectionId = fixConnectionPtr->id;
auto& readMessageBuffer = this->readMessageBufferByConnectionIdMap[connectionId];
auto& readMessageBufferReadLength = this->readMessageBufferReadLengthByConnectionIdMap[connectionId];
readMessageBufferReadLength += n;
CCAPI_LOGGER_TRACE("readMessageBufferReadLength = " + toString(readMessageBufferReadLength));
hff::message_reader reader(readMessageBuffer.data(), readMessageBuffer.data() + readMessageBufferReadLength);
std::vector<std::string> correlationIdList{fixConnectionPtr->subscription.getCorrelationId()};
for (; reader.is_complete(); reader = reader.next_message_reader()) {
Event event;
bool shouldEmitEvent = true;
Message message;
Element element(true);
message.setTimeReceived(now);
message.setCorrelationIdList(correlationIdList);
if (reader.is_valid()) {
try {
CCAPI_LOGGER_DEBUG("received " + printableString(reader.message_begin(), reader.message_end() - reader.message_begin()));
auto it = reader.message_type();
auto messageType = it->value().as_string();
CCAPI_LOGGER_DEBUG("received a " + messageType + " message");
element.insert(it->tag(), messageType);
if (messageType == "0") {
shouldEmitEvent = false;
CCAPI_LOGGER_DEBUG("Heartbeat: " + toString(*fixConnectionPtr));
// #ifdef CCAPI_FIX_SERVICE_SHOULD_RESPOND_HEARTBEAT_WITH_HEARTBEAT
// this->writeMessage(fixConnectionPtr, nowFixTimeStr,
// {{
// {hff::tag::MsgType, "0"},
// }});
// #endif
} else if (messageType == "1") {
shouldEmitEvent = false;
CCAPI_LOGGER_DEBUG("Test Request: " + toString(*fixConnectionPtr));
if (reader.find_with_hint(hff::tag::TestReqID, it)) {
this->writeMessage(fixConnectionPtr, nowFixTimeStr,
{{
{hff::tag::MsgType, "0"},
{hff::tag::TestReqID, it->value().as_string()},
}});
}
} else {
it = it + 5;
while (it->tag() != hffix::tag::CheckSum) {
element.insert(it->tag(), it->value().as_string());
++it;
}
if (reader.find_with_hint(hff::tag::MsgSeqNum, it) && it->value().as_string() == "1") {
if (messageType == "A") {
event.setType(Event::Type::AUTHORIZATION_STATUS);
message.setType(Message::Type::AUTHORIZATION_SUCCESS);
this->setPingPongTimer(
PingPongMethod::FIX_PROTOCOL_LEVEL, fixConnectionPtr,
[that = shared_from_base<FixService>()](std::shared_ptr<FixConnection<T>> fixConnectionPtr) {
auto now = UtilTime::now();
auto nowFixTimeStr = UtilTime::convertTimePointToFIXTime(now);
that->writeMessage(
fixConnectionPtr, nowFixTimeStr,
{{
{hff::tag::MsgType, "0"},
},
{
{hff::tag::MsgType, "1"},
{hff::tag::TestReqID, std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count())},
}});
},
true);
} else {
event.setType(Event::Type::AUTHORIZATION_STATUS);
message.setType(Message::Type::AUTHORIZATION_FAILURE);
}
} else {
event.setType(Event::Type::FIX);
message.setType(Message::Type::FIX);
if (messageType == "5") {
this->writeMessage(fixConnectionPtr, nowFixTimeStr,
{{
{hff::tag::MsgType, "5"},
}});
}
}
}
} catch (const std::exception& e) {
std::string errorMessage(std::string("Error reading fields: ") + e.what());
element.insert(CCAPI_ERROR_MESSAGE, errorMessage);
event.setType(Event::Type::FIX_STATUS);
message.setType(Message::Type::GENERIC_ERROR);
}
} else {
std::string errorMessage("Error Invalid FIX message: ");
errorMessage.append(reader.message_begin(), std::min(ssize_t(64), readMessageBuffer.data() + readMessageBufferReadLength - reader.message_begin()));
errorMessage.append("...");
element.insert(CCAPI_ERROR_MESSAGE, errorMessage);
event.setType(Event::Type::FIX_STATUS);
message.setType(Message::Type::GENERIC_ERROR);
}
if (shouldEmitEvent) {
message.setElementList({element});
event.setMessageList({message});
this->eventHandler(event, nullptr);
}
}
readMessageBufferReadLength = reader.buffer_end() - reader.buffer_begin();
if (readMessageBufferReadLength >= this->readMessageChunkSize) {
std::memmove(readMessageBuffer.data(), reader.buffer_begin(), readMessageBufferReadLength);
CCAPI_LOGGER_TRACE("about to start read");
this->startRead_3(fixConnectionPtr, readMessageBuffer.data() + readMessageBufferReadLength,
std::min(readMessageBuffer.size() - readMessageBufferReadLength, this->readMessageChunkSize));
} else {
CCAPI_LOGGER_TRACE("about to start read");
this->startRead_3(fixConnectionPtr, readMessageBuffer.data() + readMessageBufferReadLength,
std::min(readMessageBuffer.size() - readMessageBufferReadLength, this->readMessageChunkSize - readMessageBufferReadLength));
}
this->onPongByMethod(PingPongMethod::FIX_PROTOCOL_LEVEL, fixConnectionPtr, now);
CCAPI_LOGGER_FUNCTION_EXIT;
}
void startWrite_3(std::shared_ptr<FixConnection<T>> fixConnectionPtr, void* data, size_t numBytesToWrite) {
T& stream = *fixConnectionPtr->streamPtr;
CCAPI_LOGGER_TRACE("before async_write");
CCAPI_LOGGER_TRACE("numBytesToWrite = " + toString(numBytesToWrite));
boost::asio::async_write(stream, boost::asio::buffer(data, numBytesToWrite),
beast::bind_front_handler(&FixService::onWrite_3, shared_from_base<FixService>(), fixConnectionPtr));
CCAPI_LOGGER_TRACE("after async_write");
}
void onWrite_3(std::shared_ptr<FixConnection<T>> fixConnectionPtr, const boost::system::error_code& ec, std::size_t n) {
CCAPI_LOGGER_FUNCTION_ENTER;
auto& connectionId = fixConnectionPtr->id;
auto& writeMessageBuffer = this->writeMessageBufferByConnectionIdMap[connectionId];
auto& writeMessageBufferWrittenLength = this->writeMessageBufferWrittenLengthByConnectionIdMap[connectionId];
writeMessageBufferWrittenLength -= n;
CCAPI_LOGGER_TRACE("writeMessageBufferWrittenLength = " + toString(writeMessageBufferWrittenLength));
if (writeMessageBufferWrittenLength > 0) {
std::memmove(writeMessageBuffer.data(), writeMessageBuffer.data() + n, writeMessageBufferWrittenLength);
CCAPI_LOGGER_TRACE("about to start write");
this->startWrite_3(fixConnectionPtr, writeMessageBuffer.data(), writeMessageBufferWrittenLength);
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
void writeMessage(std::shared_ptr<FixConnection<T>> fixConnectionPtr, const std::string& nowFixTimeStr,
const std::vector<std::vector<std::pair<int, std::string>>>& paramList) {
if (fixConnectionPtr->status != FixConnection<T>::Status::OPEN) {
CCAPI_LOGGER_WARN("should write no more messages");
return;
}
auto& connectionId = fixConnectionPtr->id;
auto& writeMessageBuffer = this->writeMessageBufferByConnectionIdMap[connectionId];
auto& writeMessageBufferWrittenLength = this->writeMessageBufferWrittenLengthByConnectionIdMap[connectionId];
size_t n = 0;
for (const auto& param : paramList) {
auto commonParam = this->createCommonParam(connectionId, nowFixTimeStr);
hff::message_writer messageWriter(writeMessageBuffer.data() + n, writeMessageBuffer.data() + writeMessageBuffer.size());
messageWriter.push_back_header(this->protocolVersion.c_str());
auto it = param.begin();
if (it != param.end()) {
messageWriter.push_back_string(it->first, it->second);
for (const auto& x : commonParam) {
messageWriter.push_back_string(x.first, x.second);
}
++it;
while (it != param.end()) {
messageWriter.push_back_string(it->first, it->second);
++it;
}
}
messageWriter.push_back_trailer();
n += messageWriter.message_end() - messageWriter.message_begin();
}
CCAPI_LOGGER_DEBUG("about to send " + printableString(writeMessageBuffer.data(), n));
if (writeMessageBufferWrittenLength == 0) {
CCAPI_LOGGER_TRACE("about to start write");
this->startWrite_3(fixConnectionPtr, writeMessageBuffer.data(), n);
}
writeMessageBufferWrittenLength += n;
}
void onPongByMethod(PingPongMethod method, std::shared_ptr<FixConnection<T>> fixConnectionPtr, const TimePoint& timeReceived) {
CCAPI_LOGGER_FUNCTION_ENTER;
this->lastPongTpByMethodByConnectionIdMap[fixConnectionPtr->id][method] = timeReceived;
CCAPI_LOGGER_FUNCTION_EXIT;
}
void sendRequestByFix(Request& request, const TimePoint& now) override {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_TRACE("now = " + toString(now));
wspp::lib::asio::post(this->serviceContextPtr->tlsClientPtr->get_io_service(), [that = shared_from_base<FixService>(), 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& connectionId = request.getCorrelationId();
auto it = that->fixConnectionPtrByIdMap.find(connectionId);
if (it == that->fixConnectionPtrByIdMap.end()) {
Event event;
event.setType(Event::Type::FIX_STATUS);
Message message;
message.setTimeReceived(now);
message.setType(Message::Type::FIX_FAILURE);
message.setCorrelationIdList({request.getCorrelationId()});
Element element(true);
element.insert(CCAPI_ERROR_MESSAGE, "FIX connection was not found");
message.setElementList({element});
event.setMessageList({message});
that->eventHandler(event, nullptr);
return;
}
auto& fixConnectionPtr = it->second;
CCAPI_LOGGER_TRACE("fixConnectionPtr = " + toString(*fixConnectionPtr));
that->writeMessage(fixConnectionPtr, nowFixTimeStr, request.getParamListFix());
});
CCAPI_LOGGER_FUNCTION_EXIT;
}
void setPingPongTimer(PingPongMethod method, std::shared_ptr<FixConnection<T>> fixConnectionPtr,
std::function<void(std::shared_ptr<FixConnection<T>>)> pingMethod, bool pingNow = false) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_TRACE("method = " + pingPongMethodToString(method));
auto pingIntervalMilliSeconds = this->pingIntervalMilliSecondsByMethodMap[method];
auto pongTimeoutMilliSeconds = this->pongTimeoutMilliSecondsByMethodMap[method];
CCAPI_LOGGER_TRACE("pingIntervalMilliSeconds = " + toString(pingIntervalMilliSeconds));
CCAPI_LOGGER_TRACE("pongTimeoutMilliSeconds = " + toString(pongTimeoutMilliSeconds));
if (pingIntervalMilliSeconds <= pongTimeoutMilliSeconds) {
return;
}
if (fixConnectionPtr->status == FixConnection<T>::Status::OPEN) {
if (pingNow) {
pingMethod(fixConnectionPtr);
}
if (this->pingTimerByMethodByConnectionIdMap.find(fixConnectionPtr->id) != this->pingTimerByMethodByConnectionIdMap.end() &&
this->pingTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).find(method) !=
this->pingTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).end()) {
this->pingTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method)->cancel();
}
this->pingTimerByMethodByConnectionIdMap[fixConnectionPtr->id][method] = this->serviceContextPtr->tlsClientPtr->set_timer(
pingIntervalMilliSeconds - pongTimeoutMilliSeconds,
[fixConnectionPtr, that = shared_from_base<FixService>(), pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
if (that->fixConnectionPtrByIdMap.find(fixConnectionPtr->id) != that->fixConnectionPtrByIdMap.end()) {
if (ec) {
CCAPI_LOGGER_ERROR("fixConnectionPtr = " + toString(*fixConnectionPtr) + ", ping timer error: " + ec.message());
that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
} else {
if (that->fixConnectionPtrByIdMap.at(fixConnectionPtr->id)->status == FixConnection<T>::Status::OPEN) {
ErrorCode ec;
pingMethod(fixConnectionPtr);
if (ec) {
that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "ping");
}
if (pongTimeoutMilliSeconds <= 0) {
return;
}
if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(fixConnectionPtr->id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() &&
that->pongTimeOutTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).find(method) !=
that->pongTimeOutTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).end()) {
that->pongTimeOutTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method)->cancel();
}
that->pongTimeOutTimerByMethodByConnectionIdMap[fixConnectionPtr->id][method] = that->serviceContextPtr->tlsClientPtr->set_timer(
pongTimeoutMilliSeconds, [fixConnectionPtr, that, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
if (that->fixConnectionPtrByIdMap.find(fixConnectionPtr->id) != that->fixConnectionPtrByIdMap.end()) {
if (ec) {
CCAPI_LOGGER_ERROR("fixConnectionPtr = " + toString(*fixConnectionPtr) + ", pong timeout timer error: " + ec.message());
that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
} else {
if (that->fixConnectionPtrByIdMap.at(fixConnectionPtr->id)->status == FixConnection<T>::Status::OPEN) {
auto now = UtilTime::now();
if (that->lastPongTpByMethodByConnectionIdMap.find(fixConnectionPtr->id) != that->lastPongTpByMethodByConnectionIdMap.end() &&
that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).find(method) !=
that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).end() &&
std::chrono::duration_cast<std::chrono::milliseconds>(
now - that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method))
.count() >= pongTimeoutMilliSeconds) {
auto thisFixConnectionPtr = fixConnectionPtr;
that->onFail(fixConnectionPtr, "pong timeout");
} else {
auto thisFixConnectionPtr = fixConnectionPtr;
that->setPingPongTimer(method, thisFixConnectionPtr, pingMethod);
}
}
}
}
});
}
}
}
});
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual std::vector<std::pair<int, std::string>> createCommonParam(const std::string& connectionId, const std::string& nowFixTimeStr) { return {}; }
virtual std::vector<std::pair<int, std::string>> createLogonParam(const std::string& connectionId, const std::string& nowFixTimeStr,
const std::map<int, std::string> logonOptionMap = {}) {
return {};
}
const size_t readMessageChunkSize = CCAPI_HFFIX_READ_MESSAGE_CHUNK_SIZE;
std::map<std::string, std::array<char, 1 << 20>> readMessageBufferByConnectionIdMap;
std::map<std::string, size_t> readMessageBufferReadLengthByConnectionIdMap;
std::map<std::string, std::array<char, 1 << 20>> writeMessageBufferByConnectionIdMap;
std::map<std::string, size_t> writeMessageBufferWrittenLengthByConnectionIdMap;
std::map<std::string, std::shared_ptr<FixConnection<T>>> fixConnectionPtrByIdMap;
std::map<std::string, int> sequenceSentByConnectionIdMap;
std::map<std::string, std::map<std::string, std::string>> credentialByConnectionIdMap;
std::string apiKeyName;
std::string apiSecretName;
std::string baseUrlFix;
std::string hostFix;
std::string portFix;
tcp::resolver::results_type tcpResolverResultsFix;
std::string baseUrlFixMarketData;
std::string hostFixMarketData;
std::string portFixMarketData;
tcp::resolver::results_type tcpResolverResultsFixMarketData;
std::string baseUrlFixExecutionManagement;
std::string hostFixExecutionManagement;
std::string portFixExecutionManagement;
tcp::resolver::results_type tcpResolverResultsFixExecutionManagement;
std::string protocolVersion;
std::string senderCompID;
std::string targetCompID;
};
template <>
inline std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> FixService<beast::ssl_stream<beast::tcp_stream>>::createStreamFix(
std::shared_ptr<net::io_context> iocPtr, std::shared_ptr<net::ssl::context> ctxPtr, const std::string& host) {
std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> streamPtr(new beast::ssl_stream<beast::tcp_stream>(*iocPtr, *ctxPtr));
// Set SNI Hostname (many hosts need this to handshake successfully)
if (!SSL_set_tlsext_host_name(streamPtr->native_handle(), host.c_str())) {
beast::error_code ec{static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()};
CCAPI_LOGGER_DEBUG("error SSL_set_tlsext_host_name: " + ec.message());
throw ec;
}
return streamPtr;
}
template <>
inline std::shared_ptr<beast::tcp_stream> FixService<beast::tcp_stream>::createStreamFix(std::shared_ptr<net::io_context> iocPtr,
std::shared_ptr<net::ssl::context> ctxPtr, const std::string& host) {
std::shared_ptr<beast::tcp_stream> streamPtr(new beast::tcp_stream(*iocPtr));
return streamPtr;
}
template <>
inline void FixService<beast::ssl_stream<beast::tcp_stream>>::onConnect_3(std::shared_ptr<FixConnection<beast::ssl_stream<beast::tcp_stream>>> fixConnectionPtr,
beast::error_code ec, tcp::resolver::results_type::endpoint_type) {
CCAPI_LOGGER_TRACE("async_connect callback start");
auto now = UtilTime::now();
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onFail(fixConnectionPtr, ec, "connect");
return;
}
CCAPI_LOGGER_TRACE("fixConnectionPtr = " + toString(*fixConnectionPtr));
CCAPI_LOGGER_TRACE("connected");
beast::ssl_stream<beast::tcp_stream>& stream = *fixConnectionPtr->streamPtr;
CCAPI_LOGGER_TRACE("before async_handshake");
stream.async_handshake(ssl::stream_base::client, beast::bind_front_handler(&FixService::onHandshake_3, shared_from_base<FixService>(), fixConnectionPtr));
CCAPI_LOGGER_TRACE("after async_handshake");
}
template <>
inline void FixService<beast::tcp_stream>::onConnect_3(std::shared_ptr<FixConnection<beast::tcp_stream>> fixConnectionPtr, beast::error_code ec,
tcp::resolver::results_type::endpoint_type) {
CCAPI_LOGGER_TRACE("async_connect callback start");
auto now = UtilTime::now();
if (ec) {
CCAPI_LOGGER_TRACE("fail");
this->onFail(fixConnectionPtr, ec, "connect");
return;
}
CCAPI_LOGGER_TRACE("fixConnectionPtr = " + toString(*fixConnectionPtr));
CCAPI_LOGGER_TRACE("connected");
beast::tcp_stream& stream = *fixConnectionPtr->streamPtr;
this->start(fixConnectionPtr, now);
}
} /* namespace ccapi */
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_H_
@@ -0,0 +1,69 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_COINBASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_COINBASE_H_
#ifdef CCAPI_ENABLE_SERVICE_FIX
#ifdef CCAPI_ENABLE_EXCHANGE_COINBASE
#include "ccapi_cpp/ccapi_hmac.h"
#include "ccapi_cpp/service/ccapi_fix_service.h"
namespace ccapi {
class FixServiceCoinbase : public FixService<beast::ssl_stream<beast::tcp_stream>> {
public:
FixServiceCoinbase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: FixService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_COINBASE;
this->baseUrlFix = this->sessionConfigs.getUrlFixBase().at(this->exchangeName);
this->setHostFixFromUrlFix(this->hostFix, this->portFix, this->baseUrlFix);
try {
this->tcpResolverResultsFix = this->resolver.resolve(this->hostFix, this->portFix);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_COINBASE_API_KEY;
this->apiSecretName = CCAPI_COINBASE_API_SECRET;
this->apiPassphraseName = CCAPI_COINBASE_API_PASSPHRASE;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
this->protocolVersion = CCAPI_FIX_PROTOCOL_VERSION_COINBASE;
this->targetCompID = "Coinbase";
}
virtual ~FixServiceCoinbase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
virtual std::vector<std::pair<int, std::string>> createCommonParam(const std::string& connectionId, const std::string& nowFixTimeStr) {
return {
{hff::tag::SenderCompID, mapGetWithDefault(this->credentialByConnectionIdMap[connectionId], this->apiKeyName)},
{hff::tag::TargetCompID, this->targetCompID},
{hff::tag::MsgSeqNum, std::to_string(++this->sequenceSentByConnectionIdMap[connectionId])},
{hff::tag::SendingTime, nowFixTimeStr},
};
}
virtual std::vector<std::pair<int, std::string>> createLogonParam(const std::string& connectionId, const std::string& nowFixTimeStr,
const std::map<int, std::string> logonOptionMap = {}) {
std::vector<std::pair<int, std::string>> param;
auto msgType = "A";
param.push_back({hff::tag::MsgType, msgType});
param.push_back({hff::tag::EncryptMethod, "0"});
param.push_back({hff::tag::HeartBtInt, std::to_string(this->sessionOptions.heartbeatFixIntervalMilliSeconds / 1000)});
auto credential = this->credentialByConnectionIdMap[connectionId];
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
param.push_back({hff::tag::Password, apiPassphrase});
auto msgSeqNum = std::to_string(this->sequenceSentByConnectionIdMap[connectionId] + 1);
auto senderCompID = mapGetWithDefault(credential, this->apiKeyName);
auto targetCompID = this->targetCompID;
std::vector<std::string> prehashFieldList{nowFixTimeStr, msgType, msgSeqNum, senderCompID, targetCompID, apiPassphrase};
auto prehashStr = UtilString::join(prehashFieldList, "\x01");
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto rawData = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, UtilAlgorithm::base64Decode(apiSecret), prehashStr));
param.push_back({hff::tag::RawData, rawData});
for (const auto& x : logonOptionMap) {
param.push_back({x.first, x.second});
}
return param;
}
std::string apiPassphraseName;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_COINBASE_H_
@@ -0,0 +1,33 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_FTX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_FTX_H_
#ifdef CCAPI_ENABLE_SERVICE_FIX
#ifdef CCAPI_ENABLE_EXCHANGE_FTX
#include "ccapi_cpp/ccapi_hmac.h"
#include "ccapi_cpp/service/ccapi_fix_service_ftx_base.h"
namespace ccapi {
class FixServiceFtx : public FixServiceFtxBase {
public:
FixServiceFtx(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: FixServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_FTX;
this->baseUrlFix = this->sessionConfigs.getUrlFixBase().at(this->exchangeName);
this->setHostFixFromUrlFix(this->hostFix, this->portFix, this->baseUrlFix);
this->apiKeyName = CCAPI_FTX_API_KEY;
this->apiSecretName = CCAPI_FTX_API_SECRET;
this->apiSubaccountName = CCAPI_FTX_API_SUBACCOUNT;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiSubaccountName});
try {
this->tcpResolverResultsFix = this->resolver.resolve(this->hostFix, this->portFix);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->protocolVersion = CCAPI_FIX_PROTOCOL_VERSION_FTX;
this->targetCompID = "FTX";
}
virtual ~FixServiceFtx() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_FTX_H_
@@ -0,0 +1,56 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_FTX_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_FTX_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_FIX
#if defined(CCAPI_ENABLE_EXCHANGE_FTX) || defined(CCAPI_ENABLE_EXCHANGE_FTX_US)
#include "ccapi_cpp/ccapi_hmac.h"
#include "ccapi_cpp/service/ccapi_fix_service.h"
namespace ccapi {
class FixServiceFtxBase : public FixService<beast::ssl_stream<beast::tcp_stream>> {
public:
FixServiceFtxBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: FixService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~FixServiceFtxBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
virtual std::vector<std::pair<int, std::string>> createCommonParam(const std::string& connectionId, const std::string& nowFixTimeStr) {
return {
{hff::tag::SenderCompID, mapGetWithDefault(this->credentialByConnectionIdMap[connectionId], this->apiKeyName)},
{hff::tag::TargetCompID, this->targetCompID},
{hff::tag::MsgSeqNum, std::to_string(++this->sequenceSentByConnectionIdMap[connectionId])},
{hff::tag::SendingTime, nowFixTimeStr},
};
}
virtual std::vector<std::pair<int, std::string>> createLogonParam(const std::string& connectionId, const std::string& nowFixTimeStr,
const std::map<int, std::string> logonOptionMap = {}) {
std::vector<std::pair<int, std::string>> param;
auto msgType = "A";
param.push_back({hff::tag::MsgType, msgType});
param.push_back({hff::tag::EncryptMethod, "0"});
param.push_back({hff::tag::HeartBtInt, "30"});
auto msgSeqNum = std::to_string(this->sequenceSentByConnectionIdMap[connectionId] + 1);
auto credential = this->credentialByConnectionIdMap[connectionId];
auto senderCompID = mapGetWithDefault(credential, this->apiKeyName);
auto targetCompID = this->targetCompID;
std::vector<std::string> prehashFieldList{nowFixTimeStr, msgType, msgSeqNum, senderCompID, targetCompID};
auto prehashStr = UtilString::join(prehashFieldList, "\x01");
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string rawData = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, prehashStr, true);
param.push_back({hff::tag::RawData, rawData});
for (const auto& x : logonOptionMap) {
param.push_back({x.first, x.second});
}
auto apiSubaccountName = mapGetWithDefault(credential, this->apiSubaccountName);
if (!apiSubaccountName.empty()) {
param.push_back({hff::tag::Account, apiSubaccountName});
}
return param;
}
std::string apiSubaccountName;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_FTX_BASE_H_
@@ -0,0 +1,33 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_FTX_US_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_FTX_US_H_
#ifdef CCAPI_ENABLE_SERVICE_FIX
#ifdef CCAPI_ENABLE_EXCHANGE_FTX_US
#include "ccapi_cpp/ccapi_hmac.h"
#include "ccapi_cpp/service/ccapi_fix_service_ftx_base.h"
namespace ccapi {
class FixServiceFtxUs : public FixServiceFtxBase {
public:
FixServiceFtxUs(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: FixServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_FTX_US;
this->baseUrlFix = this->sessionConfigs.getUrlFixBase().at(this->exchangeName);
this->setHostFixFromUrlFix(this->hostFix, this->portFix, this->baseUrlFix);
this->apiKeyName = CCAPI_FTX_US_API_KEY;
this->apiSecretName = CCAPI_FTX_US_API_SECRET;
this->apiSubaccountName = CCAPI_FTX_US_API_SUBACCOUNT;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiSubaccountName});
try {
this->tcpResolverResultsFix = this->resolver.resolve(this->hostFix, this->portFix);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->protocolVersion = CCAPI_FIX_PROTOCOL_VERSION_FTX_US;
this->targetCompID = "FTXUS";
}
virtual ~FixServiceFtxUs() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_FTX_US_H_
@@ -0,0 +1,54 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_GEMINI_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_GEMINI_H_
#ifdef CCAPI_ENABLE_SERVICE_FIX
#ifdef CCAPI_ENABLE_EXCHANGE_GEMINI
#include "ccapi_cpp/service/ccapi_fix_service.h"
namespace ccapi {
class FixServiceGemini : public FixService<beast::tcp_stream> {
public:
FixServiceGemini(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: FixService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_GEMINI;
this->hostFix = CCAPI_GEMINI_URL_FIX_HOST;
this->portFix = CCAPI_GEMINI_URL_FIX_PORT;
try {
this->tcpResolverResultsFix = this->resolver.resolve(this->hostFix, this->portFix);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->protocolVersion = CCAPI_FIX_PROTOCOL_VERSION_GEMINI;
this->senderCompID = CCAPI_GEMINI_API_SENDER_COMP_ID;
this->targetCompID = CCAPI_GEMINI_API_TARGET_COMP_ID;
}
virtual ~FixServiceGemini() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
virtual std::vector<std::pair<int, std::string>> createCommonParam(const std::string& connectionId, const std::string& nowFixTimeStr) {
return {
{hff::tag::SenderCompID, CCAPI_GEMINI_API_SENDER_COMP_ID},
{hff::tag::TargetCompID, CCAPI_GEMINI_API_TARGET_COMP_ID},
{hff::tag::MsgSeqNum, std::to_string(++this->sequenceSentByConnectionIdMap[connectionId])},
{hff::tag::SendingTime, nowFixTimeStr},
};
}
virtual std::vector<std::pair<int, std::string>> createLogonParam(const std::string& connectionId, const std::string& nowFixTimeStr,
const std::map<int, std::string> logonOptionMap = {}) {
std::vector<std::pair<int, std::string>> param;
auto msgType = "A";
param.push_back({hff::tag::MsgType, msgType});
param.push_back({hff::tag::ResetSeqNumFlag, "Y"});
param.push_back({hff::tag::EncryptMethod, "0"});
param.push_back({hff::tag::HeartBtInt, std::to_string(this->sessionOptions.heartbeatFixIntervalMilliSeconds / 1000)});
for (const auto& x : logonOptionMap) {
param.push_back({x.first, x.second});
}
return param;
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_FIX_SERVICE_GEMINI_H_
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,298 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_ASCENDEX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_ASCENDEX_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceAscendex : public MarketDataService {
public:
MarketDataServiceAscendex(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_ASCENDEX;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/api/pro/v1/stream";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->getRecentTradesTarget = "/api/pro/v1/trades";
this->getInstrumentTarget = "/api/pro/v1/products";
this->getInstrumentsTarget = "/api/pro/v1/products";
}
virtual ~MarketDataServiceAscendex() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
bool doesHttpBodyContainError(const Request& request, 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 {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
if (field == CCAPI_MARKET_DEPTH) {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_BBO;
}
}
}
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)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("sub").Move(), allocator);
std::string symbolId = subscriptionListBySymbolId.first;
if (channelId == CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_BBO) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
}
std::string exchangeSubscriptionId = channelId + ":" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
document.AddMember("ch", rj::Value(exchangeSubscriptionId.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 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());
std::string m = document["m"].GetString();
if (m == "bbo" || m == "depth" || m == "depth-snapshot") {
std::string channelId = m == "depth-snapshot" ? CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_DEPTH : m;
std::string symbolId = document["symbol"].GetString();
std::string exchangeSubscriptionId = channelId + ":" + symbolId;
const rj::Value& data = document["data"];
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
if (m == "bbo") {
if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) {
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
} else {
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
}
} else if (m == "depth") {
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
} else if (m == "depth-snapshot") {
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
}
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(data["ts"].GetString())));
if (m == "bbo") {
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["bid"][0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["bid"][1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["ask"][0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["ask"][1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
} else {
for (const auto& x : 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())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
for (const auto& x : data["asks"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, 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 (m == "trades") {
std::string channelId = m;
std::string symbolId = document["symbol"].GetString();
std::string exchangeSubscriptionId = channelId + ":" + symbolId;
const rj::Value& data = document["data"];
for (const auto& x : data.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(x["ts"].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()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["seqnum"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, x["bm"].GetBool() ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (m == "ping") {
ErrorCode ec;
this->send(hdl, R"({ "op": "pong" })", wspp::frame::opcode::text, ec);
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "pong");
}
} else if (m == "sub") {
std::string ch = document["ch"].GetString();
auto splitted = UtilString::split(ch, ':');
std::string channelId = splitted.at(0);
std::string symbolId = splitted.at(1);
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->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);
CCAPI_LOGGER_TRACE(channelId);
CCAPI_LOGGER_TRACE(CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_DEPTH);
if (channelId == CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_DEPTH) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("req").Move(), allocator);
document.AddMember("action", rj::Value("depth-snapshot").Move(), allocator);
rj::Value args(rj::kObjectType);
args.AddMember("symbol", rj::Value(symbolId.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;
CCAPI_LOGGER_TRACE(sendString);
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 (m == "error") {
// TODO(cryptochassis): implement
}
}
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->getInstrumentTarget;
std::string queryString;
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;
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());
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["tickSize"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSize"].GetString());
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["minNotional"].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 = TimePoint(std::chrono::milliseconds(std::stoll(x["ts"].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()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["seqnum"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, x["bm"].GetBool() ? "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.emplace_back(std::move(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_ASCENDEX_H_
@@ -0,0 +1,33 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE
#include "ccapi_cpp/service/ccapi_market_data_service_binance_base.h"
namespace ccapi {
class MarketDataServiceBinance : public MarketDataServiceBinanceBase {
public:
MarketDataServiceBinance(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_BINANCE_API_KEY;
this->setupCredential({this->apiKeyName});
this->getRecentTradesTarget = "/api/v3/trades";
this->getRecentAggTradesTarget = "/api/v3/aggTrades";
this->getInstrumentTarget = "/api/v3/exchangeInfo";
this->getInstrumentsTarget = "/api/v3/exchangeInfo";
}
virtual ~MarketDataServiceBinance() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_H_
@@ -0,0 +1,356 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#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)
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceBinanceBase : public MarketDataService {
public:
MarketDataServiceBinanceBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->enableCheckPingPongWebsocketApplicationLevel = false;
}
virtual ~MarketDataServiceBinanceBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
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 (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_BOOK_TICKER;
} else {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
std::string updateSpeed;
if (conflateIntervalMilliSeconds < 1000) {
updateSpeed = "100ms";
}
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
if (!updateSpeed.empty()) {
channelId += "&UPDATE_SPEED=" + updateSpeed;
}
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
}
}
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("SUBSCRIBE").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 = UtilString::toLower(subscriptionListByInstrument.first) + "@";
if (channelId.rfind(CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_BOOK_TICKER, 0) == 0) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
exchangeSubscriptionId += CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_BOOK_TICKER;
} else if (channelId.rfind(CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_PARTIAL_BOOK_DEPTH, 0) == 0) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
int marketDepthSubscribedToExchange =
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
exchangeSubscriptionId += std::string(CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_PARTIAL_BOOK_DEPTH) + std::to_string(marketDepthSubscribedToExchange);
auto splitted = UtilString::split(channelId, "?");
if (splitted.size() == 2) {
auto mapped = Url::convertQueryStringToMap(splitted.at(1));
if (mapped.find("UPDATE_SPEED") != mapped.end()) {
exchangeSubscriptionId += "@" + mapped.at("UPDATE_SPEED");
}
}
} else {
exchangeSubscriptionId += channelId;
}
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->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap[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("result") && document["result"].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()) {
int id = std::stoi(document["id"].GetString());
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.find(id) != this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.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(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 (document.IsObject() && document.HasMember("stream") && document.HasMember("data")) {
MarketDataMessage marketDataMessage;
std::string exchangeSubscriptionId = document["stream"].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 == CCAPI_WEBSOCKET_BINANCE_BASE_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 = this->isDerivatives ? TimePoint(std::chrono::milliseconds(std::stoll(data["T"].GetString()))) : timeReceived;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["b"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["B"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["a"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["A"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId.rfind(CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_PARTIAL_BOOK_DEPTH, 0) == 0) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = this->isDerivatives ? TimePoint(std::chrono::milliseconds(std::stoll(data["T"].GetString()))) : timeReceived;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
const char* bidsName = this->isDerivatives ? "b" : "bids";
int bidIndex = 0;
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
for (const auto& x : data[bidsName].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;
}
const char* asksName = this->isDerivatives ? "a" : "asks";
int askIndex = 0;
for (const auto& x : data[asksName].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 (channelId == CCAPI_WEBSOCKET_BINANCE_BASE_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["t"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, data["m"].GetBool() ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId == CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_AGG_TRADE) {
auto time = UtilTime::makeTimePointFromMilliseconds(std::stoll(data["T"].GetString()));
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = time;
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::AGG_TRADE_ID, data["a"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, data["m"].GetBool() ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::AGG_TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
void prepareReq(http::request<http::string_body>& req, const std::map<std::string, std::string>& credential) {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
if (!apiKey.empty()) {
req.set("X-MBX-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_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->getInstrumentTarget;
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->getInstrumentTarget;
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());
for (const auto& y : x["filters"].GetArray()) {
std::string filterType = y["filterType"].GetString();
if (filterType == "PRICE_FILTER") {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, y["tickSize"].GetString());
} 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["minNotional"].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()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["id"].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()))});
dataPoint.insert({MarketDataMessage::DataFieldType::AGG_TRADE_ID, std::string(x["a"].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);
}
}
bool isDerivatives{};
std::string getRecentAggTradesTarget;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_BASE_H_
@@ -0,0 +1,33 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_COIN_FUTURES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_COIN_FUTURES_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_COIN_FUTURES
#include "ccapi_cpp/service/ccapi_market_data_service_binance_derivatives_base.h"
namespace ccapi {
class MarketDataServiceBinanceCoinFutures : public MarketDataServiceBinanceDerivativesBase {
public:
MarketDataServiceBinanceCoinFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_BINANCE_COIN_FUTURES_API_KEY;
this->setupCredential({this->apiKeyName});
this->getRecentTradesTarget = "/dapi/v1/trades";
this->getRecentAggTradesTarget = "/dapi/v1/aggTrades";
this->getInstrumentTarget = "/dapi/v1/exchangeInfo";
this->getInstrumentsTarget = "/dapi/v1/exchangeInfo";
}
virtual ~MarketDataServiceBinanceCoinFutures() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_COIN_FUTURES_H_
@@ -0,0 +1,101 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_DERIVATIVES_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_DERIVATIVES_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#if defined(CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES) || defined(CCAPI_ENABLE_EXCHANGE_BINANCE_COIN_FUTURES)
#include "ccapi_cpp/service/ccapi_market_data_service_binance_base.h"
namespace ccapi {
class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceBase {
public:
MarketDataServiceBinanceDerivativesBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->isDerivatives = true;
}
virtual ~MarketDataServiceBinanceDerivativesBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
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) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({1, 5, 10, 20}));
if (marketDepthSubscribedToExchange == 1) {
channelId = CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_BOOK_TICKER;
} else {
std::string updateSpeed;
if (conflateIntervalMilliSeconds < 250) {
updateSpeed = "100ms";
} else if (conflateIntervalMilliSeconds >= 500) {
updateSpeed = "500ms";
}
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
if (!updateSpeed.empty()) {
channelId += "&UPDATE_SPEED=" + updateSpeed;
}
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
}
}
void extractInstrumentInfo(Element& element, const rj::Value& x) {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_MARGIN_ASSET, x["marginAsset"].GetString());
element.insert(CCAPI_UNDERLYING_SYMBOL, x["pair"].GetString());
for (const auto& y : x["filters"].GetArray()) {
std::string filterType = y["filterType"].GetString();
if (filterType == "PRICE_FILTER") {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, y["tickSize"].GetString());
} else if (filterType == "LOT_SIZE") {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, y["stepSize"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, y["minQty"].GetString());
}
}
}
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
switch (request.getOperation()) {
case Request::Operation::GET_INSTRUMENT: {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
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: {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
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:
MarketDataServiceBinanceBase::convertTextMessageToMarketDataMessage(request, textMessage, timeReceived, event, marketDataMessageList);
}
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_DERIVATIVES_BASE_H_
@@ -0,0 +1,33 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_US_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_US_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_US
#include "ccapi_cpp/service/ccapi_market_data_service_binance_base.h"
namespace ccapi {
class MarketDataServiceBinanceUs : public MarketDataServiceBinanceBase {
public:
MarketDataServiceBinanceUs(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_BINANCE_US_API_KEY;
this->setupCredential({this->apiKeyName});
this->getRecentTradesTarget = "/api/v3/trades";
this->getRecentAggTradesTarget = "/api/v3/aggTrades";
this->getInstrumentTarget = "/api/v3/exchangeInfo";
this->getInstrumentsTarget = "/api/v3/exchangeInfo";
}
virtual ~MarketDataServiceBinanceUs() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_US_H_
@@ -0,0 +1,33 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_USDS_FUTURES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_USDS_FUTURES_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_BINANCE_USDS_FUTURES
#include "ccapi_cpp/service/ccapi_market_data_service_binance_derivatives_base.h"
namespace ccapi {
class MarketDataServiceBinanceUsdsFutures : public MarketDataServiceBinanceDerivativesBase {
public:
MarketDataServiceBinanceUsdsFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_BINANCE_USDS_FUTURES_API_KEY;
this->setupCredential({this->apiKeyName});
this->getRecentTradesTarget = "/fapi/v1/trades";
this->getRecentAggTradesTarget = "/fapi/v1/aggTrades";
this->getInstrumentTarget = "/fapi/v1/exchangeInfo";
this->getInstrumentsTarget = "/fapi/v1/exchangeInfo";
}
virtual ~MarketDataServiceBinanceUsdsFutures() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BINANCE_USDS_FUTURES_H_
@@ -0,0 +1,499 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITFINEX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITFINEX_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_BITFINEX
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceBitfinex : public MarketDataService {
public:
MarketDataServiceBitfinex(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_BITFINEX;
this->baseUrl = std::string(CCAPI_BITFINEX_PUBLIC_URL_WS_BASE) + "/ws/2";
this->baseUrlRest = CCAPI_BITFINEX_PUBLIC_URL_REST_BASE;
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->getRecentTradesTarget = "/v2/trades/{Symbol}/hist";
this->getInstrumentsTarget = CCAPI_BITFINEX_GET_INSTRUMENTS_PATH;
this->getInstrumentTarget = CCAPI_BITFINEX_GET_INSTRUMENTS_PATH;
}
virtual ~MarketDataServiceBitfinex() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl, "{\"cid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec);
}
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const 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) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({1, 25, 100, 250}));
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override { return std::vector<std::string>(); }
void onOpen(wspp::connection_hdl hdl) override {
MarketDataService::onOpen(hdl);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("conf").Move(), allocator);
document.AddMember("flags", rj::Value(229376).Move(), allocator);
rj::StringBuffer stringBuffer;
rj::Writer<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");
}
}
void onClose(wspp::connection_hdl hdl) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap.erase(wsConnection.id);
this->sequenceByConnectionIdMap.erase(wsConnection.id);
MarketDataService::onClose(hdl);
}
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
if (document.IsArray() && document.Size() >= 1) {
auto exchangeSubscriptionId = std::string(document[0].GetString());
if (document.Size() >= 2 && document[1].IsString() && std::string(document[1].GetString()) == "hb") {
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document[2].GetString());
if (!this->checkSequence(wsConnection, sequence)) {
this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, exchangeSubscriptionId);
return;
}
}
} else {
auto channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
auto symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID);
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0 || channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES) {
std::string channel =
channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0 ? CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK : CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES;
rj::Value data(rj::kArrayType);
if (document[1].IsArray()) {
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document[2].GetString());
if (!this->checkSequence(wsConnection, sequence)) {
this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, exchangeSubscriptionId);
return;
}
}
const rj::Value& content = document[1].GetArray();
if (content[0].IsArray()) {
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document[2].GetString());
}
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = timeReceived;
for (const auto& x : content.GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
auto count = std::string(x[1].GetString());
auto amount = UtilString::normalizeDecimalString(x[2].GetString());
if (count != "0") {
if (amount.at(0) == '-') {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount.substr(1)});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
} else {
if (amount.at(0) == '-') {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, "0"});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, "0"});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else {
for (const auto& x : content.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
std::string timestampInMilliseconds = x[1].GetString();
timestampInMilliseconds.insert(timestampInMilliseconds.size() - 3, ".");
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(timestampInMilliseconds));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x[3].GetString()))});
auto amount = UtilString::normalizeDecimalString(x[2].GetString());
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount.at(0) == '-' ? amount.substr(1) : amount});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, amount.at(0) == '-' ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
} else {
const rj::Value& x = content;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
auto count = std::string(x[1].GetString());
auto amount = UtilString::normalizeDecimalString(x[2].GetString());
if (count != "0") {
if (amount.at(0) == '-') {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount.substr(1)});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::ASK]
.emplace_back(std::move(dataPoint));
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::BID]
.emplace_back(std::move(dataPoint));
}
} else {
if (amount.at(0) == '-') {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, "0"});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::ASK]
.emplace_back(std::move(dataPoint));
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, "0"});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::BID]
.emplace_back(std::move(dataPoint));
}
}
}
} else if (document[1].IsString()) {
std::string str = document[1].GetString();
if (str == "tu" || str == "te") {
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document[3].GetString());
if (!this->checkSequence(wsConnection, sequence)) {
this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, exchangeSubscriptionId);
return;
}
}
if (str == CCAPI_BITFINEX_STREAM_TRADE_RAW_MESSAGE_TYPE) {
const rj::Value& x = document[2].GetArray();
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
std::string timestampInMilliseconds = x[1].GetString();
timestampInMilliseconds.insert(timestampInMilliseconds.size() - 3, ".");
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(timestampInMilliseconds));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x[3].GetString()))});
auto amount = UtilString::normalizeDecimalString(x[2].GetString());
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount.at(0) == '-' ? amount.substr(1) : amount});
if (str == "tu") {
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x[0].GetString())});
}
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, amount.at(0) == '-' ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (str == "cs") {
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document[3].GetString());
if (!this->checkSequence(wsConnection, sequence)) {
this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, exchangeSubscriptionId);
return;
}
}
if (this->sessionOptions.enableCheckOrderBookChecksum) {
this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId] =
intToHex(static_cast<uint_fast32_t>(static_cast<uint32_t>(std::stoi(document[2].GetString()))));
}
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
std::string timestampInMilliseconds = document[4].GetString();
timestampInMilliseconds.insert(timestampInMilliseconds.size() - 3, ".");
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(timestampInMilliseconds));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
std::swap(marketDataMessage.data,
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]);
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
}
} else if (document.IsObject() && document.HasMember("event")) {
std::string eventStr = document["event"].GetString();
if (eventStr == "conf") {
std::vector<std::string> sendStringList;
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0 || channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES) {
std::string channel = channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0 ? CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK
: CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES;
for (auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
document.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator);
auto symbolId = subscriptionListBySymbolId.first;
document.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
if (channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK) {
document.AddMember("prec", rj::Value("P0").Move(), allocator);
document.AddMember("freq", rj::Value("F0").Move(), allocator);
document.AddMember(
"len",
rj::Value(
std::to_string(this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId))
.c_str(),
allocator)
.Move(),
allocator);
}
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.emplace_back(std::move(sendString));
}
}
}
for (const auto& sendString : sendStringList) {
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 (eventStr == "subscribed" || eventStr == "error") {
std::string channel = document["channel"].GetString();
auto channelId = channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK
? channel + "?" + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::string(document["len"].GetString())
: channel;
auto symbolId = std::string(document["symbol"].GetString());
if (eventStr == "subscribed") {
auto exchangeSubscriptionId = std::string(document["chanId"].GetString());
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
}
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->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(eventStr == "subscribed" ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(eventStr == "subscribed" ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
event.setMessageList(messageList);
}
}
}
bool checkSequence(const WsConnection& wsConnection, int sequence) {
if (this->sequenceByConnectionIdMap.find(wsConnection.id) == this->sequenceByConnectionIdMap.end()) {
if (sequence != this->sessionConfigs.getInitialSequenceByExchangeMap().at(this->exchangeName)) {
CCAPI_LOGGER_WARN("incorrect initial sequence, wsConnection = " + toString(wsConnection));
return false;
}
this->sequenceByConnectionIdMap.insert(std::pair<std::string, int>(wsConnection.id, sequence));
return true;
} else {
if (sequence - this->sequenceByConnectionIdMap[wsConnection.id] == 1) {
this->sequenceByConnectionIdMap[wsConnection.id] = sequence;
return true;
} else {
return false;
}
}
}
void onOutOfSequence(WsConnection& wsConnection, int sequence, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
const std::string& exchangeSubscriptionId) {
int previous = 0;
if (this->sequenceByConnectionIdMap.find(wsConnection.id) != this->sequenceByConnectionIdMap.end()) {
previous = this->sequenceByConnectionIdMap[wsConnection.id];
}
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND,
"out of sequence: previous = " + toString(previous) + ", current = " + toString(sequence) + ", connection = " + toString(wsConnection) +
", textMessage = " + textMessage + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived));
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId].clear();
ErrorCode ec;
this->close(wsConnection, hdl, websocketpp::close::status::normal, "out of sequence", ec);
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown");
}
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false;
}
std::string calculateOrderBookChecksum(const std::map<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(i1->first.toString());
csData.push_back(i1->second);
++i1;
}
if (i2 != snapshotAsk.end()) {
csData.push_back(i2->first.toString());
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 onIncorrectStatesFound(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
const std::string& exchangeSubscriptionId, std::string const& reason) override {
CCAPI_LOGGER_ERROR("incorrect states found: connection = " + toString(wsConnection) + ", textMessage = " + textMessage +
", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", reason = " + reason);
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId].clear();
MarketDataService::onIncorrectStatesFound(wsConnection, hdl, textMessage, timeReceived, exchangeSubscriptionId, reason);
}
void convertRequestForRest(http::request<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, {
{"{Symbol}", 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_INSTRUMENTS: {
req.method(http::verb::get);
auto target = this->getInstrumentsTarget;
req.target(target);
} break;
case Request::Operation::GET_INSTRUMENT: {
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 std::string& pair, const rj::Value& z) {
element.insert(CCAPI_INSTRUMENT, "t" + pair);
if (pair.find(':') != std::string::npos) {
auto splitted = UtilString::split(pair, ':');
element.insert(CCAPI_BASE_ASSET, splitted.at(0));
element.insert(CCAPI_QUOTE_ASSET, splitted.at(1));
} else {
element.insert(CCAPI_BASE_ASSET, pair.substr(0, 3));
element.insert(CCAPI_QUOTE_ASSET, pair.substr(3, 6));
}
element.insert(CCAPI_ORDER_QUANTITY_MIN, z[3].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[1].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
std::string rawAmount = UtilString::normalizeDecimalString(x[2].GetString());
bool isAmountNegative = !rawAmount.empty() && rawAmount.at(0) == '-';
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x[3].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, isAmountNegative ? rawAmount.substr(1) : rawAmount});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, isAmountNegative ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} 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[0].GetArray()) {
std::string pair = x[0].GetString();
Element element;
this->extractInstrumentInfo(element, pair, x[1]);
elementList.push_back(element);
}
message.setElementList(elementList);
message.setCorrelationIdList({request.getCorrelationId()});
event.addMessages({message});
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
std::vector<Element> elementList;
bool found{};
for (const auto& x : document[0].GetArray()) {
std::string pair = x[0].GetString();
if ("t" + pair == request.getInstrument()) {
Element element;
this->extractInstrumentInfo(element, pair, x[1]);
elementList.push_back(element);
found = true;
}
if (found) {
break;
}
}
message.setElementList(elementList);
message.setCorrelationIdList({request.getCorrelationId()});
event.addMessages({message});
} break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
std::map<std::string, std::map<std::string, MarketDataMessage::TypeForData> > marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap;
std::map<std::string, int> sequenceByConnectionIdMap;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITFINEX_H_
@@ -0,0 +1,330 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITMEX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITMEX_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_BITMEX
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceBitmex : public MarketDataService {
public:
MarketDataServiceBitmex(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_BITMEX;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/realtime";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->getRecentTradesTarget = "/api/v1/trade";
this->getInstrumentTarget = "/api/v1/instrument";
this->getInstrumentsTarget = "/api/v1/instrument";
// this->convertNumberToStringInJsonRegex = std::regex("(\\[|,|\":)(-?\\d+\\.?\\d*)");
}
virtual ~MarketDataServiceBitmex() {}
#ifndef CCAPI_EXPOSE_INTERNAL
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 {
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;
}
}
}
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_BITMEX_CHANNEL_QUOTE || channelId == CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_10) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
}
std::string exchangeSubscriptionId = channelId + ":" + 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);
}
}
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 onClose(wspp::connection_hdl hdl) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
this->priceByConnectionIdChannelIdSymbolIdPriceIdMap.erase(wsConnection.id);
MarketDataService::onClose(hdl);
}
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
if (textMessage != "pong") {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
if (document.IsObject() && document.HasMember("table")) {
std::string channelId = document["table"].GetString();
if (channelId == CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_10 || channelId == CCAPI_WEBSOCKET_BITMEX_CHANNEL_QUOTE) {
std::string action = document["action"].GetString();
MarketDataMessage::RecapType recapType;
if (action == "partial") {
recapType = MarketDataMessage::RecapType::SOLICITED;
} else {
recapType = MarketDataMessage::RecapType::NONE;
}
int i = 0;
std::string symbolId;
std::string exchangeSubscriptionId;
for (const auto& x : document["data"].GetArray()) {
if (i == 0) {
symbolId = x["symbol"].GetString();
exchangeSubscriptionId = channelId + ":" + symbolId;
}
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = recapType;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::parse(std::string(x["timestamp"].GetString()));
if (channelId == CCAPI_WEBSOCKET_BITMEX_CHANNEL_QUOTE) {
MarketDataMessage::TypeForDataPoint dataPointBid;
dataPointBid.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x["bidPrice"].GetString())});
dataPointBid.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x["bidSize"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPointBid));
MarketDataMessage::TypeForDataPoint dataPointAsk;
dataPointAsk.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x["askPrice"].GetString())});
dataPointAsk.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x["askSize"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPointAsk));
} else {
for (const auto& y : x["bids"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(y[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(y[1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
for (const auto& y : x["asks"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(y[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(y[1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
++i;
}
} else if (channelId == CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_L2 || channelId == CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_L2_25) {
std::string action = document["action"].GetString();
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.tp = timeReceived;
marketDataMessage.recapType = action == "partial" ? MarketDataMessage::RecapType::SOLICITED : MarketDataMessage::RecapType::NONE;
int i = 0;
std::string symbolId;
std::string exchangeSubscriptionId;
for (const auto& x : document["data"].GetArray()) {
if (i == 0) {
symbolId = x["symbol"].GetString();
exchangeSubscriptionId = channelId + ":" + symbolId;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
}
MarketDataMessage::TypeForDataPoint dataPoint;
std::string price;
std::string size;
std::string priceId = x["id"].GetString();
if (action == "insert" || action == "partial") {
price = UtilString::normalizeDecimalString(x["price"].GetString());
size = UtilString::normalizeDecimalString(x["size"].GetString());
this->priceByConnectionIdChannelIdSymbolIdPriceIdMap[wsConnection.id][channelId][symbolId][priceId] = price;
} else {
price = this->priceByConnectionIdChannelIdSymbolIdPriceIdMap[wsConnection.id][channelId][symbolId][priceId];
if (price.empty()) {
this->onIncorrectStatesFound(wsConnection, hdl, textMessage, timeReceived, exchangeSubscriptionId,
"bitmex update for missing item came through on wsConnection = " + toString(wsConnection) +
", channelId = " + channelId + ", symbolId = " + symbolId + ", priceId = " + priceId + ". Data: " +
toString(this->priceByConnectionIdChannelIdSymbolIdPriceIdMap[wsConnection.id][channelId][symbolId]));
}
if (action == "update") {
size = UtilString::normalizeDecimalString(x["size"].GetString());
} else if (action == "delete") {
size = "0";
}
}
std::string side = x["side"].GetString();
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, price});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, size});
marketDataMessage.data[side == "Buy" ? MarketDataMessage::DataType::BID : MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
++i;
}
if (i > 0) {
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (channelId == CCAPI_WEBSOCKET_BITMEX_CHANNEL_TRADE) {
std::string action = document["action"].GetString();
for (const auto& x : document["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.tp = UtilTime::parse(std::string(x["timestamp"].GetString()));
marketDataMessage.recapType = action == "partial" ? MarketDataMessage::RecapType::SOLICITED : MarketDataMessage::RecapType::NONE;
std::string symbolId = x["symbol"].GetString();
marketDataMessage.exchangeSubscriptionId = channelId + ":" + symbolId;
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()))});
auto timePair = UtilTime::divide(marketDataMessage.tp);
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["trdMatchID"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["side"].GetString()) == "Sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
} else if (document.IsObject() && document.HasMember("request") && std::string(document["request"]["op"].GetString()) == "subscribe") {
bool success = document.HasMember("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()) {
for (const auto& x : document["request"]["args"].GetArray()) {
auto splitted = UtilString::split(x.GetString(), ":");
std::string channelId = splitted.at(0);
std::string symbolId = splitted.at(1);
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) {
std::vector<std::string> correlationIdList_2 =
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
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;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "count"},
{"reverse", "true"},
});
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->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_MARGIN_ASSET, x["settlCurrency"].GetString());
element.insert(CCAPI_UNDERLYING_SYMBOL, x["referenceSymbol"].GetString());
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["tickSize"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSize"].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::parse(std::string(x["timestamp"].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::TRADE_ID, std::string(x["trdMatchID"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["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.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.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::map<std::string, std::map<std::string, std::map<std::string, std::map<std::string, std::string> > > > priceByConnectionIdChannelIdSymbolIdPriceIdMap;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITMEX_H_
@@ -0,0 +1,271 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITSTAMP_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BITSTAMP_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_BITSTAMP
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceBitstamp : public MarketDataService {
public:
MarketDataServiceBitstamp(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_BITSTAMP;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->enableCheckPingPongWebsocketApplicationLevel = false;
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
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/";
}
virtual ~MarketDataServiceBitstamp() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
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 {
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 {
std::vector<std::string> sendStringList;
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
for (auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("bts:subscribe").Move(), allocator);
rj::Value data(rj::kObjectType);
auto symbolId = subscriptionListByInstrument.first;
if (channelId == CCAPI_WEBSOCKET_BITSTAMP_CHANNEL_ORDER_BOOK) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
}
std::string exchangeSubscriptionId = channelId + "_" + symbolId;
data.AddMember("channel", rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
document.AddMember("data", data, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.emplace_back(std::move(sendString));
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
}
}
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());
const rj::Value& data = document["data"];
if (document.IsObject() && document.HasMember("event") && std::string(document["event"].GetString()) == "bts:subscription_succeeded") {
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 exchangeSubscriptionId = document["channel"].GetString();
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(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 (document.IsObject() && document.HasMember("event") &&
(std::string(document["event"].GetString()) == "data" || std::string(document["event"].GetString()) == "trade")) {
MarketDataMessage marketDataMessage;
std::string exchangeSubscriptionId = document["channel"].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];
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
if (channelId == CCAPI_WEBSOCKET_BITSTAMP_CHANNEL_ORDER_BOOK) {
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;
}
std::string microtimestamp = data["microtimestamp"].GetString();
microtimestamp.insert(microtimestamp.size() - 6, ".");
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(microtimestamp));
int bidIndex = 0;
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
for (const auto& x : data["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 : data["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 (channelId == CCAPI_WEBSOCKET_BITSTAMP_CHANNEL_LIVE_TRADES) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
std::string microtimestamp = data["microtimestamp"].GetString();
microtimestamp.insert(microtimestamp.size() - 6, ".");
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(microtimestamp));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(data["price_str"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(data["amount_str"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(data["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(data["type"].GetString()) == "0" ? "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;
this->substituteParam(target, {
{"{currency_pair}", symbolId},
});
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param, {});
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
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["url_symbol"].GetString());
std::string name = x["name"].GetString();
auto splitted = UtilString::split(name, "/");
auto baseAsset = splitted.at(0);
auto quoteAsset = splitted.at(1);
element.insert(CCAPI_BASE_ASSET, baseAsset);
element.insert(CCAPI_QUOTE_ASSET, quoteAsset);
int counterDecimals = std::stoi(x["counter_decimals"].GetString());
if (counterDecimals > 0) {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(counterDecimals - 1, '0') + "1");
} else {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1");
}
int baseDecimals = std::stoi(x["base_decimals"].GetString());
if (baseDecimals > 0) {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "0." + std::string(baseDecimals - 1, '0') + "1");
} else {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "1");
}
auto splittedMinimumOrder = UtilString::split(x["minimum_order"].GetString(), ' ');
if (splittedMinimumOrder.size() == 2) {
if (splittedMinimumOrder.at(1) == quoteAsset) {
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, splittedMinimumOrder.at(0));
} else if (splittedMinimumOrder.at(1) == baseAsset) {
element.insert(CCAPI_ORDER_QUANTITY_MIN, splittedMinimumOrder.at(0));
}
}
}
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::makeTimePointFromSeconds(std::stol(x["date"].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["amount"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["tid"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["type"].GetString()) == "0" ? "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["url_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.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_BITSTAMP_H_
@@ -0,0 +1,278 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_H_
#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"
namespace ccapi {
class MarketDataServiceBybit : public MarketDataService {
public:
MarketDataServiceBybit(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_BYBIT;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/quote/ws/v2";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->getRecentTradesTarget = "/spot/quote/v1/trades";
this->getInstrumentTarget = "/spot/v1/symbols";
this->getInstrumentsTarget = "/spot/v1/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 {
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;
} else {
channelId = CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH;
}
}
}
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;
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();
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);
}
}
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());
}
}
}
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();
auto optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
std::string exchangeSubscriptionId = channelId + "|" + symbolId;
const rj::Value& data = document["data"];
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())});
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())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
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));
for (const auto& x : data[bidsName].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;
}
const char* asksName = "a";
int askIndex = 0;
for (const auto& x : data[asksName].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 (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"});
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;
req.target(target);
} break;
case Request::Operation::GET_INSTRUMENTS: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
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["name"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCurrency"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCurrency"].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());
}
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"].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"});
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"].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["result"].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_H_
@@ -0,0 +1,269 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_COINBASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_COINBASE_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_COINBASE
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceCoinbase : public MarketDataService {
public:
MarketDataServiceCoinbase(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_COINBASE;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->getRecentTradesTarget = "/products/<product-id>/trades";
this->getInstrumentTarget = "/products/<product-id>";
this->getInstrumentsTarget = "/products";
}
virtual ~MarketDataServiceCoinbase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
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("type", rj::Value("subscribe").Move(), allocator);
rj::Value channels(rj::kArrayType);
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
rj::Value channel(rj::kObjectType);
rj::Value symbolIds(rj::kArrayType);
for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
std::string symbolId = subscriptionListBySymbolId.first;
symbolIds.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
std::string exchangeSubscriptionId = channelId + "|" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
}
channel.AddMember("name", rj::Value(channelId.c_str(), allocator).Move(), allocator);
channel.AddMember("product_ids", symbolIds, allocator);
channels.PushBack(channel, allocator);
rj::Value heartbeatChannel(rj::kObjectType);
heartbeatChannel.AddMember("name", rj::Value("heartbeat").Move(), allocator);
rj::Value heartbeatSymbolIds(rj::kArrayType);
for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
heartbeatSymbolIds.PushBack(rj::Value(subscriptionListBySymbolId.first.c_str(), allocator).Move(), allocator);
}
heartbeatChannel.AddMember("product_ids", heartbeatSymbolIds, allocator);
channels.PushBack(heartbeatChannel, allocator);
}
document.AddMember("channels", channels, 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 {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
auto type = std::string(document["type"].GetString());
if (type == "l2update") {
auto symbolId = std::string(document["product_id"].GetString());
auto exchangeSubscriptionId = std::string(CCAPI_WEBSOCKET_COINBASE_CHANNEL_LEVEL2) + "|" + symbolId;
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::parse(std::string(document["time"].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
const rj::Value& changes = document["changes"];
for (const auto& change : changes.GetArray()) {
auto side = std::string(change[0].GetString());
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(change[1].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(change[2].GetString())});
if (side == "buy") {
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
} else {
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (type == "match") {
auto symbolId = std::string(document["product_id"].GetString());
auto exchangeSubscriptionId = std::string(CCAPI_WEBSOCKET_COINBASE_CHANNEL_MATCH) + "|" + symbolId;
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::parse(std::string(document["time"].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(document["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(document["size"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(document["trade_id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(document["side"].GetString()) == "buy" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (type == "snapshot") {
auto symbolId = std::string(document["product_id"].GetString());
auto exchangeSubscriptionId = std::string(CCAPI_WEBSOCKET_COINBASE_CHANNEL_LEVEL2) + "|" + symbolId;
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = timeReceived;
const rj::Value& bids = document["bids"];
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));
}
const rj::Value& asks = document["asks"];
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 (type == "subscriptions") {
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()) {
for (const auto& x : document["channels"].GetArray()) {
std::string channelId = x["name"].GetString();
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
for (const auto& y : x["product_ids"].GetArray()) {
std::string symbolId = y.GetString();
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 (type == "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);
}
}
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, {
{"<product-id>", 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->getInstrumentTarget;
this->substituteParam(target, {
{"<product-id>", symbolId},
});
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["id"].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, x["quote_increment"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["base_increment"].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::parse(std::string(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::TRADE_ID, std::string(x["trade_id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["side"].GetString()) == "buy" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
Element element;
this->extractInstrumentInfo(element, document);
message.setElementList({element});
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);
}
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_COINBASE_H_
@@ -0,0 +1,338 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_CRYPTOCOM_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_CRYPTOCOM_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_CRYPTOCOM
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceCryptocom : public MarketDataService {
public:
MarketDataServiceCryptocom(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_CRYPTOCOM;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/market";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->getRecentTradesTarget = "/v2/public/get-trades";
this->getInstrumentTarget = "/v2/public/get-instruments";
this->getInstrumentsTarget = "/v2/public/get-instruments";
}
virtual ~MarketDataServiceCryptocom() {}
#ifndef CCAPI_EXPOSE_INTERNAL
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 {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
if (field == CCAPI_MARKET_DEPTH) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({10, 150}));
channelId = CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_BOOK;
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
}
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();
auto now = UtilTime::now();
int64_t requestId = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
document.AddMember("id", rj::Value(requestId).Move(), allocator);
document.AddMember("method", rj::Value("subscribe").Move(), allocator);
rj::Value channels(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_CRYPTOCOM_CHANNEL_BOOK) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
}
std::string exchangeSubscriptionId(channelId);
std::map<std::string, std::string> replaceMap;
if (channelId == CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_BOOK) {
int marketDepthSubscribedToExchange =
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
replaceMap = {
{"{instrument_name}", symbolId},
{"{depth}", std::to_string(marketDepthSubscribedToExchange)},
};
} else if (channelId == CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_TRADE) {
replaceMap = {
{"{instrument_name}", symbolId},
};
}
for (const auto& x : replaceMap) {
auto toReplace = x.first;
auto replacement = x.second;
if (exchangeSubscriptionId.find(toReplace) != std::string::npos) {
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), replacement);
}
}
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
channels.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
}
}
rj::Value params(rj::kObjectType);
params.AddMember("channels", channels, allocator);
document.AddMember("params", params, allocator);
document.AddMember("nonce", rj::Value(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()).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,
std::vector<MarketDataMessage>& marketDataMessageList) override {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
auto it = document.FindMember("id");
if (it == document.MemberEnd()) {
std::string method = document["method"].GetString();
const rj::Value& result = document["result"];
if (method == "subscribe") {
std::string exchangeSubscriptionId = result["subscription"].GetString();
const std::string& channelId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
const std::string& symbolId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID);
if (channelId == CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_BOOK) {
for (const auto& datum : result["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["t"].GetString())));
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
if (channelId == CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_BOOK) {
if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) {
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
} else {
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
}
auto optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
int bidIndex = 0;
for (const auto& x : datum["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 : datum["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 (channelId == CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_TRADE) {
for (const auto& x : result["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(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()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["d"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["s"].GetString()) == "SELL" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
} else {
std::string method = document["method"].GetString();
if (method == "subscribe") {
if (std::string(document["code"].GetString()) != "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});
messageList.emplace_back(std::move(message));
event.setMessageList(messageList);
} else {
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()) {
for (const auto& subscription : wsConnection.subscriptionList) {
correlationIdList.push_back(subscription.getCorrelationId());
}
}
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 (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();
ErrorCode ec;
this->send(hdl, msg, wspp::frame::opcode::text, ec);
if (ec) {
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request");
}
}
}
}
void appendParam(rj::Document& document, rj::Document::AllocatorType& allocator, int64_t requestId, const std::string& method,
const std::map<std::string, std::string>& param, const std::map<std::string, std::string> standardizationMap = {}) {
document.AddMember("id", rj::Value(requestId).Move(), allocator);
document.AddMember("method", rj::Value(method.c_str(), allocator).Move(), allocator);
rj::Value params(rj::kObjectType);
for (const auto& kv : param) {
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
auto value = kv.second;
if (value != "null") {
if (value == "true" || value == "false") {
params.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator);
} else {
params.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
}
}
document.AddMember("params", params, allocator);
}
void prepareReq(http::request<http::string_body>& req) {
req.set(beast::http::field::content_type, "application/json");
req.method(http::verb::get);
}
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);
switch (request.getOperation()) {
case Request::Operation::GENERIC_PUBLIC_REQUEST: {
MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential);
} break;
case Request::Operation::GET_RECENT_TRADES: {
std::string target = this->getRecentTradesTarget + "?instrument_name=" + symbolId;
req.target(target);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.target(this->getInstrumentTarget);
} break;
case Request::Operation::GET_INSTRUMENTS: {
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["instrument_name"].GetString());
element.insert(CCAPI_BASE_ASSET, x["base_currency"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quote_currency"].GetString());
int priceDecimals = std::stoi(x["price_decimals"].GetString());
if (priceDecimals > 0) {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(priceDecimals - 1, '0') + "1");
} else {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1");
}
int quantityDecimals = std::stoi(x["quantity_decimals"].GetString());
if (quantityDecimals > 0) {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "0." + std::string(quantityDecimals - 1, '0') + "1");
} else {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "1");
}
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["min_quantity"].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"]["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(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()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["d"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["s"].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()));
const rj::Value& instruments = document["result"]["instruments"];
std::vector<Element> elementList;
for (const auto& x : instruments.GetArray()) {
if (std::string(x["instrument_name"].GetString()) == request.getInstrument()) {
Element element;
this->extractInstrumentInfo(element, x);
elementList.push_back(element);
break;
}
}
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()));
const rj::Value& instruments = document["result"]["instruments"];
std::vector<Element> elementList;
for (const auto& x : instruments.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_CRYPTOCOM_H_
@@ -0,0 +1,473 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_DERIBIT_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_DERIBIT_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceDeribit : public MarketDataService {
public:
MarketDataServiceDeribit(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_DERIBIT;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/api/v2";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->restTarget = "/api/v2";
this->getRecentTradesTarget = "/public/get_last_trades_by_instrument";
this->getInstrumentTarget = "/public/get_instrument";
this->getInstrumentsTarget = "/public/get_instruments";
}
virtual ~MarketDataServiceDeribit() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
void onOpen(wspp::connection_hdl hdl) override {
MarketDataService::onOpen(hdl);
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
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/set_heartbeat",
{
{"interval", "10"},
});
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string msg = stringBuffer.GetString();
ErrorCode ec;
this->send(hdl, msg, wspp::frame::opcode::text, ec);
if (ec) {
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request");
}
}
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));
if (field == CCAPI_MARKET_DEPTH) {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_DERIBIT_CHANNEL_QUOTE;
} else if (marketDepthRequested <= 20) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({10, 20}));
channelId = CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK;
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
} else {
channelId = CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK_TBT;
}
}
}
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("jsonrpc", rj::Value("2.0").Move(), allocator);
document.AddMember("method", rj::Value("public/subscribe").Move(), allocator);
auto now = UtilTime::now();
int64_t requestId = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
document.AddMember("id", rj::Value(requestId).Move(), allocator);
this->subscriptionJsonrpcIdSetByConnectionIdMap[wsConnection.id].insert(requestId);
rj::Value channels(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_DERIBIT_CHANNEL_QUOTE || channelId == CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
}
std::string exchangeSubscriptionId(channelId);
std::map<std::string, std::string> replaceMap;
if (channelId == CCAPI_WEBSOCKET_DERIBIT_CHANNEL_QUOTE) {
replaceMap = {
{"{instrument_name}", symbolId},
};
} else if (channelId == CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK) {
int marketDepthSubscribedToExchange =
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
replaceMap = {
{"{instrument_name}", symbolId},
{"{group}", "none"},
{"{depth}", std::to_string(marketDepthSubscribedToExchange)},
{"{interval}", "100ms"},
};
} else if (channelId == CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK_TBT) {
replaceMap = {
{"{instrument_name}", symbolId},
{"{interval}", "raw"},
};
} else if (channelId == CCAPI_WEBSOCKET_DERIBIT_CHANNEL_TRADES) {
replaceMap = {
{"{instrument_name}", symbolId},
{"{interval}", "raw"},
};
}
for (const auto& x : replaceMap) {
auto toReplace = x.first;
auto replacement = x.second;
if (exchangeSubscriptionId.find(toReplace) != std::string::npos) {
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), replacement);
}
}
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
channels.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
}
}
rj::Value params(rj::kObjectType);
params.AddMember("channels", channels, 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 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 it = document.FindMember("result");
if (it == document.MemberEnd()) {
std::string method = document["method"].GetString();
const rj::Value& params = document["params"];
if (method == "subscription") {
std::string exchangeSubscriptionId = params["channel"].GetString();
const std::string& channelId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
const std::string& symbolId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID);
const rj::Value& data = params["data"];
if (channelId == CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK || channelId == CCAPI_WEBSOCKET_DERIBIT_CHANNEL_QUOTE ||
channelId == CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK_TBT) {
MarketDataMessage marketDataMessage;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(data["timestamp"].GetString())));
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
if (channelId == CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK) {
if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) {
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
} else {
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
}
auto optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
int bidIndex = 0;
for (const auto& x : data["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 : data["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;
}
} else if (channelId == CCAPI_WEBSOCKET_DERIBIT_CHANNEL_QUOTE) {
if (this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]) {
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
} else {
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
}
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["best_bid_price"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["best_bid_amount"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["best_ask_price"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["best_ask_amount"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
} else if (channelId == CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK_TBT) {
auto it = data.FindMember("prev_change_id");
if (it == data.MemberEnd() || it->value.IsNull()) {
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
} else {
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
}
for (const auto& x : data["bids"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[1].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[2].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
for (const auto& x : data["asks"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[1].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[2].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId == CCAPI_WEBSOCKET_DERIBIT_CHANNEL_TRADES) {
for (const auto& x : data.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(x["timestamp"].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["amount"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["trade_id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SEQUENCE_NUMBER, std::string(x["trade_seq"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["direction"].GetString()) == "sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
} else if (method == "heartbeat") {
std::string type = document["params"]["type"].GetString();
if (type == "test_request") {
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/test", {});
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string msg = stringBuffer.GetString();
ErrorCode ec;
this->send(hdl, msg, wspp::frame::opcode::text, ec);
if (ec) {
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request");
}
}
}
} else {
auto it = document.FindMember("id");
if (it != document.MemberEnd()) {
int64_t id = std::stoll(it->value.GetString());
if (this->subscriptionJsonrpcIdSetByConnectionIdMap.at(wsConnection.id).find(id) !=
this->subscriptionJsonrpcIdSetByConnectionIdMap.at(wsConnection.id).end()) {
if (document["result"].GetArray().Empty()) {
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 {
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()) {
for (const auto& x : document["result"].GetArray()) {
std::string exchangeSubscriptionId = x.GetString();
const std::string& channelId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
const std::string& symbolId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(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(Message::Type::SUBSCRIPTION_STARTED);
Element element;
element.insert(CCAPI_INFO_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
event.setMessageList(messageList);
}
}
this->subscriptionJsonrpcIdSetByConnectionIdMap.at(wsConnection.id).erase(id);
}
}
}
void appendParam(rj::Document& document, rj::Document::AllocatorType& allocator, int64_t requestId, const std::string& method,
const std::map<std::string, std::string>& param, const std::map<std::string, std::string> standardizationMap = {}) {
document.AddMember("jsonrpc", rj::Value("2.0").Move(), allocator);
document.AddMember("id", rj::Value(requestId).Move(), allocator);
document.AddMember("method", rj::Value(method.c_str(), allocator).Move(), allocator);
rj::Value params(rj::kObjectType);
for (const auto& kv : param) {
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
auto value = kv.second;
if (value != "null") {
if (value == "true" || value == "false") {
params.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator);
} else {
params.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
}
}
document.AddMember("params", params, allocator);
}
void appendSymbolId(rj::Document& document, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
document["params"].AddMember("instrument_name", rj::Value(symbolId.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 {
int64_t requestId = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
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::post);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(document, allocator, requestId, this->getRecentTradesTarget, param,
{
{CCAPI_LIMIT, "count"},
});
if (document["params"].FindMember("sorting") == document["params"].MemberEnd()) {
document["params"].AddMember("sorting", rj::Value("desc").Move(), allocator);
}
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();
req.target(this->restTarget);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::post);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, requestId, this->getInstrumentTarget, {});
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();
req.target(this->restTarget);
} break;
case Request::Operation::GET_INSTRUMENTS: {
req.method(http::verb::post);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(document, allocator, requestId, this->getInstrumentsTarget, param,
{
{CCAPI_EM_ASSET, "currency"},
});
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
auto body = stringBuffer.GetString();
req.body() = body;
req.prepare_payload();
req.target(this->restTarget);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractInstrumentInfo(Element& element, const rj::Value& x) {
element.insert(CCAPI_INSTRUMENT, x["instrument_name"].GetString());
element.insert(CCAPI_MARGIN_ASSET, x["base_currency"].GetString());
element.insert(CCAPI_UNDERLYING_SYMBOL, x["base_currency"].GetString());
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["tick_size"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["contract_size"].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"]["trades"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(x["timestamp"].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["amount"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["trade_id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SEQUENCE_NUMBER, std::string(x["trade_seq"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["direction"].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()));
const rj::Value& result = document["result"];
Element element;
this->extractInstrumentInfo(element, result);
message.setElementList({element});
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()));
const rj::Value& result = document["result"];
std::vector<Element> elementList;
for (const auto& x : result.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);
}
}
void onClose(wspp::connection_hdl hdl) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
this->subscriptionJsonrpcIdSetByConnectionIdMap.erase(wsConnection.id);
MarketDataService::onClose(hdl);
}
std::map<std::string, std::set<int64_t>> subscriptionJsonrpcIdSetByConnectionIdMap;
std::string restTarget;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_DERIBIT_H_
@@ -0,0 +1,170 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_ERISX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_ERISX_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_ERISX
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceErisx : public MarketDataService {
public:
MarketDataServiceErisx(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_ERISX;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
// this->convertNumberToStringInJsonRegex = std::regex("(\\[|,|\":)(-?\\d+\\.?\\d*)");
}
virtual ~MarketDataServiceErisx() {}
#ifndef CCAPI_EXPOSE_INTERNAL
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 {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
if (field == CCAPI_MARKET_DEPTH) {
if (marketDepthRequested <= 20) {
channelId = std::string(CCAPI_WEBSOCKET_ERISX_CHANNEL_TOP_OF_BOOK_MARKET_DATA_SUBSCRIBE) + "?" + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" +
std::to_string(marketDepthRequested);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthRequested;
} else {
channelId += "|" + field;
}
} else if (field == CCAPI_TRADE) {
channelId += "|" + field;
}
}
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& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
std::string symbolId = subscriptionListBySymbolId.first;
std::string exchangeSubscriptionId = std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]);
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
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("correlation", rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
document.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
if (channelId.rfind(CCAPI_WEBSOCKET_ERISX_CHANNEL_MARKET_DATA_SUBSCRIBE, 0) == 0) {
document.AddMember("type", rj::Value(CCAPI_WEBSOCKET_ERISX_CHANNEL_MARKET_DATA_SUBSCRIBE).Move(), allocator);
if (UtilString::split(channelId, "|").at(1) == CCAPI_TRADE) {
document.AddMember("tradeOnly", rj::Value(true).Move(), allocator);
}
} else if (channelId.rfind(CCAPI_WEBSOCKET_ERISX_CHANNEL_TOP_OF_BOOK_MARKET_DATA_SUBSCRIBE, 0) == 0) {
document.AddMember("type", rj::Value(CCAPI_WEBSOCKET_ERISX_CHANNEL_TOP_OF_BOOK_MARKET_DATA_SUBSCRIBE).Move(), allocator);
int marketDepthSubscribedToExchange =
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
document.AddMember("topOfBookDepth", rj::Value(marketDepthSubscribedToExchange).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,
std::vector<MarketDataMessage>& marketDataMessageList) override {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
std::string type = document["type"].GetString();
if (type == "MarketDataIncrementalRefresh" || type == "MarketDataIncrementalRefreshTrade") {
std::string exchangeSubscriptionId = document["correlation"].GetString();
auto channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
auto symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID);
MarketDataMessage::RecapType recapType;
if (std::string(document["marketDataID"].GetString()) == "0") {
recapType = MarketDataMessage::RecapType::SOLICITED;
} else {
recapType = MarketDataMessage::RecapType::NONE;
}
if (type == "MarketDataIncrementalRefresh") {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = recapType;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::parse(UtilTime::convertFIXTimeToISO(std::string(document["transactTime"].GetString())));
for (const auto& side : {"bids", "offers"}) {
for (const auto& x : document[side].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x["price"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE,
std::string(x["updateAction"].GetString()) == "DELETE" ? "0" : UtilString::normalizeDecimalString(x["amount"].GetString())});
marketDataMessage.data[strcmp(side, "bids") == 0 ? MarketDataMessage::DataType::BID : MarketDataMessage::DataType::ASK].push_back(
std::move(dataPoint));
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else {
for (const auto& x : document["trades"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.tp = UtilTime::parse(UtilTime::convertFIXTimeToISO(std::string(x["transactTime"].GetString())));
marketDataMessage.recapType = recapType;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
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::TRADE_ID, ""});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["tickerType"].GetString()) == "GIVEN" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
} else if (type == "TopOfBookMarketData") {
std::string exchangeSubscriptionId = document["correlation"].GetString();
auto channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
auto symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID);
MarketDataMessage marketDataMessage;
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;
}
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
std::string latestFIXTime;
for (const auto& side : {"bids", "offers"}) {
for (const auto& x : document[side].GetArray()) {
if (std::string(x["action"].GetString()) != "NO CHANGE") {
std::string lastUpdate = x["lastUpdate"].GetString();
if (lastUpdate > latestFIXTime) {
latestFIXTime = lastUpdate;
}
}
}
}
marketDataMessage.tp = UtilTime::parse(UtilTime::convertFIXTimeToISO(latestFIXTime));
for (const auto& side : {"bids", "offers"}) {
for (const auto& x : document[side].GetArray()) {
if (std::string(x["action"].GetString()) != "NO CHANGE") {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x["price"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE,
std::string(x["action"].GetString()) == "DELETE" ? "0" : UtilString::normalizeDecimalString(x["totalVolume"].GetString())});
marketDataMessage.data[strcmp(side, "bids") == 0 ? MarketDataMessage::DataType::BID : MarketDataMessage::DataType::ASK].push_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 {
// TODO(cryptochassis): implement
}
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
// TODO(cryptochassis): implement
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_ERISX_H_
@@ -0,0 +1,27 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_FTX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_FTX_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_FTX
#include "ccapi_cpp/service/ccapi_market_data_service_ftx_base.h"
namespace ccapi {
class MarketDataServiceFtx : public MarketDataServiceFtxBase {
public:
MarketDataServiceFtx(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
}
virtual ~MarketDataServiceFtx() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_FTX_H_
@@ -0,0 +1,337 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_FTX_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_FTX_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#if defined(CCAPI_ENABLE_EXCHANGE_FTX) || defined(CCAPI_ENABLE_EXCHANGE_FTX_US)
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceFtxBase : public MarketDataService {
public:
MarketDataServiceFtxBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->shouldAlignSnapshot = true;
this->getRecentTradesTarget = "/api/markets/{market_name}/trades";
this->getInstrumentTarget = "/api/markets/{market_name}";
this->getInstrumentsTarget = "/api/markets";
// this->convertNumberToStringInJsonRegex = std::regex("(\\[|,|\":)\\s?(-?\\d+\\.?\\d*[eE]?-?\\d*)");
}
virtual ~MarketDataServiceFtxBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
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 {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
if (field == CCAPI_MARKET_DEPTH) {
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = 100;
}
}
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)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
rj::Value channel(rj::kObjectType);
rj::Value symbolIds(rj::kArrayType);
for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
std::string symbolId = subscriptionListBySymbolId.first;
symbolIds.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
std::string exchangeSubscriptionId = channelId + "|" + symbolId;
std::string market = symbolId;
std::string channelIdString = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
document.AddMember("channel", rj::Value(channelIdString.c_str(), allocator).Move(), allocator);
document.AddMember("market", rj::Value(market.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;
}
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 < 100 && (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 {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
auto type = std::string(document["type"].GetString());
if (type == "update") {
const rj::Value& data = document["data"];
auto symbolId = std::string(document["market"].GetString());
auto channel = std::string(document["channel"].GetString());
auto exchangeSubscriptionId = channel + "|" + symbolId;
if (channel == CCAPI_WEBSOCKET_FTX_BASE_CHANNEL_ORDERBOOKS) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
auto timePair = UtilTime::divide(data["time"].GetString());
auto tp = TimePoint(std::chrono::duration<int64_t>(timePair.first));
tp += std::chrono::nanoseconds(timePair.second);
marketDataMessage.tp = tp;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
const rj::Value& asks = data["asks"];
const rj::Value& bids = data["bids"];
for (auto& ask : asks.GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
if (this->sessionOptions.enableCheckOrderBookChecksum) {
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, ask[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, ask[1].GetString()});
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(ask[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(ask[1].GetString())});
}
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
for (auto& bid : bids.GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
if (this->sessionOptions.enableCheckOrderBookChecksum) {
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, bid[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, bid[1].GetString()});
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(bid[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(bid[1].GetString())});
}
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
if (this->sessionOptions.enableCheckOrderBookChecksum) {
this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId] =
intToHex(static_cast<uint_fast32_t>(static_cast<uint32_t>(std::stoul(data["checksum"].GetString()))));
}
} else if (channel == CCAPI_WEBSOCKET_FTX_BASE_CHANNEL_TRADES) {
for (const auto& x : data.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::parse(std::string(x["time"].GetString()), "%FT%T%Ez");
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
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::TRADE_ID, std::string(x["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["side"].GetString()) == "sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
} else if (type == "partial") {
const rj::Value& data = document["data"];
auto symbolId = std::string(document["market"].GetString());
auto exchangeSubscriptionId = std::string(CCAPI_WEBSOCKET_FTX_BASE_CHANNEL_ORDERBOOKS) + "|" + symbolId;
if (this->sessionOptions.enableCheckOrderBookChecksum) {
this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId] =
intToHex(static_cast<uint_fast32_t>(static_cast<uint32_t>(std::stoul(data["checksum"].GetString()))));
}
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
auto timePair = UtilTime::divide(std::string(data["time"].GetString()));
auto tp = TimePoint(std::chrono::duration<int64_t>(timePair.first));
tp += std::chrono::nanoseconds(timePair.second);
marketDataMessage.tp = tp;
const rj::Value& bids = data["bids"];
for (auto& x : 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));
}
const rj::Value& asks = data["asks"];
for (auto& x : 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 (type == "subscribed") {
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["channel"].GetString();
std::string symbolId = document["market"].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 (type == "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);
}
}
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_name}", Url::urlEncode(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->getInstrumentTarget;
this->substituteParam(target, {
{"{market_name}", Url::urlEncode(symbolId)},
});
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["name"].GetString());
if (!x["baseCurrency"].IsNull()) {
element.insert(CCAPI_BASE_ASSET, x["baseCurrency"].GetString());
}
if (!x["quoteCurrency"].IsNull()) {
element.insert(CCAPI_QUOTE_ASSET, x["quoteCurrency"].GetString());
}
if (!x["priceIncrement"].IsNull()) {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["priceIncrement"].GetString());
}
if (!x["sizeIncrement"].IsNull()) {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["sizeIncrement"].GetString());
}
if (!x["underlying"].IsNull()) {
element.insert(CCAPI_UNDERLYING_SYMBOL, x["underlying"].GetString());
}
if (!x["minProvideSize"].IsNull()) {
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minProvideSize"].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"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.tp = UtilTime::parse(std::string(x["time"].GetString()), "%FT%T%Ez");
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::TRADE_ID, std::string(x["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["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()));
const rj::Value& result = document["result"];
Element element;
this->extractInstrumentInfo(element, result);
message.setElementList({element});
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()));
const rj::Value& result = document["result"];
std::vector<Element> elementList;
for (const auto& x : result.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_FTX_BASE_H_
@@ -0,0 +1,27 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_FTX_US_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_FTX_US_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_FTX_US
#include "ccapi_cpp/service/ccapi_market_data_service_ftx_base.h"
namespace ccapi {
class MarketDataServiceFtxUs : public MarketDataServiceFtxBase {
public:
MarketDataServiceFtxUs(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
}
virtual ~MarketDataServiceFtxUs() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_FTX_US_H_
@@ -0,0 +1,138 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_GATEIO_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_GATEIO_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_GATEIO
#include "ccapi_cpp/service/ccapi_market_data_service_gateio_base.h"
namespace ccapi {
class MarketDataServiceGateio : public MarketDataServiceGateioBase {
public:
MarketDataServiceGateio(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_GATEIO_API_KEY;
this->setupCredential({this->apiKeyName});
std::string prefix = "/api/v4";
this->getRecentTradesTarget = prefix + "/spot/trades";
this->getInstrumentTarget = prefix + "/spot/currency_pairs/{currency_pair}";
this->getInstrumentsTarget = prefix + "/spot/currency_pairs";
this->websocketChannelTrades = CCAPI_WEBSOCKET_GATEIO_CHANNEL_TRADES;
this->websocketChannelBookTicker = CCAPI_WEBSOCKET_GATEIO_CHANNEL_BOOK_TICKER;
this->websocketChannelOrderBook = CCAPI_WEBSOCKET_GATEIO_CHANNEL_ORDER_BOOK;
this->symbolName = "currency_pair";
}
virtual ~MarketDataServiceGateio() {}
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("Accept", "application/json");
req.set(beast::http::field::content_type, "application/json");
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, symbolName);
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
this->substituteParam(target, {
{"{currency_pair}", symbolId},
});
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["id"].GetString());
element.insert(CCAPI_BASE_ASSET, x["base"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quote"].GetString());
int precision = std::stoi(x["precision"].GetString());
if (precision > 0) {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(precision - 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 {
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::makeTimePointMilli(UtilTime::divideMilli(x["create_time_ms"].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["amount"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["side"].GetString()) == "buy" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
Element element;
this->extractInstrumentInfo(element, document);
message.setElementList({element});
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.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_GATEIO_H_
@@ -0,0 +1,308 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_GATEIO_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_GATEIO_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#if defined(CCAPI_ENABLE_EXCHANGE_GATEIO) || defined(CCAPI_ENABLE_EXCHANGE_GATEIO_PERPETUAL_FUTURES)
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceGateioBase : public MarketDataService {
public:
MarketDataServiceGateioBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~MarketDataServiceGateioBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
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 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 (marketDepthRequested == 1) {
channelId = this->websocketChannelBookTicker;
} else {
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);
std::string updateSpeed;
if (this->isDerivatives) {
updateSpeed = "0";
} else {
if (conflateIntervalMilliSeconds < 1000) {
updateSpeed = "100ms";
} else {
updateSpeed = "1000ms";
}
}
if (!updateSpeed.empty()) {
channelId += "&UPDATE_SPEED=" + updateSpeed;
}
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
auto now = UtilTime::now();
std::vector<std::string> sendStringList;
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
if (channelId == this->websocketChannelBookTicker || channelId == this->websocketChannelTrades) {
std::vector<std::string> exchangeSubscriptionIdList;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
document.AddMember("time", rj::Value(UtilTime::getUnixTimestamp(now)).Move(), allocator);
document.AddMember("channel", rj::Value(channelId.c_str(), allocator).Move(), allocator);
rj::Value payload(rj::kArrayType);
for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListByInstrument.first;
if (channelId == this->websocketChannelBookTicker) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
}
payload.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
std::string exchangeSubscriptionId = channelId + "|" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
}
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]] =
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);
} else if (channelId.rfind(this->websocketChannelOrderBook, 0) == 0) {
for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListByInstrument.first;
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
int marketDepthSubscribedToExchange =
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
document.AddMember("time", rj::Value(UtilTime::getUnixTimestamp(now)).Move(), allocator);
document.AddMember("channel", rj::Value(this->websocketChannelOrderBook.c_str(), allocator).Move(), allocator);
rj::Value payload(rj::kArrayType);
payload.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
payload.PushBack(rj::Value(std::to_string(marketDepthSubscribedToExchange).c_str(), allocator).Move(), allocator);
auto splitted = UtilString::split(channelId, "?");
if (splitted.size() == 2) {
auto mapped = Url::convertQueryStringToMap(splitted.at(1));
if (mapped.find("UPDATE_SPEED") != mapped.end()) {
payload.PushBack(rj::Value(mapped.at("UPDATE_SPEED").c_str(), allocator).Move(), allocator);
}
}
document.AddMember("payload", payload, allocator);
std::string exchangeSubscriptionId = std::string(this->websocketChannelOrderBook) + "|" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
if (!this->isDerivatives) {
std::vector<std::string> exchangeSubscriptionIdList;
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap[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.HasMember("event") && std::string(document["event"].GetString()) == "subscribe") {
event.setType(Event::Type::SUBSCRIPTION_STATUS);
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
std::vector<std::string> correlationIdList;
if (document.HasMember("id") && !document["id"].IsNull()) {
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)) {
auto splitted = UtilString::split(exchangeSubscriptionId, '|');
std::string channelId = splitted.at(0);
std::string symbolId = splitted.at(1);
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) {
std::vector<std::string> correlationIdList_2 =
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end());
}
}
}
}
}
}
message.setCorrelationIdList(correlationIdList);
bool hasError = document.HasMember("error") && !document["error"].IsNull();
message.setType(!hasError ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(!hasError ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
event.setMessageList(messageList);
} else if (document.HasMember("event")) {
std::string eventType = document["event"].GetString();
if (eventType == "update" || eventType == "all") {
std::string channel = document["channel"].GetString();
const rj::Value& result = document["result"];
std::string symbol;
if (result.IsObject()) {
auto it = result.FindMember(symbolName.c_str());
auto its = result.FindMember("s");
symbol = it != result.MemberEnd() ? it->value.GetString() : (its != result.MemberEnd() ? its->value.GetString() : "");
}
MarketDataMessage marketDataMessage;
std::string exchangeSubscriptionId;
std::string channelId;
std::string symbolId;
std::map<std::string, std::string> optionMap;
if (!symbol.empty()) {
exchangeSubscriptionId = channel + "|" + symbol;
channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
} else {
channelId = channel;
}
if (channelId == this->websocketChannelBookTicker) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(result["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
{
std::string p = result["b"].GetString();
if (!p.empty()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(p)});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(result["B"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
}
{
std::string p = result["a"].GetString();
if (!p.empty()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(p)});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(result["A"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId.rfind(this->websocketChannelOrderBook, 0) == 0) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(result["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
int bidIndex = 0;
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
for (const auto& x : result["bids"].GetArray()) {
if (bidIndex >= maxMarketDepth) {
break;
}
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString((this->isDerivatives ? x["p"] : x[0]).GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString((this->isDerivatives ? x["s"] : x[1]).GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
++bidIndex;
}
int askIndex = 0;
for (const auto& x : result["asks"].GetArray()) {
if (askIndex >= maxMarketDepth) {
break;
}
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString((this->isDerivatives ? x["p"] : x[0]).GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString((this->isDerivatives ? x["s"] : x[1]).GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
++askIndex;
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId == this->websocketChannelTrades) {
if (this->isDerivatives) {
for (const auto& x : result.GetArray()) {
symbol = x["contract"].GetString();
exchangeSubscriptionId = channel + "|" + symbol;
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::makeTimePointMilli(UtilTime::divideMilli(x["create_time_ms"].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
std::string size = x["size"].GetString();
std::string sizeAbs;
bool isBuyerMaker;
if (size.at(0) == '-') {
sizeAbs = size.substr(1);
isBuyerMaker = true;
} else {
sizeAbs = size;
isBuyerMaker = false;
}
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(sizeAbs)});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, isBuyerMaker ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::makeTimePointMilli(UtilTime::divideMilli(result["create_time_ms"].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(result["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(result["amount"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(result["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(result["side"].GetString()) == "sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
}
}
bool isDerivatives{};
std::string symbolName;
std::string websocketChannelTrades;
std::string websocketChannelBookTicker;
std::string websocketChannelOrderBook;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_GATEIO_BASE_H_
@@ -0,0 +1,171 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_GATEIO_PERPETUAL_FUTURES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_GATEIO_PERPETUAL_FUTURES_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_GATEIO_PERPETUAL_FUTURES
#include "ccapi_cpp/service/ccapi_market_data_service_gateio_base.h"
namespace ccapi {
class MarketDataServiceGateioPerpetualFutures : public MarketDataServiceGateioBase {
public:
MarketDataServiceGateioPerpetualFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->apiKeyName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY;
this->setupCredential({this->apiKeyName});
std::string prefix = "/api/v4";
this->getRecentTradesTarget = prefix + "/futures/{settle}/trades";
this->getInstrumentTarget = prefix + "/futures/{settle}/contracts/{contract}";
this->getInstrumentsTarget = prefix + "/futures/{settle}/contracts";
this->isDerivatives = true;
this->websocketChannelTrades = CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_TRADES;
this->websocketChannelBookTicker = CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_BOOK_TICKER;
this->websocketChannelOrderBook = CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_ORDER_BOOK;
this->symbolName = "contract";
}
virtual ~MarketDataServiceGateioPerpetualFutures() {}
std::string getInstrumentGroup(const Subscription& subscription) override {
auto instrument = subscription.getInstrument();
std::string url(this->baseUrl);
if (UtilString::endsWith(instrument, "_USD")) {
url += "btc";
} else if (UtilString::endsWith(instrument, "_USDT")) {
url += "usdt";
}
return url + "|" + subscription.getField() + "|" + subscription.getSerializedOptions();
}
void substituteParamSettle(std::string& target, const std::map<std::string, std::string>& param, const std::string& symbolId) {
this->substituteParam(target, param,
{
{"settle", "{settle}"},
{CCAPI_MARGIN_ASSET, "{settle}"},
});
std::string settle;
if (UtilString::endsWith(symbolId, "_USD")) {
settle = "btc";
} else if (UtilString::endsWith(symbolId, "_USDT")) {
settle = "usdt";
}
this->substituteParam(target, {
{"{settle}", settle},
});
}
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("Accept", "application/json");
req.set(beast::http::field::content_type, "application/json");
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;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->substituteParamSettle(target, param, symbolId);
std::string queryString;
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
});
this->appendSymbolId(queryString, symbolId, symbolName);
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->substituteParamSettle(target, param, symbolId);
this->substituteParam(target, {
{"{contract}", symbolId},
});
req.target(target);
} break;
case Request::Operation::GET_INSTRUMENTS: {
req.method(http::verb::get);
auto target = this->getInstrumentsTarget;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->substituteParam(target, param,
{
{"settle", "{settle}"},
{CCAPI_MARGIN_ASSET, "{settle}"},
});
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["name"].GetString());
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["order_price_round"].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::makeTimePointMilli(UtilTime::divideMilli(x["create_time_ms"].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
std::string size = x["size"].GetString();
std::string sizeAbs;
bool isBuyerMaker;
if (size.at(0) == '-') {
sizeAbs = size.substr(1);
isBuyerMaker = true;
} else {
sizeAbs = size;
isBuyerMaker = false;
}
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(sizeAbs)});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, isBuyerMaker ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
Element element;
this->extractInstrumentInfo(element, document);
message.setElementList({element});
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.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_GATEIO_PERPETUAL_FUTURES_H_
@@ -0,0 +1,303 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_GEMINI_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_GEMINI_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_GEMINI
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceGemini : public MarketDataService {
public:
MarketDataServiceGemini(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_GEMINI;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v1/marketdata";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->getRecentTradesTarget = "/v1/trades/:symbol";
this->getInstrumentTarget = "/v1/symbols/details/:symbol";
this->getInstrumentsTarget = "/v1/symbols";
}
virtual ~MarketDataServiceGemini() {}
#ifndef CCAPI_EXPOSE_INTERNAL
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 {
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) {
int marketDepthSubscribedToExchange = 1;
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 { return std::vector<std::string>(); }
void onOpen(wspp::connection_hdl hdl) override {
MarketDataService::onOpen(hdl);
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
std::vector<std::string> correlationIdList;
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
for (auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListByInstrument.first;
int marketDepthSubscribedToExchange = this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
if (marketDepthSubscribedToExchange == 1) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
}
auto exchangeSubscriptionId = wsConnection.url;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
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 timeReceived = UtilTime::now();
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);
messageList.emplace_back(std::move(message));
event.setMessageList(messageList);
this->eventHandler(event, nullptr);
}
void onClose(wspp::connection_hdl hdl) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
this->sequenceByConnectionIdMap.erase(wsConnection.id);
MarketDataService::onClose(hdl);
}
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
auto type = std::string(document["type"].GetString());
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document["socket_sequence"].GetString());
if (!this->checkSequence(wsConnection, sequence)) {
this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, "");
return;
}
}
if (type == "update") {
MarketDataMessage marketDataMessage;
marketDataMessage.exchangeSubscriptionId = wsConnection.url;
TimePoint time = timeReceived;
auto it = document.FindMember("timestampms");
if (it != document.MemberEnd()) {
time = TimePoint(std::chrono::milliseconds(std::stoll(it->value.GetString())));
}
for (auto& event : document["events"].GetArray()) {
auto gType = std::string(event["type"].GetString());
if (gType == "change") {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(event["price"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(event["remaining"].GetString())});
auto isBid = std::string(event["side"].GetString()) == "bid";
std::string reason = event["reason"].GetString();
if (reason == "place" || reason == "cancel" || reason == "trade") {
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = time;
if (isBid) {
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
} else {
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
} else if (reason == "initial") {
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = time;
if (isBid) {
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
} else {
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
} else if (reason == "top-of-book") {
marketDataMessage.tp = time;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
if (isBid) {
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
} else {
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
}
} else if (gType == "trade") {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
std::string makerSide = event["makerSide"].GetString();
if (makerSide == "bid" || makerSide == "ask") {
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = time;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(event["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(event["amount"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(event["tid"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, makerSide == "bid" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
}
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
std::string getInstrumentGroup(const Subscription& subscription) override {
auto instrument = subscription.getInstrument();
auto symbolId = instrument;
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;
url += "?";
if ((parameterSet.find(CCAPI_WEBSOCKET_GEMINI_PARAMETER_BIDS) != parameterSet.end() ||
parameterSet.find(CCAPI_WEBSOCKET_GEMINI_PARAMETER_OFFERS) != parameterSet.end())) {
auto optionMap = subscription.getOptionMap();
if (std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)) == 1) {
parameterSet.insert(CCAPI_WEBSOCKET_GEMINI_PARAMETER_TOP_OF_BOOK);
}
}
parameterSet.insert("heartbeat");
bool isFirstParameter = true;
for (auto const& parameter : parameterSet) {
if (isFirstParameter) {
isFirstParameter = false;
} else {
url += "&";
}
url += parameter + "=true";
}
return url;
}
bool checkSequence(const WsConnection& wsConnection, int sequence) {
if (this->sequenceByConnectionIdMap.find(wsConnection.id) == this->sequenceByConnectionIdMap.end()) {
if (sequence != this->sessionConfigs.getInitialSequenceByExchangeMap().at(this->exchangeName)) {
CCAPI_LOGGER_WARN("incorrect initial sequence, wsConnection = " + toString(wsConnection));
return false;
}
this->sequenceByConnectionIdMap.insert(std::pair<std::string, int>(wsConnection.id, sequence));
return true;
} else {
if (sequence - this->sequenceByConnectionIdMap[wsConnection.id] == 1) {
this->sequenceByConnectionIdMap[wsConnection.id] = sequence;
return true;
} else {
return false;
}
}
}
void onOutOfSequence(WsConnection& wsConnection, int sequence, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
const std::string& exchangeSubscriptionId) {
int previous = 0;
if (this->sequenceByConnectionIdMap.find(wsConnection.id) != this->sequenceByConnectionIdMap.end()) {
previous = this->sequenceByConnectionIdMap[wsConnection.id];
}
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND,
"out of sequence: previous = " + toString(previous) + ", current = " + toString(sequence) + ", connection = " + toString(wsConnection) +
", textMessage = " + textMessage + ", timeReceived = " + UtilTime::getISOTimestamp(timeReceived));
ErrorCode ec;
this->close(wsConnection, hdl, websocketpp::close::status::normal, "out of sequence", ec);
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown");
}
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false;
}
void convertRequestForRest(http::request<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, {
{":symbol", symbolId},
});
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit_trades"},
});
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
this->substituteParam(target, {
{":symbol", symbolId},
});
req.target(target);
} break;
case Request::Operation::GET_INSTRUMENTS: {
req.method(http::verb::get);
req.target(this->getInstrumentTarget);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
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 = TimePoint(std::chrono::milliseconds(std::stoll(x["timestampms"].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["amount"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, x["tid"].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()));
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());
message.setElementList({element});
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;
element.insert(CCAPI_INSTRUMENT, x.GetString());
elementList.push_back(element);
}
message.setElementList(elementList);
message.setCorrelationIdList({request.getCorrelationId()});
event.addMessages({message});
} break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
std::map<std::string, int> sequenceByConnectionIdMap;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_GEMINI_H_
@@ -0,0 +1,105 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI
#include "ccapi_cpp/service/ccapi_market_data_service_huobi_base.h"
namespace ccapi {
class MarketDataServiceHuobi : public MarketDataServiceHuobiBase {
public:
MarketDataServiceHuobi(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataServiceHuobiBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
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 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::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
req.target(target);
} break;
case Request::Operation::GET_INSTRUMENTS: {
req.method(http::verb::get);
auto target = this->getInstrumentsTarget;
req.target(target);
} break;
default:
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()) {
case Request::Operation::GET_INSTRUMENT: {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
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: {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
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:
MarketDataServiceHuobiBase::convertTextMessageToMarketDataMessage(request, textMessage, timeReceived, event, marketDataMessageList);
}
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_H_
@@ -0,0 +1,352 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#if defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceHuobiBase : public MarketDataService {
public:
MarketDataServiceHuobiBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->needDecompressWebsocketMessage = true;
ErrorCode ec = this->inflater.init(false, 31);
if (ec) {
CCAPI_LOGGER_FATAL(ec.message());
}
// this->convertNumberToStringInJsonRegex = std::regex("(\\[|,|\":)\\s?(-?\\d+\\.?\\d*[eE]?-?\\d*)");
}
virtual ~MarketDataServiceHuobiBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
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;
}
}
}
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);
}
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 (auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
auto symbolId = subscriptionListByInstrument.first;
std::string exchangeSubscriptionId;
if (channelId.rfind(CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO, 0) == 0) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
exchangeSubscriptionId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO;
} else if (channelId.rfind(CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_DEPTH, 0) == 0) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
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;
}
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);
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(),
allocator);
} else {
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
}
this->exchangeSubscriptionIdByExchangeJsonPayloadIdMap[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = exchangeSubscriptionId;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.emplace_back(std::move(sendString));
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
}
}
return sendStringList;
}
std::string getInstrumentGroup(const Subscription& subscription) override {
auto url = this->baseUrl;
auto field = subscription.getField();
if (!this->isDerivatives) {
if (field == CCAPI_TRADE || field == CCAPI_MARKET_DEPTH) {
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 {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
if (document.IsObject() && document.HasMember("ch") && document.HasMember("tick")) {
std::string exchangeSubscriptionId = document["ch"].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];
if (std::regex_search(channelId, std::regex(CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO_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 = tick[this->isDerivatives ? "ts" : "quoteTime"].GetString();
ts.insert(ts.size() - 3, ".");
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(ts));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
if (this->isDerivatives) {
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(tick["bid"][0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(tick["bid"][1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(tick["ask"][0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(tick["ask"][1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else {
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(tick["bid"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(tick["bidSize"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(tick["ask"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(tick["askSize"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
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;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
const rj::Value& tick = document["tick"];
std::string ts = tick["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_TRADE_DETAIL_REGEX))) {
const rj::Value& tick = document["tick"];
for (const auto& x : tick["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
std::string ts = x["ts"].GetString();
ts.insert(ts.size() - 3, ".");
auto time = UtilTime::makeTimePoint(UtilTime::divide(ts));
marketDataMessage.tp = time;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
if (this->isDerivatives) {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, std::to_string(std::stoi(x["amount"].GetString()) / 2)});
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["amount"].GetString()))});
}
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x[this->isDerivatives ? "id" : "tradeId"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["direction"].GetString()) == "sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
} else if (document.IsObject() && document.HasMember("ping")) {
std::string payload("{\"pong\":");
payload += document["ping"].GetString();
payload += "}";
ErrorCode ec;
this->send(hdl, payload, wspp::frame::opcode::text, ec);
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "pong");
}
} else if (document.IsObject() && document.HasMember("status")) {
std::string status = document["status"].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 exchangeSubscriptionId = this->exchangeSubscriptionIdByExchangeJsonPayloadIdMap.at(std::stoi(document["id"].GetString()));
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(status == "ok" ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(status == "ok" ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
event.setMessageList(messageList);
}
}
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, "size"},
});
this->appendSymbolId(queryString, symbolId, this->isDerivatives ? "contract_code" : "symbol");
req.target(target + "?" + queryString);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractInstrumentInfo(Element& element, const rj::Value& x) {
element.insert(CCAPI_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");
}
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["limit-order-min-order-amt"].GetString());
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["min-order-value"].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()) {
for (const auto& x : datum["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
std::string ts = x["ts"].GetString();
ts.insert(ts.size() - 3, ".");
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(ts));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
if (this->isDerivatives) {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, std::to_string(std::stoi(x["amount"].GetString()) / 2)});
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["amount"].GetString()))});
}
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x[this->isDerivatives ? "id" : "trade-id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["direction"].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{};
std::map<int, std::string> exchangeSubscriptionIdByExchangeJsonPayloadIdMap;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_BASE_H_
@@ -0,0 +1,30 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_COIN_SWAP_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_COIN_SWAP_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP
#include "ccapi_cpp/service/ccapi_market_data_service_huobi_derivatives_base.h"
namespace ccapi {
class MarketDataServiceHuobiCoinSwap : public MarketDataServiceHuobiDerivativesBase {
public:
MarketDataServiceHuobiCoinSwap(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
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";
}
virtual ~MarketDataServiceHuobiCoinSwap() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_COIN_SWAP_H_
@@ -0,0 +1,84 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_DERIVATIVES_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_DERIVATIVES_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#if defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)
#include "ccapi_cpp/service/ccapi_market_data_service_huobi_base.h"
namespace ccapi {
class MarketDataServiceHuobiDerivativesBase : public MarketDataServiceHuobiBase {
public:
MarketDataServiceHuobiDerivativesBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataServiceHuobiBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->isDerivatives = true;
}
virtual ~MarketDataServiceHuobiDerivativesBase() {}
bool doesHttpBodyContainError(const Request& request, 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()) {
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
std::string queryString;
this->appendSymbolId(queryString, symbolId, "contract_code");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENTS: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
req.target(target);
} break;
default:
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_ORDER_PRICE_INCREMENT, UtilString::normalizeDecimalString(x["price_tick"].GetString()));
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, 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 {
switch (request.getOperation()) {
case Request::Operation::GET_INSTRUMENT: {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
for (const auto& x : document["data"].GetArray()) {
if (std::string(x["contract_code"].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: {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
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:
MarketDataServiceHuobiBase::convertTextMessageToMarketDataMessage(request, textMessage, timeReceived, event, marketDataMessageList);
}
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_DERIVATIVES_BASE_H_
@@ -0,0 +1,30 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_USDT_SWAP_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_USDT_SWAP_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP
#include "ccapi_cpp/service/ccapi_market_data_service_huobi_derivatives_base.h"
namespace ccapi {
class MarketDataServiceHuobiUsdtSwap : public MarketDataServiceHuobiDerivativesBase {
public:
MarketDataServiceHuobiUsdtSwap(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
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";
}
virtual ~MarketDataServiceHuobiUsdtSwap() {}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_HUOBI_USDT_SWAP_H_
@@ -0,0 +1,357 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KRAKEN_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KRAKEN_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceKraken : public MarketDataService {
public:
MarketDataServiceKraken(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_KRAKEN;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->shouldAlignSnapshot = true;
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->getRecentTradesTarget = "/0/public/Trades";
this->getInstrumentTarget = "/0/public/AssetPairs";
this->getInstrumentsTarget = "/0/public/AssetPairs";
}
virtual ~MarketDataServiceKraken() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl, "{\"reqid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec);
}
bool doesHttpBodyContainError(const Request& request, 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 {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({10, 25, 100, 500, 1000}));
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
}
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.rfind(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_BOOK, 0) == 0) {
std::map<int, std::vector<std::string> > symbolIdListByMarketDepthSubscribedToExchangeMap;
for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListBySymbolId.first;
int marketDepthSubscribedToExchange =
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
std::string exchangeSubscriptionId =
std::string(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_BOOK) + "-" + std::to_string(marketDepthSubscribedToExchange) + "|" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
symbolIdListByMarketDepthSubscribedToExchangeMap[marketDepthSubscribedToExchange].push_back(symbolId);
}
for (const auto& x : symbolIdListByMarketDepthSubscribedToExchangeMap) {
auto marketDepthSubscribedToExchange = x.first;
auto symbolIdList = x.second;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
rj::Value instrument(rj::kArrayType);
for (const auto& symbolId : symbolIdList) {
instrument.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
document.AddMember("pair", instrument, allocator);
rj::Value subscription(rj::kObjectType);
subscription.AddMember("depth", rj::Value(marketDepthSubscribedToExchange).Move(), allocator);
subscription.AddMember("name", rj::Value(std::string(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_BOOK).c_str(), allocator).Move(), allocator);
document.AddMember("subscription", subscription, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
}
} else if (channelId == CCAPI_WEBSOCKET_KRAKEN_CHANNEL_TRADE) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
rj::Value instrument(rj::kArrayType);
for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListBySymbolId.first;
std::string exchangeSubscriptionId = std::string(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_TRADE) + "|" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
instrument.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
document.AddMember("pair", instrument, allocator);
rj::Value subscription(rj::kObjectType);
subscription.AddMember("name", rj::Value(std::string(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_TRADE).c_str(), allocator).Move(), allocator);
document.AddMember("subscription", subscription, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
}
}
return sendStringList;
}
void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
rj::Document document;
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
if (document.IsArray() && document.Size() >= 4 && document.Size() <= 5) {
auto documentSize = document.Size();
auto channelNameWithSuffix = std::string(document[documentSize - 2].GetString());
if (channelNameWithSuffix.rfind(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_BOOK, 0) == 0) {
auto symbolId = std::string(document[documentSize - 1].GetString());
auto exchangeSubscriptionId = channelNameWithSuffix + "|" + symbolId;
auto channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
const rj::Value& anonymous = document[1];
if (anonymous.IsObject() && (anonymous.HasMember("b") || anonymous.HasMember("a"))) {
rj::Value anonymous2(anonymous, allocator);
if (documentSize == 5) {
rj::Value& source = document[2];
for (rj::Value::MemberIterator itr = source.MemberBegin(); itr != source.MemberEnd(); ++itr) {
anonymous2.AddMember(itr->name, itr->value, allocator);
}
}
TimePoint latestTp(std::chrono::seconds(0));
if (anonymous2.HasMember("b")) {
for (const auto& x : anonymous2["b"].GetArray()) {
auto timePair = UtilTime::divide(std::string(x[2].GetString()));
auto tp = TimePoint(std::chrono::duration<int64_t>(timePair.first));
tp += std::chrono::nanoseconds(timePair.second);
if (tp > latestTp) {
latestTp = tp;
}
}
}
if (anonymous2.HasMember("a")) {
for (const auto& x : anonymous2["a"].GetArray()) {
auto timePair = UtilTime::divide(std::string(x[2].GetString()));
auto tp = TimePoint(std::chrono::duration<int64_t>(timePair.first));
tp += std::chrono::nanoseconds(timePair.second);
if (tp > latestTp) {
latestTp = tp;
}
}
}
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = latestTp;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
if (anonymous2.HasMember("b")) {
for (const auto& x : anonymous2["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));
}
}
if (anonymous2.HasMember("a")) {
for (const auto& x : anonymous2["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 (anonymous.IsObject() && anonymous.HasMember("as") && anonymous.HasMember("bs")) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = timeReceived;
for (const auto& x : anonymous["bs"].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 : anonymous["as"].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 (channelNameWithSuffix == CCAPI_WEBSOCKET_KRAKEN_CHANNEL_TRADE) {
for (const auto& x : document[1].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
auto symbolId = std::string(document[documentSize - 1].GetString());
marketDataMessage.exchangeSubscriptionId = channelNameWithSuffix + "|" + symbolId;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
auto timePair = UtilTime::divide(std::string(x[2].GetString()));
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[0].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x[1].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x[3].GetString()) == "s" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
} else if (document.IsObject() && document.HasMember("event")) {
std::string eventPayload = std::string(document["event"].GetString());
if (eventPayload == "heartbeat") {
} else if (eventPayload == "subscriptionStatus") {
std::string status = document["status"].GetString();
if (status == "subscribed" || status == "error") {
event.setType(Event::Type::SUBSCRIPTION_STATUS);
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
std::vector<std::string> correlationIdList;
std::string exchangeSubscriptionId = document["subscription"]["name"].GetString();
if (exchangeSubscriptionId == CCAPI_WEBSOCKET_KRAKEN_CHANNEL_BOOK) {
exchangeSubscriptionId += "-" + std::string(document["subscription"]["depth"].GetString());
}
std::string symbolId = document["pair"].GetString();
exchangeSubscriptionId += "|" + symbolId;
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
auto channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_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(status == "subscribed" ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(status == "subscribed" ? 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;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendSymbolId(queryString, symbolId, "pair");
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->appendSymbolId(queryString, symbolId, "pair");
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_BASE_ASSET, x["base"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quote"].GetString());
int pairDecimals = std::stoi(x["pair_decimals"].GetString());
if (pairDecimals > 0) {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(pairDecimals - 1, '0') + "1");
} else {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1");
}
int lotDecimals = std::stoi(x["lot_decimals"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "0." + std::string(lotDecimals - 1, '0') + "1");
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["ordermin"].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());
auto instrument = request.getInstrument();
const std::string& symbolId = instrument;
switch (request.getOperation()) {
case Request::Operation::GET_RECENT_TRADES: {
for (const auto& x : document["result"][symbolId.c_str()].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
auto timePair = UtilTime::divide(std::string(x[2].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[0].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x[1].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x[3].GetString()) == "s" ? "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()));
const rj::Value& x = document["result"][request.getInstrument().c_str()];
Element element;
this->extractInstrumentInfo(element, x);
element.insert(CCAPI_INSTRUMENT, request.getInstrument());
message.setElementList({element});
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 (auto itr = document["result"].MemberBegin(); itr != document["result"].MemberEnd(); ++itr) {
Element element;
this->extractInstrumentInfo(element, itr->value);
element.insert(CCAPI_INSTRUMENT, itr->name.GetString());
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_KRAKEN_H_
@@ -0,0 +1,272 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KRAKEN_FUTURES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KRAKEN_FUTURES_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_KRAKEN_FUTURES
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceKrakenFutures : public MarketDataService {
public:
MarketDataServiceKrakenFutures(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_KRAKEN_FUTURES;
this->baseUrl = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v1";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
std::string prefix("/derivatives/api/v3");
this->getRecentTradesTarget = prefix + "/history";
this->getInstrumentTarget = prefix + "/instruments";
this->getInstrumentsTarget = prefix + "/instruments";
}
virtual ~MarketDataServiceKrakenFutures() {}
#ifndef CCAPI_EXPOSE_INTERNAL
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 {
symbolId = UtilString::toUpper(symbolId);
}
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;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
document.AddMember("feed", rj::Value(channelId.c_str(), allocator).Move(), allocator);
rj::Value instrument(rj::kArrayType);
for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = UtilString::toUpper(subscriptionListBySymbolId.first);
instrument.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
std::string exchangeSubscriptionId = std::string(channelId) + "|" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
}
document.AddMember("product_ids", instrument, 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 {
rj::Document document;
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
if (document.HasMember("event")) {
std::string eventPayload = std::string(document["event"].GetString());
if (eventPayload == "heartbeat") {
} else if (eventPayload == "subscriptionStatus") {
std::string status = document["status"].GetString();
if (status == "subscribed" || status == "error") {
event.setType(Event::Type::SUBSCRIPTION_STATUS);
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
std::vector<std::string> correlationIdList;
std::string exchangeSubscriptionId = document["subscription"]["name"].GetString();
if (exchangeSubscriptionId == CCAPI_WEBSOCKET_KRAKEN_FUTURES_CHANNEL_BOOK) {
exchangeSubscriptionId += "-" + std::string(document["subscription"]["depth"].GetString());
}
std::string symbolId = document["pair"].GetString();
exchangeSubscriptionId += "|" + symbolId;
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
auto channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_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(status == "subscribed" ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(status == "subscribed" ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
event.setMessageList(messageList);
}
}
} else {
std::string feed = document["feed"].GetString();
std::string productId = document["product_id"].GetString();
if (feed == "book" || feed == "book_snapshot") {
if (feed == "book") {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.exchangeSubscriptionId = "book|" + productId;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(document["timestamp"].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(document["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(document["qty"].GetString()))});
marketDataMessage.data[std::string(document["side"].GetString()) == "buy" ? MarketDataMessage::DataType::BID : MarketDataMessage::DataType::ASK]
.emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.exchangeSubscriptionId = "book|" + productId;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(document["timestamp"].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
std::map<std::string, MarketDataMessage::DataType> dataTypeMap{
{"bids", MarketDataMessage::DataType::BID},
{"asks", MarketDataMessage::DataType::ASK},
};
for (const auto& kv : dataTypeMap) {
for (const auto& x : document[kv.first.c_str()].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x["price"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x["qty"].GetString())});
marketDataMessage.data[kv.second].emplace_back(std::move(dataPoint));
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (feed == "trade" || feed == "trade_snapshot") {
if (feed == "trade") {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = "trade|" + productId;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(document["time"].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(document["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(document["qty"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(document["side"].GetString()) == "sell" ? "1" : "0"});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, document["uid"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else {
for (const auto& x : document["trades"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = "trade|" + productId;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
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, std::string(x["side"].GetString()) == "sell" ? "1" : "0"});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, x["uid"].GetString()});
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->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
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_UNDERLYING_SYMBOL, x["underlying"].GetString());
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["tickSize"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, 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());
auto instrument = request.getInstrument();
const std::string& symbolId = instrument;
switch (request.getOperation()) {
case Request::Operation::GET_RECENT_TRADES: {
for (const auto& x : document["history"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.tp = UtilTime::parse(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" ? "1" : "0"});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, x["uid"].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()));
std::vector<Element> elementList;
for (const auto& x : document["instruments"].GetArray()) {
if (x["tradeable"].GetBool()) {
if (std::string(x["symbol"].GetString()) == request.getInstrument()) {
Element element;
this->extractInstrumentInfo(element, x);
elementList.push_back(element);
break;
}
}
}
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["instruments"].GetArray()) {
if (x["tradeable"].GetBool()) {
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_KRAKEN_FUTURES_H_
@@ -0,0 +1,50 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KUCOIN_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KUCOIN_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#if defined(CCAPI_ENABLE_EXCHANGE_KUCOIN)
#include "ccapi_cpp/service/ccapi_market_data_service_kucoin_base.h"
namespace ccapi {
class MarketDataServiceKucoin : public MarketDataServiceKucoinBase {
public:
MarketDataServiceKucoin(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataServiceKucoinBase(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 {
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 = "/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->tickerSubject = "trade.ticker";
this->tickerBestBidPriceKey = "bestBid";
this->tickerBestAskPriceKey = "bestAsk";
this->matchSubject = "trade.l3match";
this->recentTradesTimeKey = "time";
}
virtual ~MarketDataServiceKucoin() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
void extractInstrumentInfo(Element& element, const rj::Value& x) override {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCurrency"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCurrency"].GetString());
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());
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KUCOIN_H_
@@ -0,0 +1,373 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KUCOIN_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KUCOIN_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#if defined(CCAPI_ENABLE_EXCHANGE_KUCOIN) || defined(CCAPI_ENABLE_EXCHANGE_KUCOIN_FUTURES)
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceKucoinBase : public MarketDataService {
public:
MarketDataServiceKucoinBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~MarketDataServiceKucoinBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
bool doesHttpBodyContainError(const Request& request, 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 {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
if (field == CCAPI_MARKET_DEPTH) {
if (marketDepthRequested == 1) {
channelId = this->channelMarketTicker;
} else if (marketDepthRequested <= 5) {
channelId = this->channelMarketLevel2Depth5;
} else {
channelId = this->channelMarketLevel2Depth50;
}
}
}
void prepareConnect(WsConnection& wsConnection) override {
http::request<http::string_body> req;
req.set(http::field::host, this->hostRest);
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
req.set(beast::http::field::content_type, "application/json");
req.method(http::verb::post);
req.target("/api/v1/bullet-public");
this->sendRequest(
req,
[wsConnection, that = shared_from_base<MarketDataServiceKucoinBase>()](const beast::error_code& ec) {
WsConnection thisWsConnection = wsConnection;
that->onFail_(thisWsConnection);
},
[wsConnection, that = shared_from_base<MarketDataServiceKucoinBase>()](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);
for (const auto& subscription : thisWsConnection.subscriptionList) {
auto instrument = subscription.getInstrument();
that->subscriptionStatusByInstrumentGroupInstrumentMap[thisWsConnection.group][instrument] = Subscription::Status::SUBSCRIBING;
}
that->extraPropertyByConnectionIdMap[thisWsConnection.id].insert({
{"pingInterval", std::string(instanceServer["pingInterval"].GetString())},
{"pingTimeout", std::string(instanceServer["pingInterval"].GetString())},
});
return;
} catch (const std::runtime_error& e) {
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
}
}
that->onFail_(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 onOpen(wspp::connection_hdl hdl) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
wsConnection.status = WsConnection::Status::OPEN;
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
std::vector<std::string> sendStringList;
std::map<std::string, std::vector<std::string>> symbolListByTopicMap;
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 + ":" + symbolId;
if (channelId == this->channelMarketTicker || channelId == this->channelMarketLevel2Depth5 || channelId == this->channelMarketLevel2Depth50) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
}
symbolListByTopicMap[channelId].push_back(symbolId);
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
}
}
for (const auto& x : symbolListByTopicMap) {
auto topic = x.first;
auto symbolList = x.second;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("type", rj::Value("subscribe").Move(), allocator);
document.AddMember("privateChannel", false, allocator);
document.AddMember("response", true, allocator);
document.AddMember("topic", rj::Value((topic + ":" + UtilString::join(symbolList, ",")).c_str(), allocator).Move(), allocator);
int nextRequestId = this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id];
std::string requestId = std::to_string(nextRequestId);
std::vector<std::string> exchangeSubscriptionIdList;
for (const auto& symbol : symbolList) {
exchangeSubscriptionIdList.push_back(topic + ":" + symbol);
}
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
}
return sendStringList;
}
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()) {
auto it = document.FindMember("type");
if (it != document.MemberEnd()) {
std::string type = it->value.GetString();
if (type == "message") {
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];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
const rj::Value& data = document["data"];
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 = this->isDerivatives ? UtilTime::makeTimePoint(UtilTime::divideNanoWhole(data["ts"].GetString()))
: TimePoint(std::chrono::milliseconds(std::stoll(data["time"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert(
{MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data[this->tickerBestBidPriceKey.c_str()].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["bestBidSize"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert(
{MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data[this->tickerBestAskPriceKey.c_str()].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["bestAskSize"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (std::string(document["subject"].GetString()) == "level2") {
MarketDataMessage marketDataMessage;
std::string exchangeSubscriptionId = document["topic"].GetString();
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
auto optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
const rj::Value& data = document["data"];
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
// kucoin futures documentation is incorrect: https://docs.kucoin.com/futures/#message-channel-for-the-5-best-ask-bid-full-data-of-level-2
// "ts" is actually milliseconds
marketDataMessage.tp = this->isDerivatives ? TimePoint(std::chrono::milliseconds(std::stoll(data["ts"].GetString())))
: TimePoint(std::chrono::milliseconds(std::stoll(data["timestamp"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
const std::map<MarketDataMessage::DataType, const char*> bidAsk{{MarketDataMessage::DataType::BID, "bids"},
{MarketDataMessage::DataType::ASK, "asks"}};
for (const auto& x : bidAsk) {
int index = 0;
for (const auto& y : data[x.second].GetArray()) {
if (index >= maxMarketDepth) {
break;
}
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(y[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(y[1].GetString())});
marketDataMessage.data[x.first].emplace_back(std::move(dataPoint));
++index;
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (std::string(document["subject"].GetString()) == this->matchSubject) {
const rj::Value& data = document["data"];
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
std::string exchangeSubscriptionId = document["topic"].GetString();
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divideNanoWhole(data[this->recentTradesTimeKey.c_str()].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(data["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(data["size"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(data["tradeId"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SEQUENCE_NUMBER, std::string(data["sequence"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(data["side"].GetString()) == "sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (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;
}
MarketDataService::onOpen(hdl);
} else if (type == "pong") {
auto now = UtilTime::now();
this->lastPongTpByMethodByConnectionIdMap[wsConnection.id][PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = now;
} else if (type == "ack") {
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["id"].GetString());
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.find(id) != this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.end()) {
auto exchangeSubscriptionIdList = this->exchangeSubscriptionIdListByExchangeJsonPayloadIdMap.at(id);
for (const auto& exchangeSubscriptionId : exchangeSubscriptionIdList) {
auto splitted = UtilString::split(exchangeSubscriptionId, ":");
auto channelId = splitted.at(0);
auto symbolId = splitted.at(1);
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) {
std::vector<std::string> correlationIdList_2 =
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
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 (type == "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);
}
}
}
}
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->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
req.target(target);
} break;
case Request::Operation::GET_INSTRUMENTS: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
req.target(target);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
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::makeTimePoint(UtilTime::divideNanoWhole(x[this->recentTradesTimeKey.c_str()].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::SEQUENCE_NUMBER, std::string(x["sequence"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["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);
}
}
virtual void extractInstrumentInfo(Element& element, const rj::Value& x) {}
bool isDerivatives{};
std::string channelMarketTicker;
std::string channelMarketLevel2Depth5;
std::string channelMarketLevel2Depth50;
std::string tickerSubject;
std::string tickerBestBidPriceKey;
std::string tickerBestAskPriceKey;
std::string matchSubject;
std::string recentTradesTimeKey;
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KUCOIN_BASE_H_
@@ -0,0 +1,49 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KUCOIN_FUTURES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KUCOIN_FUTURES_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#if defined(CCAPI_ENABLE_EXCHANGE_KUCOIN_FUTURES)
#include "ccapi_cpp/service/ccapi_market_data_service_kucoin_base.h"
namespace ccapi {
class MarketDataServiceKucoinFutures : public MarketDataServiceKucoinBase {
public:
MarketDataServiceKucoinFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->getRecentTradesTarget = "/api/v1/trade/history";
this->getInstrumentTarget = "/api/v1/contracts/active";
this->getInstrumentsTarget = "/api/v1/contracts/active";
this->isDerivatives = true;
this->channelMarketTicker = CCAPI_WEBSOCKET_KUCOIN_FUTURES_CHANNEL_MARKET_TICKER;
this->channelMarketLevel2Depth5 = CCAPI_WEBSOCKET_KUCOIN_FUTURES_CHANNEL_MARKET_LEVEL2DEPTH5;
this->channelMarketLevel2Depth50 = CCAPI_WEBSOCKET_KUCOIN_FUTURES_CHANNEL_MARKET_LEVEL2DEPTH50;
this->tickerSubject = "tickerV2";
this->tickerBestBidPriceKey = "bestBidPrice";
this->tickerBestAskPriceKey = "bestAskPrice";
this->matchSubject = "match";
this->recentTradesTimeKey = "ts";
}
virtual ~MarketDataServiceKucoinFutures() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
void extractInstrumentInfo(Element& element, const rj::Value& x) override {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
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());
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_KUCOIN_FUTURES_H_
@@ -0,0 +1,333 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKEX_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKEX_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_OKEX
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceOkex : public MarketDataService {
public:
MarketDataServiceOkex(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->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
this->getRecentTradesTarget = "/api/v5/market/trades";
this->getInstrumentTarget = "/api/v5/public/instruments";
this->getInstrumentsTarget = "/api/v5/public/instruments";
}
virtual ~MarketDataServiceOkex() {}
#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\"")); }
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 < 100) {
if (marketDepthRequested <= 50) {
channelId = CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH50_L2_TBT;
} else {
channelId = CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400_L2_TBT;
}
} else {
if (marketDepthRequested <= 5) {
channelId = CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH5;
} else {
channelId = CCAPI_WEBSOCKET_OKEX_CHANNEL_PUBLIC_DEPTH400;
}
}
}
}
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_OKEX_CHANNEL_PUBLIC_DEPTH5) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
}
std::string exchangeSubscriptionId = UtilString::split(channelId, "?").at(0) + ":" + symbolId;
rj::Value arg(rj::kObjectType);
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());
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());
}
}
}
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()))));
}
}
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;
} 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;
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_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));
}
}
}
}
}
}
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, "instId");
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, "instType"},
});
this->appendSymbolId(queryString, symbolId, "instId");
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, "instType"},
});
this->appendSymbolId(queryString, symbolId, "instId");
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["instId"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCcy"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCcy"].GetString());
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["tickSz"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSz"].GetString());
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());
}
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["ts"].GetString())));
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));
}
} 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["instId"].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);
}
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_OKEX_H_
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,66 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_
#include "ccapi_cpp/ccapi_logger.h"
#include "websocketpp/client.hpp"
#include "websocketpp/common/connection_hdl.hpp"
#include "websocketpp/config/asio_client.hpp"
#include "websocketpp/config/boost_config.hpp"
namespace wspp = websocketpp;
namespace ccapi {
class ServiceContext CCAPI_FINAL {
public:
typedef wspp::lib::asio::io_service IoContext;
typedef wspp::lib::shared_ptr<wspp::lib::asio::io_service> IoContextPtr;
struct CustomClientConfig : public wspp::config::asio_tls_client {
#ifdef WEBSOCKETPP_ENABLE_SINGLE_THREADING
typedef wspp::config::asio_tls_client base;
static bool const enable_multithreading = false;
struct transport_config : public base::transport_config {
static bool const enable_multithreading = false;
};
#endif
static const wspp::log::level alog_level = wspp::log::alevel::none;
static const wspp::log::level elog_level = wspp::log::elevel::none;
};
typedef wspp::client<CustomClientConfig> TlsClient;
typedef wspp::lib::shared_ptr<wspp::client<CustomClientConfig> > TlsClientPtr;
typedef wspp::lib::error_code ErrorCode;
typedef wspp::lib::asio::ssl::context SslContext;
typedef wspp::lib::shared_ptr<SslContext> SslContextPtr;
ServiceContext() {
this->tlsClientPtr->set_access_channels(websocketpp::log::alevel::none);
this->tlsClientPtr->set_error_channels(websocketpp::log::elevel::none);
ErrorCode ec;
CCAPI_LOGGER_DEBUG("asio initialization start");
this->tlsClientPtr->init_asio(this->ioContextPtr.get(), ec);
if (ec) {
CCAPI_LOGGER_FATAL("asio initialization error: " + ec.message());
}
CCAPI_LOGGER_DEBUG("asio initialization end");
this->sslContextPtr->set_options(SslContext::default_workarounds | SslContext::no_sslv2 | SslContext::no_sslv3 | SslContext::single_dh_use);
this->sslContextPtr->set_verify_mode(wspp::lib::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;
void start() {
CCAPI_LOGGER_INFO("about to start client asio io_service run loop");
this->tlsClientPtr->start_perpetual();
this->tlsClientPtr->run();
CCAPI_LOGGER_INFO("just exited client asio io_service run loop");
}
void stop() {
this->ioContextPtr->stop();
this->tlsClientPtr->stop();
this->tlsClientPtr->stop_perpetual();
}
IoContextPtr ioContextPtr{new IoContext()};
TlsClientPtr tlsClientPtr{new TlsClient()};
SslContextPtr sslContextPtr{new SslContext(SslContext::sslv23)};
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more