Upgrade ccapi to v6.12.0

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

No files matched your search

File diff suppressed because it is too large. Load diff
+1
View File
@@ -2,6 +2,7 @@
#define INCLUDE_CCAPI_CPP_CCAPI_DECIMAL_H_
#include <string>
#include "ccapi_cpp/ccapi_logger.h"
#include "ccapi_cpp/ccapi_util_private.h"
namespace ccapi {
/**
@@ -10,7 +10,7 @@ class Session;
class EventHandler {
public:
virtual ~EventHandler() {}
virtual bool processEvent(const Event& event, Session* session) { return true; }
virtual bool processEvent(const Event& event, Session* sessionPtr) { 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
@@ -6,11 +6,11 @@
#include "ccapi_cpp/ccapi_subscription.h"
namespace beast = boost::beast;
namespace ccapi {
/**
* This class represents a TCP socket connection for the FIX API.
*/
template <class T>
class FixConnection CCAPI_FINAL {
/**
* This class represents a TCP socket connection for the FIX API.
*/
public:
FixConnection(std::string host, std::string port, Subscription subscription, std::shared_ptr<T> streamPtr)
: host(host), port(port), subscription(subscription), streamPtr(streamPtr) {
@@ -15,12 +15,14 @@ class HttpConnection CCAPI_FINAL {
std::string toString() const {
std::ostringstream oss;
oss << streamPtr;
std::string output = "HttpConnection [host = " + host + ", port = " + port + ", streamPtr = " + oss.str() + "]";
std::string output = "HttpConnection [host = " + host + ", port = " + port + ", streamPtr = " + oss.str() +
", lastReceiveDataTp = " + UtilTime::getISOTimestamp(lastReceiveDataTp) + "]";
return output;
}
std::string host;
std::string port;
std::shared_ptr<beast::ssl_stream<beast::tcp_stream> > streamPtr;
TimePoint lastReceiveDataTp{std::chrono::seconds{0}};
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_HTTP_CONNECTION_H_
+6 -9
View File
@@ -68,12 +68,12 @@
#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 <sstream>
#include <string>
#include <thread>
#include "ccapi_cpp/ccapi_date.h"
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_util.h"
#include "ccapi_cpp/ccapi_util_private.h"
namespace ccapi {
/**
* This class is used for library logging.
@@ -112,21 +112,18 @@ class Logger {
this->logMessagePrivate(LOG_SEVERITY_TRACE, threadId, time, fileName, lineNumber, message);
}
static Logger* logger;
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) {}
#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));
this->logMessage(severity, ss.str(), UtilTime::getISOTimestamp(time), fileName, lineNumber, message);
}
};
} /* namespace ccapi */
+94 -38
View File
@@ -27,6 +27,9 @@
#ifndef CCAPI_AGG_TRADE
#define CCAPI_AGG_TRADE "AGG_TRADE"
#endif
#ifndef CCAPI_CANDLESTICK
#define CCAPI_CANDLESTICK "CANDLESTICK"
#endif
#ifndef CCAPI_MARKET_DEPTH_MAX
#define CCAPI_MARKET_DEPTH_MAX CCAPI_MARKET_DEPTH "_MAX"
#endif
@@ -49,6 +52,12 @@
#define CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS "FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS"
#endif
#define CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS_DEFAULT "0"
#ifndef CCAPI_CANDLESTICK_INTERVAL_SECONDS
#define CCAPI_CANDLESTICK_INTERVAL_SECONDS CCAPI_CANDLESTICK "_INTERVAL_SECONDS"
#endif
#ifndef CCAPI_CANDLESTICK_INTERVAL_SECONDS_DEFAULT
#define CCAPI_CANDLESTICK_INTERVAL_SECONDS_DEFAULT "60"
#endif
#ifndef CCAPI_EXCHANGE_NAME_COINBASE
#define CCAPI_EXCHANGE_NAME_COINBASE "coinbase"
#endif
@@ -127,9 +136,6 @@
#ifndef CCAPI_EXCHANGE_NAME_BYBIT
#define CCAPI_EXCHANGE_NAME_BYBIT "bybit"
#endif
#ifndef CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES
#define CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES "bybit-derivatives"
#endif
#ifndef CCAPI_EXCHANGE_NAME_ASCENDEX
#define CCAPI_EXCHANGE_NAME_ASCENDEX "ascendex"
#endif
@@ -196,24 +202,48 @@
#ifndef CCAPI_BEST_ASK_N_SIZE_EMPTY
#define CCAPI_BEST_ASK_N_SIZE_EMPTY ""
#endif
#ifndef CCAPI_OHLC_EMPTY
#define CCAPI_OHLC_EMPTY ""
#ifndef CCAPI_CANDLESTICK_EMPTY
#define CCAPI_CANDLESTICK_EMPTY ""
#endif
#ifndef CCAPI_OPEN
#define CCAPI_OPEN "OPEN"
#ifndef CCAPI_OPEN_PRICE
#define CCAPI_OPEN_PRICE "OPEN_PRICE"
#endif
#ifndef CCAPI_HIGH
#define CCAPI_HIGH "HIGH"
#ifndef CCAPI_HIGH_PRICE
#define CCAPI_HIGH_PRICE "HIGH_PRICE"
#endif
#ifndef CCAPI_LOW
#define CCAPI_LOW "LOW"
#ifndef CCAPI_LOW_PRICE
#define CCAPI_LOW_PRICE "LOW_PRICE"
#endif
#ifndef CCAPI_CLOSE
#define CCAPI_CLOSE "CLOSE"
#ifndef CCAPI_CLOSE_PRICE
#define CCAPI_CLOSE_PRICE "CLOSE_PRICE"
#endif
#ifndef CCAPI_VOLUME
#define CCAPI_VOLUME "VOLUME"
#endif
#ifndef CCAPI_QUOTE_VOLUME
#define CCAPI_QUOTE_VOLUME "QUOTE_VOLUME"
#endif
#ifndef CCAPI_LIMIT
#define CCAPI_LIMIT "LIMIT"
#endif
#ifndef CCAPI_START_TRADE_ID
#define CCAPI_START_TRADE_ID "START_TRADE_ID"
#endif
#ifndef CCAPI_END_TRADE_ID
#define CCAPI_END_TRADE_ID "END_TRADE_ID"
#endif
#ifndef CCAPI_START_AGG_TRADE_ID
#define CCAPI_START_AGG_TRADE_ID "START_AGG_TRADE_ID"
#endif
#ifndef CCAPI_START_TIME_SECONDS
#define CCAPI_START_TIME_SECONDS "START_TIME_SECONDS"
#endif
#ifndef CCAPI_END_TIME_SECONDS
#define CCAPI_END_TIME_SECONDS "END_TIME_SECONDS"
#endif
#ifndef CCAPI_LAST_UPDATED_TIME_SECONDS
#define CCAPI_LAST_UPDATED_TIME_SECONDS "LAST_UPDATED_TIME_SECONDS"
#endif
#ifndef CCAPI_BASE_ASSET
#define CCAPI_BASE_ASSET "BASE_ASSET"
#endif
@@ -235,9 +265,15 @@
#ifndef CCAPI_ORDER_QUANTITY_MIN
#define CCAPI_ORDER_QUANTITY_MIN "QUANTITY_MIN"
#endif
#ifndef CCAPI_ORDER_QUANTITY_MAX
#define CCAPI_ORDER_QUANTITY_MAX "QUANTITY_MAX"
#endif
#ifndef CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN
#define CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN "PRICE_TIMES_QUANTITY_MIN"
#endif
#ifndef CCAPI_INSTRUMENT_STATUS
#define CCAPI_INSTRUMENT_STATUS "INSTRUMENT_STATUS"
#endif
#ifndef CCAPI_CONTRACT_SIZE
#define CCAPI_CONTRACT_SIZE "CONTRACT_SIZE"
#endif
@@ -252,12 +288,14 @@
#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_CHANNEL_OHLC "ohlc"
#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_BITFINEX_CHANNEL_BOOKS "book"
#define CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES "candles"
#define CCAPI_WEBSOCKET_BITMEX_CHANNEL_TRADE "trade"
#define CCAPI_WEBSOCKET_BITMEX_CHANNEL_QUOTE "quote"
#define CCAPI_WEBSOCKET_BITMEX_CHANNEL_ORDER_BOOK_10 "orderBook10"
@@ -267,6 +305,7 @@
#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_BINANCE_BASE_CHANNEL_KLINE "kline"
#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"
@@ -281,6 +320,7 @@
#define CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH5 "books5"
#define CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400 "books"
#define CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT "bbo-tbt"
#define CCAPI_WEBSOCKET_OKX_CHANNEL_CANDLESTICK "candle"
#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"
@@ -288,6 +328,7 @@
#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_CHANNEL_MARKET_KLINES "/market/candles"
#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"
@@ -303,25 +344,27 @@
#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_CHANNEL_CANDLESTICKS "spot.candlesticks"
#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_GATEIO_PERPETUAL_FUTURES_CHANNEL_CANDLESTICKS "futures.candlesticks"
#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.{symbol}"
#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER "bookticker.{symbol}"
#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH "orderbook.40.{symbol}"
#define CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE "publicTrade.{symbol}"
#define CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK "orderbook.{depth}.{symbol}"
#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_TRADE "publicTrade.{symbol}"
#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_ORDERBOOK "orderbook.{depth}.{symbol}"
#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_KLINE "kline.{interval}.{symbol}"
#define CCAPI_WEBSOCKET_BYBIT_CHANNEL_KLINE_2 "kline"
#define CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_TRADES "trades"
#define CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_BBO "bbo"
#define CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_DEPTH "depth"
#define CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_BAR "bar"
#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_TRADES "trade"
#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS "books"
#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1 "books1"
#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5 "books5"
#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15 "books15"
#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_TRADES "trade"
#define CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_KLINE "candle"
#define CCAPI_WEBSOCKET_BITMART_CHANNEL_TRADE "spot/trade"
#define CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH5 "spot/depth5"
#define CCAPI_WEBSOCKET_BITMART_CHANNEL_PUBLIC_DEPTH20 "spot/depth20"
@@ -365,8 +408,18 @@
#ifndef CCAPI_UNKNOWN
#define CCAPI_UNKNOWN "unknown"
#endif
#ifndef CCAPI_EM_ORDER_UPDATE
#define CCAPI_EM_ORDER_UPDATE "ORDER_UPDATE"
#endif
#ifndef CCAPI_EM_PRIVATE_TRADE
#define CCAPI_EM_PRIVATE_TRADE "PRIVATE_TRADE"
#endif
#ifndef CCAPI_EM_BALANCE_UPDATE
#define CCAPI_EM_BALANCE_UPDATE "BALANCE_UPDATE"
#endif
#ifndef CCAPI_EM_POSITION_UPDATE
#define CCAPI_EM_POSITION_UPDATE "POSITION_UPDATE"
#endif
#ifndef CCAPI_EM_ORDER_SIDE
#define CCAPI_EM_ORDER_SIDE "SIDE"
#endif
@@ -394,6 +447,9 @@
#ifndef CCAPI_EM_ORDER_FEE_QUANTITY
#define CCAPI_EM_ORDER_FEE_QUANTITY "FEE_QUANTITY"
#endif
#ifndef CCAPI_EM_ORDER_CUMULATIVE_FEE_QUANTITY
#define CCAPI_EM_ORDER_CUMULATIVE_FEE_QUANTITY "CUMULATIVE_FEE_QUANTITY"
#endif
#ifndef CCAPI_EM_ORDER_FEE_ASSET
#define CCAPI_EM_ORDER_FEE_ASSET "FEE_ASSET"
#endif
@@ -487,6 +543,9 @@
#ifndef CCAPI_INSTRUMENT
#define CCAPI_INSTRUMENT "INSTRUMENT"
#endif
#ifndef CCAPI_MARGIN_MODE
#define CCAPI_MARGIN_MODE "MARGIN_MODE"
#endif
#ifndef CCAPI_EM_ORDER_STATUS
#define CCAPI_EM_ORDER_STATUS "STATUS"
#endif
@@ -496,6 +555,9 @@
#ifndef CCAPI_EM_POSITION_LEVERAGE
#define CCAPI_EM_POSITION_LEVERAGE "LEVERAGE"
#endif
#ifndef CCAPI_EM_UNREALIZED_PNL
#define CCAPI_EM_UNREALIZED_PNL "UNREALIZED_PNL"
#endif
#ifndef CCAPI_HTTP_STATUS_CODE
#define CCAPI_HTTP_STATUS_CODE "HTTP_STATUS_CODE"
#endif
@@ -700,9 +762,6 @@
#ifndef CCAPI_BYBIT_URL_REST_BASE
#define CCAPI_BYBIT_URL_REST_BASE "https://api.bybit.com"
#endif
#ifndef CCAPI_BYBIT_DERIVATIVES_URL_REST_BASE
#define CCAPI_BYBIT_DERIVATIVES_URL_REST_BASE "https://api.bybit.com"
#endif
#ifndef CCAPI_ASCENDEX_URL_REST_BASE
#define CCAPI_ASCENDEX_URL_REST_BASE "https://ascendex.com"
#endif
@@ -802,6 +861,9 @@
#ifndef CCAPI_OKX_PRIVATE_WS_PATH
#define CCAPI_OKX_PRIVATE_WS_PATH "/ws/v5/private"
#endif
#ifndef CCAPI_OKX_BUSINESS_WS_PATH
#define CCAPI_OKX_BUSINESS_WS_PATH "/ws/v5/business"
#endif
#ifndef CCAPI_ERISX_URL_WS_BASE
#define CCAPI_ERISX_URL_WS_BASE "wss://publicmd-api.erisx.com"
#endif
@@ -826,9 +888,6 @@
#ifndef CCAPI_BYBIT_URL_WS_BASE
#define CCAPI_BYBIT_URL_WS_BASE "wss://stream.bybit.com"
#endif
#ifndef CCAPI_BYBIT_DERIVATIVES_URL_WS_BASE
#define CCAPI_BYBIT_DERIVATIVES_URL_WS_BASE "wss://stream.bybit.com"
#endif
#ifndef CCAPI_ASCENDEX_URL_WS_BASE
#define CCAPI_ASCENDEX_URL_WS_BASE "wss://ascendex.com"
#endif
@@ -937,12 +996,6 @@
#ifndef CCAPI_BINANCE_API_SECRET
#define CCAPI_BINANCE_API_SECRET "BINANCE_API_SECRET"
#endif
// #ifndef CCAPI_BINANCE_MARGIN_API_KEY
// #define CCAPI_BINANCE_MARGIN_API_KEY "BINANCE_MARGIN_API_KEY"
// #endif
// #ifndef CCAPI_BINANCE_MARGIN_API_SECRET
// #define CCAPI_BINANCE_MARGIN_API_SECRET "BINANCE_MARGIN_API_SECRET"
// #endif
#ifndef CCAPI_BINANCE_USDS_FUTURES_API_KEY
#define CCAPI_BINANCE_USDS_FUTURES_API_KEY "BINANCE_USDS_FUTURES_API_KEY"
#endif
@@ -1060,12 +1113,6 @@
#ifndef CCAPI_BYBIT_API_SECRET
#define CCAPI_BYBIT_API_SECRET "BYBIT_API_SECRET"
#endif
#ifndef CCAPI_BYBIT_DERIVATIVES_API_KEY
#define CCAPI_BYBIT_DERIVATIVES_API_KEY "BYBIT_DERIVATIVES_API_KEY"
#endif
#ifndef CCAPI_BYBIT_DERIVATIVES_API_SECRET
#define CCAPI_BYBIT_DERIVATIVES_API_SECRET "BYBIT_DERIVATIVES_API_SECRET"
#endif
#ifndef CCAPI_ASCENDEX_API_KEY
#define CCAPI_ASCENDEX_API_KEY "ASCENDEX_API_KEY"
#endif
@@ -1168,4 +1215,13 @@
#ifndef CCAPI_BYBIT_API_BROKER_ID
#define CCAPI_BYBIT_API_BROKER_ID "Vs000261"
#endif
#ifndef CCAPI_BINANCE_API_LINK_ID
#define CCAPI_BINANCE_API_LINK_ID "XHKUG2CH"
#endif
#ifndef CCAPI_BINANCE_USDS_FUTURES_API_LINK_ID
#define CCAPI_BINANCE_USDS_FUTURES_API_LINK_ID "QzcVS63u"
#endif
#ifndef CCAPI_BITMART_BROKER_ID
#define CCAPI_BITMART_BROKER_ID "cryptochassis01"
#endif
#endif // INCLUDE_CCAPI_CPP_CCAPI_MACRO_H_
@@ -16,6 +16,7 @@ class MarketDataMessage CCAPI_FINAL {
MARKET_DATA_EVENTS_MARKET_DEPTH,
MARKET_DATA_EVENTS_TRADE,
MARKET_DATA_EVENTS_AGG_TRADE,
MARKET_DATA_EVENTS_CANDLESTICK,
};
enum class RecapType {
UNKNOWN,
@@ -44,6 +45,7 @@ class MarketDataMessage CCAPI_FINAL {
ASK = 1,
TRADE = 2,
AGG_TRADE = 3,
CANDLESTICK = 4,
};
static std::string dataTypeToString(DataType dataType) {
std::string output;
@@ -60,6 +62,9 @@ class MarketDataMessage CCAPI_FINAL {
case DataType::AGG_TRADE:
output = "AGG_TRADE";
break;
case DataType::CANDLESTICK:
output = "CANDLESTICK";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
@@ -72,6 +77,12 @@ class MarketDataMessage CCAPI_FINAL {
AGG_TRADE_ID = 3,
IS_BUYER_MAKER = 4,
SEQUENCE_NUMBER = 5,
OPEN_PRICE = 6,
HIGH_PRICE = 7,
LOW_PRICE = 8,
CLOSE_PRICE = 9,
VOLUME = 10,
QUOTE_VOLUME = 11,
};
static std::string dataFieldTypeToString(DataFieldType dataFieldType) {
std::string output;
@@ -94,6 +105,24 @@ class MarketDataMessage CCAPI_FINAL {
case DataFieldType::SEQUENCE_NUMBER:
output = "SEQUENCE_NUMBER";
break;
case DataFieldType::OPEN_PRICE:
output = "OPEN_PRICE";
break;
case DataFieldType::HIGH_PRICE:
output = "HIGH_PRICE";
break;
case DataFieldType::LOW_PRICE:
output = "LOW_PRICE";
break;
case DataFieldType::CLOSE_PRICE:
output = "CLOSE_PRICE";
break;
case DataFieldType::VOLUME:
output = "VOLUME";
break;
case DataFieldType::QUOTE_VOLUME:
output = "QUOTE_VOLUME";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
@@ -156,6 +185,9 @@ class MarketDataMessage CCAPI_FINAL {
case Type::MARKET_DATA_EVENTS_AGG_TRADE:
output = "MARKET_DATA_EVENTS_AGG_TRADE";
break;
case Type::MARKET_DATA_EVENTS_CANDLESTICK:
output = "MARKET_DATA_EVENTS_CANDLESTICK";
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
+32
View File
@@ -45,8 +45,11 @@ class Message CCAPI_FINAL {
MARKET_DATA_EVENTS_MARKET_DEPTH,
MARKET_DATA_EVENTS_TRADE,
MARKET_DATA_EVENTS_AGG_TRADE,
MARKET_DATA_EVENTS_CANDLESTICK,
EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE,
EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE,
EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE,
EXECUTION_MANAGEMENT_EVENTS_POSITION_UPDATE,
SUBSCRIPTION_STARTED,
SUBSCRIPTION_FAILURE,
SESSION_CONNECTION_UP,
@@ -61,7 +64,12 @@ class Message CCAPI_FINAL {
GET_ACCOUNT_BALANCES,
GET_ACCOUNT_POSITIONS,
GET_RECENT_TRADES,
GET_HISTORICAL_TRADES,
GET_RECENT_AGG_TRADES,
GET_HISTORICAL_AGG_TRADES,
GET_RECENT_CANDLESTICKS,
GET_HISTORICAL_CANDLESTICKS,
GET_MARKET_DEPTH,
GET_INSTRUMENT,
GET_INSTRUMENTS,
RESPONSE_ERROR,
@@ -89,6 +97,9 @@ class Message CCAPI_FINAL {
case Type::MARKET_DATA_EVENTS_AGG_TRADE:
output = "MARKET_DATA_EVENTS_AGG_TRADE";
break;
case Type::MARKET_DATA_EVENTS_CANDLESTICK:
output = "MARKET_DATA_EVENTS_CANDLESTICK";
break;
case Type::AUTHORIZATION_SUCCESS:
output = "AUTHORIZATION_SUCCESS";
break;
@@ -101,6 +112,12 @@ class Message CCAPI_FINAL {
case Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE:
output = "EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE";
break;
case Type::EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE:
output = "EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE";
break;
case Type::EXECUTION_MANAGEMENT_EVENTS_POSITION_UPDATE:
output = "EXECUTION_MANAGEMENT_EVENTS_POSITION_UPDATE";
break;
case Type::SUBSCRIPTION_STARTED:
output = "SUBSCRIPTION_STARTED";
break;
@@ -143,9 +160,24 @@ class Message CCAPI_FINAL {
case Type::GET_RECENT_TRADES:
output = "GET_RECENT_TRADES";
break;
case Type::GET_HISTORICAL_TRADES:
output = "GET_HISTORICAL_TRADES";
break;
case Type::GET_RECENT_AGG_TRADES:
output = "GET_RECENT_AGG_TRADES";
break;
case Type::GET_HISTORICAL_AGG_TRADES:
output = "GET_HISTORICAL_AGG_TRADES";
break;
case Type::GET_RECENT_CANDLESTICKS:
output = "GET_RECENT_CANDLESTICKS";
break;
case Type::GET_HISTORICAL_CANDLESTICKS:
output = "GET_HISTORICAL_CANDLESTICKS";
break;
case Type::GET_MARKET_DEPTH:
output = "GET_MARKET_DEPTH";
break;
case Type::GET_INSTRUMENT:
output = "GET_INSTRUMENT";
break;
+12 -1
View File
@@ -6,15 +6,26 @@
#include "ccapi_cpp/ccapi_logger.h"
namespace ccapi {
template <class T>
/**
* This class represents a generic FIFO queue.
*/
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(const T& t) {
#ifndef CCAPI_USE_SINGLE_THREAD
std::lock_guard<std::mutex> lock(this->m);
#endif
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);
}
}
void pushBack(T&& t) {
#ifndef CCAPI_USE_SINGLE_THREAD
std::lock_guard<std::mutex> lock(this->m);
+68 -17
View File
@@ -7,6 +7,15 @@
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_util_private.h"
// We use macros instead of static constants in the Request class so that SWIG can properly generate C# bindings
#define CCAPI_REQUEST_OPERATION_TYPE_CUSTOM 0x100
#define CCAPI_REQUEST_OPERATION_TYPE_GENERIC_PUBLIC_REQUEST 0x200
#define CCAPI_REQUEST_OPERATION_TYPE_GENERIC_PRIVATE_REQUEST 0x300
#define CCAPI_REQUEST_OPERATION_TYPE_FIX 0x400
#define CCAPI_REQUEST_OPERATION_TYPE_MARKET_DATA 0x500
#define CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT 0x600
#define CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ORDER CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT
#define CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ACCOUNT 0x700
namespace ccapi {
/**
* A single request. Request objects are created using Request constructors. They are used with Session::sendRequest() or Session::sendRequestByWebsocket() or
@@ -16,29 +25,26 @@ 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,
CUSTOM = CCAPI_REQUEST_OPERATION_TYPE_CUSTOM,
GENERIC_PUBLIC_REQUEST = CCAPI_REQUEST_OPERATION_TYPE_GENERIC_PUBLIC_REQUEST,
GENERIC_PRIVATE_REQUEST = CCAPI_REQUEST_OPERATION_TYPE_GENERIC_PRIVATE_REQUEST,
FIX = CCAPI_REQUEST_OPERATION_TYPE_FIX,
GET_RECENT_TRADES = CCAPI_REQUEST_OPERATION_TYPE_MARKET_DATA,
GET_HISTORICAL_TRADES,
GET_RECENT_AGG_TRADES,
GET_HISTORICAL_AGG_TRADES,
GET_RECENT_CANDLESTICKS,
GET_HISTORICAL_CANDLESTICKS,
GET_MARKET_DEPTH,
GET_INSTRUMENT,
GET_INSTRUMENTS,
CREATE_ORDER = operationTypeExecutionManagementOrder,
CREATE_ORDER = CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ORDER,
CANCEL_ORDER,
GET_ORDER,
GET_OPEN_ORDERS,
CANCEL_OPEN_ORDERS,
GET_ACCOUNTS = operationTypeExecutionManagementAccount,
GET_ACCOUNTS = CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ACCOUNT,
GET_ACCOUNT_BALANCES,
GET_ACCOUNT_POSITIONS,
};
@@ -60,9 +66,24 @@ class Request CCAPI_FINAL {
case Operation::GET_RECENT_TRADES:
output = "GET_RECENT_TRADES";
break;
case Operation::GET_HISTORICAL_TRADES:
output = "GET_HISTORICAL_TRADES";
break;
case Operation::GET_RECENT_AGG_TRADES:
output = "GET_RECENT_AGG_TRADES";
break;
case Operation::GET_HISTORICAL_AGG_TRADES:
output = "GET_HISTORICAL_AGG_TRADES";
break;
case Operation::GET_RECENT_CANDLESTICKS:
output = "GET_RECENT_CANDLESTICKS";
break;
case Operation::GET_HISTORICAL_CANDLESTICKS:
output = "GET_HISTORICAL_CANDLESTICKS";
break;
case Operation::GET_MARKET_DEPTH:
output = "GET_MARKET_DEPTH";
break;
case Operation::GET_INSTRUMENT:
output = "GET_INSTRUMENT";
break;
@@ -111,7 +132,7 @@ class Request CCAPI_FINAL {
} else if (operation == Operation::FIX) {
this->serviceName = CCAPI_FIX;
} else {
this->serviceName = static_cast<int>(operation) >= operationTypeExecutionManagement ? CCAPI_EXECUTION_MANAGEMENT : CCAPI_MARKET_DATA;
this->serviceName = static_cast<int>(operation) >= CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT ? CCAPI_EXECUTION_MANAGEMENT : CCAPI_MARKET_DATA;
}
if (this->correlationId.empty()) {
this->correlationId = UtilString::generateRandomString(CCAPI_CORRELATION_ID_GENERATED_LENGTH);
@@ -127,7 +148,8 @@ class Request CCAPI_FINAL {
", correlationId = " + correlationId + ", secondaryCorrelationId = " + secondaryCorrelationId +
(this->serviceName == CCAPI_FIX ? ", paramListFix = " + ccapi::toString(paramListFix) : ", paramList = " + ccapi::toString(paramList)) +
", credential = " + ccapi::toString(shortCredential) + ", operation = " + operationToString(operation) +
", timeSent = " + UtilTime::getISOTimestamp(timeSent) + "]";
", timeSent = " + UtilTime::getISOTimestamp(timeSent) + ", index = " + ccapi::toString(index) + ", localIpAddress = " + localIpAddress +
", baseUrl = " + baseUrl + "]";
return output;
}
const std::string& getCorrelationId() const { return correlationId; }
@@ -160,11 +182,36 @@ class Request CCAPI_FINAL {
std::pair<long long, long long> getTimeSentPair() const { return UtilTime::divide(timeSent); }
void setTimeSent(TimePoint timeSent) { this->timeSent = timeSent; }
int getIndex() const { return index; }
const std::string& getLocalIpAddress() const { return localIpAddress; }
const std::string& getBaseUrl() const { return baseUrl; }
const std::string& getHost() const { return host; }
const std::string& getPort() const { return port; }
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; }
void setSecondaryCorrelationId(const std::string& secondaryCorrelationId) { this->secondaryCorrelationId = secondaryCorrelationId; }
void setMarginType(const std::string& marginType) { this->marginType = marginType; }
void setLocalIpAddress(const std::string& localIpAddress) { this->localIpAddress = localIpAddress; }
void setBaseUrl(const std::string& baseUrl) {
this->baseUrl = baseUrl;
this->setBaseUrlParts();
}
void setBaseUrlParts() {
auto splitted1 = UtilString::split(this->baseUrl, "://");
if (splitted1.size() >= 2) {
auto splitted2 = UtilString::split(UtilString::split(splitted1.at(1), "/").at(0), ":");
this->host = splitted2.at(0);
if (splitted2.size() == 2) {
this->port = splitted2.at(1);
} else {
if (splitted1.at(0) == "https" || splitted1.at(0) == "wss") {
this->port = CCAPI_HTTPS_PORT_DEFAULT;
} else {
this->port = CCAPI_HTTP_PORT_DEFAULT;
}
}
}
}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
@@ -181,6 +228,10 @@ class Request CCAPI_FINAL {
std::vector<std::vector<std::pair<int, std::string> > > paramListFix;
TimePoint timeSent{std::chrono::seconds{0}};
int index{};
std::string localIpAddress;
std::string baseUrl;
std::string host;
std::string port;
};
} /* namespace ccapi */
#endif // INCLUDE_CCAPI_CPP_CCAPI_REQUEST_H_
+93 -63
View File
@@ -79,9 +79,6 @@
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
#include "ccapi_cpp/service/ccapi_market_data_service_bybit.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES
#include "ccapi_cpp/service/ccapi_market_data_service_bybit_derivatives.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX
#include "ccapi_cpp/service/ccapi_market_data_service_ascendex.h"
#endif
@@ -186,9 +183,6 @@
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
#include "ccapi_cpp/service/ccapi_execution_management_service_bybit.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES
#include "ccapi_cpp/service/ccapi_execution_management_service_bybit_derivatives.h"
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX
#include "ccapi_cpp/service/ccapi_execution_management_service_ascendex.h"
#endif
@@ -227,9 +221,9 @@
#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
// #ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT
// #include "ccapi_cpp/service/ccapi_fix_service_deribit.h"
// #endif
#endif
// end: enable exchanges for FIX
@@ -259,15 +253,27 @@ class Session {
Session(const Session&) = delete;
Session& operator=(const Session&) = delete;
Session(const SessionOptions& sessionOptions = SessionOptions(), const SessionConfigs& sessionConfigs = SessionConfigs(),
EventHandler* eventHandler = nullptr, EventDispatcher* eventDispatcher = nullptr)
EventHandler* eventHandler = nullptr, EventDispatcher* eventDispatcher = nullptr
#ifndef SWIG
,
ServiceContext* serviceContextPtr = nullptr
#endif
)
: sessionOptions(sessionOptions),
sessionConfigs(sessionConfigs),
eventHandler(eventHandler),
#ifndef CCAPI_USE_SINGLE_THREAD
eventDispatcher(eventDispatcher),
#endif
eventQueue(sessionOptions.maxEventQueueSize),
serviceContextPtr(new ServiceContext()) {
eventQueue(sessionOptions.maxEventQueueSize)
#ifndef SWIG
,
serviceContextPtr(serviceContextPtr)
#endif
{
if (!this->serviceContextPtr) {
this->serviceContextPtr = new ServiceContext();
}
CCAPI_LOGGER_FUNCTION_ENTER;
#ifndef CCAPI_USE_SINGLE_THREAD
if (this->eventHandler) {
@@ -291,6 +297,7 @@ class Session {
delete this->eventDispatcher;
}
#endif
delete this->serviceContextPtr;
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void start() {
@@ -399,10 +406,6 @@ class Session {
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BYBIT] =
std::make_shared<MarketDataServiceBybit>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES
this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES] =
std::make_shared<MarketDataServiceBybitDerivatives>(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);
@@ -537,10 +540,6 @@ class Session {
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BYBIT] =
std::make_shared<ExecutionManagementServiceBybit>(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr);
#endif
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES
this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES] =
std::make_shared<ExecutionManagementServiceBybitDerivatives>(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);
@@ -576,10 +575,10 @@ class Session {
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_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);
@@ -588,10 +587,10 @@ class Session {
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
// #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;
@@ -623,6 +622,34 @@ class Session {
}
virtual void subscribe(std::vector<Subscription>& subscriptionList) {
CCAPI_LOGGER_FUNCTION_ENTER;
for (auto& subscription : subscriptionList) {
auto exchange = subscription.getExchange();
if (exchange == CCAPI_EXCHANGE_NAME_BYBIT) {
auto instrumentType = subscription.getInstrumentType();
if (instrumentType.empty()) {
instrumentType = "spot";
}
std::vector<std::string> instrumentTypeList = {"spot", "linear", "inverse", "option"};
if (std::find(instrumentTypeList.begin(), instrumentTypeList.end(), instrumentType) == instrumentTypeList.end()) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE,
"unsupported exchange instrument types: " + toString(instrumentType) + ". Allowed values: " + toString(instrumentTypeList) + ".");
return;
}
subscription.setInstrumentType(instrumentType);
} else if (exchange == CCAPI_EXCHANGE_NAME_BITGET_FUTURES) {
auto instrumentType = subscription.getInstrumentType();
if (instrumentType.empty()) {
instrumentType = "USDT-FUTURES";
}
std::vector<std::string> instrumentTypeList = {"USDT-FUTURES", "COIN-FUTURES", "USDC-FUTURES"};
if (std::find(instrumentTypeList.begin(), instrumentTypeList.end(), instrumentType) == instrumentTypeList.end()) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE,
"unsupported exchange instrument types: " + toString(instrumentType) + ". Allowed values: " + toString(instrumentTypeList) + ".");
return;
}
subscription.setInstrumentType(instrumentType);
}
}
std::map<std::string, std::vector<Subscription> > subscriptionListByServiceNameMap;
for (const auto& subscription : subscriptionList) {
auto serviceName = subscription.getServiceName();
@@ -637,19 +664,10 @@ class Session {
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();
@@ -661,29 +679,16 @@ class Session {
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;
}
std::map<std::string, std::vector<Subscription> > subscriptionListByExchangeMap;
for (const auto& subscription : subscriptionList) {
auto exchange = subscription.getExchange();
if (exchange == CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES) {
const auto& instrumentType = subscription.getInstrumentType();
std::vector<std::string> instrumentTypeList = {"usdt-contract", "usdc-contract", "usdc-options"};
if (std::find(instrumentTypeList.begin(), instrumentTypeList.end(), instrumentType) == instrumentTypeList.end()) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE,
"unsupported exchange instrument types: " + toString(instrumentType) + ". Allowed values: " + toString(instrumentTypeList) + ".");
return;
}
}
subscriptionListByExchangeMap[exchange].push_back(subscription);
}
CCAPI_LOGGER_TRACE("subscriptionListByExchangeMap = " + toString(subscriptionListByExchangeMap));
for (auto& subscriptionListByExchange : subscriptionListByExchangeMap) {
@@ -821,13 +826,13 @@ class Session {
this->sendRequestByWebsocket(x);
}
}
virtual void sendRequest(Request& request, Queue<Event>* eventQueuePtr = nullptr, long delayMilliSeconds = 0) {
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);
this->sendRequest(requestList, eventQueuePtr, delayMilliseconds);
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void sendRequest(std::vector<Request>& requestList, Queue<Event>* eventQueuePtr = nullptr, long delayMilliSeconds = 0) {
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;
@@ -854,7 +859,7 @@ class Session {
// serviceNameExchangeSet.insert(key);
// }
auto now = UtilTime::now();
auto futurePtr = servicePtr->sendRequest(request, !!eventQueuePtr, now, delayMilliSeconds, eventQueuePtr);
auto futurePtr = servicePtr->sendRequest(request, !!eventQueuePtr, now, delayMilliseconds, eventQueuePtr);
if (eventQueuePtr) {
futurePtrList.push_back(futurePtr);
}
@@ -886,10 +891,24 @@ class Session {
this->onEvent(event, eventQueuePtr);
}
#ifndef SWIG
virtual void setTimer(const std::string& id, long delayMilliSeconds, std::function<void(const boost::system::error_code&)> errorHandler,
virtual void setImmediate(std::function<void()> successHandler) {
boost::asio::post(*this->serviceContextPtr->ioContextPtr, [this, successHandler]() {
if (this->eventHandler) {
#ifdef CCAPI_USE_SINGLE_THREAD
successHandler();
#else
this->eventDispatcher->dispatch([successHandler] {
successHandler();
});
#endif
}
});
}
virtual void setTimer(const std::string& id, long delayMilliseconds, std::function<void(const boost::system::error_code&)> errorHandler,
std::function<void()> successHandler) {
boost::asio::post(*this->serviceContextPtr->ioContextPtr, [this, id, delayMilliSeconds, errorHandler, successHandler]() {
std::shared_ptr<steady_timer> timerPtr(new steady_timer(*this->serviceContextPtr->ioContextPtr, boost::asio::chrono::milliseconds(delayMilliSeconds)));
boost::asio::post(*this->serviceContextPtr->ioContextPtr, [this, id, delayMilliseconds, errorHandler, successHandler]() {
std::shared_ptr<boost::asio::steady_timer> timerPtr(
new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, boost::asio::chrono::milliseconds(delayMilliseconds)));
timerPtr->async_wait([this, id, errorHandler, successHandler](const boost::system::error_code& ec) {
if (this->eventHandler) {
#ifdef CCAPI_USE_SINGLE_THREAD
@@ -932,19 +951,30 @@ class Session {
}
}
}
void forceCloseWebsocketConnections(const std::string& serviceName = "", const std::string& exchangeName = "") {
for (const auto& x : this->serviceByServiceNameExchangeMap) {
if (serviceName.empty() || serviceName == x.first) {
for (const auto& y : x.second) {
if (exchangeName.empty() || exchangeName == y.first) {
y.second->forceCloseWebsocketConnections();
}
}
}
}
}
#endif
#ifndef CCAPI_EXPOSE_INTERNAL
private:
protected:
#endif
SessionOptions sessionOptions;
SessionConfigs sessionConfigs;
EventHandler* eventHandler;
EventHandler* eventHandler{nullptr};
#ifndef CCAPI_USE_SINGLE_THREAD
EventDispatcher* eventDispatcher;
EventDispatcher* eventDispatcher{nullptr};
bool useInternalEventDispatcher{};
#endif
std::shared_ptr<ServiceContext> serviceContextPtr;
ServiceContext* serviceContextPtr{nullptr};
std::map<std::string, std::map<std::string, std::shared_ptr<Service> > > serviceByServiceNameExchangeMap;
std::thread t;
Queue<Event> eventQueue;
+16 -14
View File
@@ -47,6 +47,7 @@ class SessionConfigs CCAPI_FINAL {
std::map<std::string, std::string> fieldWebsocketChannelMapKraken = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_KRAKEN_CHANNEL_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_KRAKEN_CHANNEL_BOOK},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC},
};
std::map<std::string, std::string> fieldWebsocketChannelMapKrakenFutures = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_KRAKEN_FUTURES_CHANNEL_TRADE},
@@ -58,7 +59,8 @@ class SessionConfigs CCAPI_FINAL {
};
std::map<std::string, std::string> fieldWebsocketChannelMapBitfinex = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES},
};
std::map<std::string, std::string> fieldWebsocketChannelMapBitmex = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_BITMEX_CHANNEL_TRADE},
@@ -68,19 +70,23 @@ class SessionConfigs CCAPI_FINAL {
{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},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_KLINE},
};
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},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_KLINE},
};
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},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_KLINE},
};
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},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_KLINE},
};
std::map<std::string, std::string> fieldWebsocketChannelMapHuobi = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL},
@@ -97,6 +103,7 @@ class SessionConfigs CCAPI_FINAL {
std::map<std::string, std::string> fieldWebsocketChannelMapOkx = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_OKX_CHANNEL_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_OKX_CHANNEL_CANDLESTICK},
};
std::map<std::string, std::string> fieldWebsocketChannelMapErisx = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_ERISX_CHANNEL_MARKET_DATA_SUBSCRIBE},
@@ -105,6 +112,7 @@ class SessionConfigs CCAPI_FINAL {
std::map<std::string, std::string> fieldWebsocketChannelMapKucoin = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_MATCH},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_KLINES},
};
std::map<std::string, std::string> fieldWebsocketChannelMapKucoinFutures = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_KUCOIN_FUTURES_CHANNEL_MARKET_MATCH},
@@ -125,10 +133,12 @@ class SessionConfigs CCAPI_FINAL {
std::map<std::string, std::string> fieldWebsocketChannelMapGateio = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_GATEIO_CHANNEL_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_GATEIO_CHANNEL_ORDER_BOOK},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_GATEIO_CHANNEL_CANDLESTICKS},
};
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},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_CANDLESTICKS},
};
std::map<std::string, std::string> fieldWebsocketChannelMapCryptocom = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_TRADE},
@@ -136,23 +146,23 @@ class SessionConfigs CCAPI_FINAL {
};
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> fieldWebsocketChannelMapBybitDerivatives = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BYBIT_CHANNEL_ORDERBOOK},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_BYBIT_CHANNEL_KLINE},
};
std::map<std::string, std::string> fieldWebsocketChannelMapAscendex = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_DEPTH},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_BAR},
};
std::map<std::string, std::string> fieldWebsocketChannelMapBitget = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_KLINE},
};
std::map<std::string, std::string> fieldWebsocketChannelMapBitgetFutures = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_TRADES},
{CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS},
{CCAPI_CANDLESTICK, CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_KLINE},
};
std::map<std::string, std::string> fieldWebsocketChannelMapBitmart = {
{CCAPI_TRADE, CCAPI_WEBSOCKET_BITMART_CHANNEL_TRADE},
@@ -245,9 +255,6 @@ class SessionConfigs CCAPI_FINAL {
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBybit) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BYBIT].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapBybitDerivatives) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES].push_back(fieldWebsocketChannel.first);
}
for (auto const& fieldWebsocketChannel : fieldWebsocketChannelMapAscendex) {
this->exchangeFieldMap[CCAPI_EXCHANGE_NAME_ASCENDEX].push_back(fieldWebsocketChannel.first);
}
@@ -299,7 +306,6 @@ class SessionConfigs CCAPI_FINAL {
{CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES, fieldWebsocketChannelMapGateioPerpetualFutures},
{CCAPI_EXCHANGE_NAME_CRYPTOCOM, fieldWebsocketChannelMapCryptocom},
{CCAPI_EXCHANGE_NAME_BYBIT, fieldWebsocketChannelMapBybit},
{CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES, fieldWebsocketChannelMapBybitDerivatives},
{CCAPI_EXCHANGE_NAME_ASCENDEX, fieldWebsocketChannelMapAscendex},
{CCAPI_EXCHANGE_NAME_BITGET, fieldWebsocketChannelMapBitget},
{CCAPI_EXCHANGE_NAME_BITGET_FUTURES, fieldWebsocketChannelMapBitgetFutures},
@@ -319,7 +325,6 @@ class SessionConfigs CCAPI_FINAL {
{CCAPI_EXCHANGE_NAME_BITMEX, CCAPI_BITMEX_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE_US, CCAPI_BINANCE_US_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE, CCAPI_BINANCE_URL_WS_BASE},
// {CCAPI_EXCHANGE_NAME_BINANCE_MARGIN, CCAPI_BINANCE_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES, CCAPI_BINANCE_USDS_FUTURES_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES, CCAPI_BINANCE_COIN_FUTURES_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_HUOBI, CCAPI_HUOBI_URL_WS_BASE},
@@ -338,7 +343,6 @@ class SessionConfigs CCAPI_FINAL {
{CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES, CCAPI_GATEIO_PERPETUAL_FUTURES_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_CRYPTOCOM, CCAPI_CRYPTOCOM_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BYBIT, CCAPI_BYBIT_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES, CCAPI_BYBIT_DERIVATIVES_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_ASCENDEX, CCAPI_ASCENDEX_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BITGET, CCAPI_BITGET_URL_WS_BASE},
{CCAPI_EXCHANGE_NAME_BITGET_FUTURES, CCAPI_BITGET_FUTURES_URL_WS_BASE},
@@ -361,7 +365,6 @@ class SessionConfigs CCAPI_FINAL {
{CCAPI_EXCHANGE_NAME_BITMEX, CCAPI_BITMEX_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE_US, CCAPI_BINANCE_US_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE, CCAPI_BINANCE_URL_REST_BASE},
// {CCAPI_EXCHANGE_NAME_BINANCE_MARGIN, CCAPI_BINANCE_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES, CCAPI_BINANCE_USDS_FUTURES_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES, CCAPI_BINANCE_COIN_FUTURES_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_HUOBI, CCAPI_HUOBI_URL_REST_BASE},
@@ -378,7 +381,6 @@ class SessionConfigs CCAPI_FINAL {
{CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES, CCAPI_GATEIO_PERPETUAL_FUTURES_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_CRYPTOCOM, CCAPI_CRYPTOCOM_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BYBIT, CCAPI_BYBIT_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES, CCAPI_BYBIT_DERIVATIVES_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_ASCENDEX, CCAPI_ASCENDEX_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BITGET, CCAPI_BITGET_URL_REST_BASE},
{CCAPI_EXCHANGE_NAME_BITGET_FUTURES, CCAPI_BITGET_FUTURES_URL_REST_BASE},
+22 -23
View File
@@ -12,51 +12,50 @@ namespace ccapi {
class SessionOptions CCAPI_FINAL {
public:
std::string toString() const {
std::string output = "SessionOptions [warnLateEventMaxMilliSeconds = " + ccapi::toString(warnLateEventMaxMilliSeconds) +
", enableCheckSequence = " + ccapi::toString(enableCheckSequence) +
std::string output = "SessionOptions [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) +
", 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) +
", httpRequestTimeoutMilliseconds = " + ccapi::toString(httpRequestTimeoutMilliseconds) +
", httpConnectionPoolMaxSize = " + ccapi::toString(httpConnectionPoolMaxSize) +
", httpConnectionPoolIdleTimeoutMilliSeconds = " + ccapi::toString(httpConnectionPoolIdleTimeoutMilliSeconds) +
", httpConnectionKeepAliveTimeoutSeconds = " + ccapi::toString(httpConnectionKeepAliveTimeoutSeconds) +
", enableOneHttpConnectionPerRequest = " + ccapi::toString(enableOneHttpConnectionPerRequest) + "]";
return output;
}
long warnLateEventMaxMilliSeconds{}; // used to print a warning log message if en event arrives late
// 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
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};
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
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
long httpConnectionKeepAliveTimeoutSeconds{
10}; // used to remove a http connection from the http connection pool if it has stayed idle for at least this amount of time
bool enableOneHttpConnectionPerRequest{}; // create a new http connection for each request
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
long websocketConnectTimeoutMilliSeconds{10000};
long websocketConnectTimeoutMilliseconds{10000};
#endif
};
} /* namespace ccapi */
+6 -3
View File
@@ -3,6 +3,7 @@
#include <set>
#include <string>
#include "ccapi_cpp/ccapi_logger.h"
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_util_private.h"
namespace ccapi {
@@ -34,12 +35,14 @@ class Subscription CCAPI_FINAL {
this->optionMap[CCAPI_CONFLATE_GRACE_PERIOD_MILLISECONDS] = CCAPI_CONFLATE_GRACE_PERIOD_MILLISECONDS_DEFAULT;
this->optionMap[CCAPI_MARKET_DEPTH_RETURN_UPDATE] = CCAPI_MARKET_DEPTH_RETURN_UPDATE_DEFAULT;
this->optionMap[CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS] = CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS_DEFAULT;
this->optionMap[CCAPI_CANDLESTICK_INTERVAL_SECONDS] = CCAPI_CANDLESTICK_INTERVAL_SECONDS_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)};
std::set<std::string> executionManagementSubscriptionFieldSet = {std::string(CCAPI_EM_ORDER_UPDATE), std::string(CCAPI_EM_PRIVATE_TRADE),
std::string(CCAPI_EM_BALANCE_UPDATE), std::string(CCAPI_EM_POSITION_UPDATE)};
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) {
@@ -47,7 +50,7 @@ class Subscription CCAPI_FINAL {
} 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) {
} else if (field == CCAPI_MARKET_DEPTH || field == CCAPI_TRADE || field == CCAPI_AGG_TRADE || field == CCAPI_CANDLESTICK) {
this->serviceName = CCAPI_MARKET_DATA;
}
CCAPI_LOGGER_TRACE("this->serviceName = " + this->serviceName);
@@ -95,7 +98,7 @@ class Subscription CCAPI_FINAL {
}
return output;
}
const std::string getSerializedCredential() const { return ::ccapi::toString(this->credential); }
const std::string getSerializedCredential() const { return ccapi::toString(this->credential); }
// 'getTimeSent' only works in C++. For other languages, please use 'getTimeSentISO'.
TimePoint getTimeSent() const { return timeSent; }
std::string getTimeSentISO() const { return UtilTime::getISOTimestamp(timeSent); }
+1
View File
@@ -1,6 +1,7 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_UTIL_H_
#define INCLUDE_CCAPI_CPP_CCAPI_UTIL_H_
#include <chrono>
#include <sstream>
namespace ccapi {
typedef std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds> TimePoint;
} /* namespace ccapi */
+105 -25
View File
@@ -1,5 +1,8 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_UTIL_PRIVATE_H_
#define INCLUDE_CCAPI_CPP_CCAPI_UTIL_PRIVATE_H_
#ifdef _WIN32
#define timegm _mkgmtime
#endif
#include <unistd.h>
#include <algorithm>
@@ -9,6 +12,7 @@
#include <ctime>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <random>
@@ -21,8 +25,7 @@
#include <unordered_set>
#include <vector>
#include "ccapi_cpp/ccapi_date.h"
#include "ccapi_cpp/ccapi_logger.h"
#include "ccapi_cpp/ccapi_macro.h"
#include "ccapi_cpp/ccapi_util.h"
#include "openssl/evp.h"
namespace ccapi {
@@ -52,9 +55,12 @@ class UtilString CCAPI_FINAL {
output += ".";
output += c.substr(c.size() + exponent);
} else {
output = std::string(-exponent - c.size() + 1, '0');
output += ".";
output += c;
// output = std::string(-exponent - c.size() + 1, '0');
// output += ".";
// output += c; // use these three code, roundInputBySignificantFigure(0.00123456, 3, 1), output is "000.124"
output = "0.";
output += std::string(-exponent - c.size(), '0');
output += c; // use these three code, roundInputBySignificantFigure(0.00123456, 3, 1), output is "0.00124"
}
return output;
}
@@ -302,7 +308,8 @@ class UtilTime CCAPI_FINAL {
output += millisecondStr;
return output;
}
static void timePointToParts(TimePoint tp, int& year, int& month, int& day, int& hour, int& minute, int& second, int& millisecond) {
template <typename T = std::chrono::milliseconds>
static void timePointToParts(TimePoint tp, int& year, int& month, int& day, int& hour, int& minute, int& second, int& fractionalSecond) {
auto epoch_sec = std::chrono::time_point_cast<std::chrono::seconds>(tp).time_since_epoch().count();
auto day_sec = epoch_sec - (epoch_sec % 86400);
auto days_since_epoch = day_sec / 86400;
@@ -317,28 +324,46 @@ class UtilTime CCAPI_FINAL {
day = doy - (153 * mp + 2) / 5 + 1;
month = mp + (mp < 10 ? 3 : -9);
year += month <= 2;
auto in_day = tp - std::chrono::seconds(day_sec);
millisecond = std::chrono::time_point_cast<std::chrono::milliseconds>(in_day).time_since_epoch().count();
hour = millisecond / (60 * 60 * 1000);
millisecond -= hour * 60 * 60 * 1000;
minute = millisecond / (60 * 1000);
millisecond -= minute * 60 * 1000;
second = millisecond / 1000;
millisecond -= second * 1000;
auto in_day = tp - std::chrono::duration_cast<T>(std::chrono::seconds(day_sec));
auto in_day_sec_original = std::chrono::time_point_cast<std::chrono::seconds>(in_day).time_since_epoch().count();
auto in_day_sec = in_day_sec_original;
hour = in_day_sec / 3600;
in_day_sec -= hour * 3600;
minute = in_day_sec / 60;
second = in_day_sec - minute * 60;
auto in_day_fractional_second = in_day - std::chrono::duration_cast<T>(std::chrono::seconds(in_day_sec_original));
fractionalSecond = std::chrono::time_point_cast<T>(in_day_fractional_second).time_since_epoch().count();
}
static TimePoint now() {
auto now = std::chrono::system_clock::now();
return TimePoint(now);
}
static TimePoint parse(const std::string& s, const std::string& fmt = "%FT%TZ") {
TimePoint tp;
std::istringstream ss{s};
ss >> date::parse(fmt, tp);
if (ss.fail()) {
CCAPI_LOGGER_FATAL("unable to parse time string");
static TimePoint parse(const std::string& input) {
std::tm time{};
time.tm_year = std::strtol(&input[0], nullptr, 10) - 1900;
time.tm_mon = std::strtol(&input[5], nullptr, 10) - 1;
time.tm_mday = std::strtol(&input[8], nullptr, 10);
if (input.length() > 10) {
time.tm_hour = std::strtol(&input[11], nullptr, 10);
time.tm_min = std::strtol(&input[14], nullptr, 10);
time.tm_sec = std::strtol(&input[17], nullptr, 10);
}
return tp;
time.tm_isdst = 0;
long nanoseconds = 0;
if (input.length() > 20) {
std::string trail = input.substr(20);
if (trail.back() == 'Z') {
trail.pop_back();
}
if (!trail.empty()) {
if (trail.length() > 9) {
throw std::invalid_argument("input too long");
}
nanoseconds = std::stoll(UtilString::rightPadTo(trail, 9, '0'));
}
}
return TimePoint(std::chrono::system_clock::from_time_t(timegm(&time))) + std::chrono::nanoseconds(nanoseconds);
}
static TimePoint makeTimePoint(const std::pair<long long, long long>& timePair) {
auto tp = TimePoint(std::chrono::duration<int64_t>(timePair.first));
@@ -381,12 +406,65 @@ class UtilTime CCAPI_FINAL {
return std::make_pair(std::stoll(milliseconds), 0);
}
}
static std::string convertMillisecondsStrToSecondsStr(const std::string& milliseconds) {
std::string output;
if (milliseconds.length() >= 4) {
output = milliseconds;
output.insert(milliseconds.length() - 3, 1, '.');
} else {
output = "0.";
output += std::string(3 - milliseconds.length(), '0');
output += milliseconds;
output = UtilString::normalizeDecimalString(output);
}
return output;
}
static std::pair<long long, long long> divideNanoWhole(const std::string& nanoseconds) {
return std::make_pair(std::stoll(nanoseconds.substr(0, nanoseconds.length() - 9)), std::stoll(nanoseconds.substr(nanoseconds.length() - 9)));
}
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));
static std::string getISOTimestamp(const TimePoint& tp) {
int year, month, day, hour, minute, second, fractionalSecond;
timePointToParts<T>(tp, year, month, day, hour, minute, second, fractionalSecond);
std::string output;
output += std::to_string(year);
output += "-";
auto monthStr = std::to_string(month);
output += std::string(2 - monthStr.length(), '0');
output += monthStr;
output += "-";
auto dayStr = std::to_string(day);
output += std::string(2 - dayStr.length(), '0');
output += dayStr;
output += "T";
auto hourStr = std::to_string(hour);
output += std::string(2 - hourStr.length(), '0');
output += hourStr;
output += ":";
auto minuteStr = std::to_string(minute);
output += std::string(2 - minuteStr.length(), '0');
output += minuteStr;
output += ":";
auto secondStr = std::to_string(second);
output += std::string(2 - secondStr.length(), '0');
output += secondStr;
if (!std::is_same<T, std::chrono::seconds>::value) {
output += ".";
auto fractionalSecondStr = std::to_string(fractionalSecond);
int padToLength;
if (std::is_same<T, std::chrono::nanoseconds>::value) {
padToLength = 9;
} else if (std::is_same<T, std::chrono::microseconds>::value) {
padToLength = 6;
} else if (std::is_same<T, std::chrono::milliseconds>::value) {
padToLength = 3;
}
output += std::string(padToLength - fractionalSecondStr.length(), '0');
// UtilString::rtrimInPlace(fractionalSecondStr, '0');
output += fractionalSecondStr;
}
output += "Z";
return output;
}
static int getUnixTimestamp(const TimePoint& tp) {
auto then = tp.time_since_epoch();
@@ -415,7 +493,9 @@ class UtilAlgorithm CCAPI_FINAL {
EVP_DigestInit_ex(context, EVP_sha512(), NULL);
break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
// Release the context, adding an extra line here to avoid potential memory leaks that may occur in computeHash
EVP_MD_CTX_free(context);
throw std::invalid_argument("invalid shaVersion");
}
EVP_DigestUpdate(context, unhashed.c_str(), unhashed.length());
unsigned char hash[EVP_MAX_MD_SIZE];
@@ -657,7 +737,7 @@ int ceilSearch(const std::vector<T>& c, int low, int high, T x) {
if (x <= c[low]) {
return low;
}
for (i = low; i < high; i++) {
for (i = low; i < high - 1; i++) {
if (c[i] == x) {
return i;
}
+49 -29
View File
@@ -1,6 +1,6 @@
#ifndef INCLUDE_CCAPI_CPP_CCAPI_WS_CONNECTION_H_
#define INCLUDE_CCAPI_CPP_CCAPI_WS_CONNECTION_H_
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#include <string>
#include "ccapi_cpp/ccapi_logger.h"
@@ -91,31 +91,9 @@ class WsConnection CCAPI_FINAL {
: url(url), group(group), subscriptionList(subscriptionList), credential(credential), streamPtr(streamPtr) {
this->id = this->url + "||" + this->group + "||" + ccapi::toString(this->subscriptionList) + "||" + ccapi::toString(this->credential);
this->correlationIdList.reserve(subscriptionList.size());
std::transform(subscriptionList.cbegin(), subscriptionList.cend(), this->correlationIdList.begin(),
std::transform(subscriptionList.cbegin(), subscriptionList.cend(), std::back_inserter(this->correlationIdList),
[](Subscription subscription) { return subscription.getCorrelationId(); });
auto splitted1 = UtilString::split(url, "://");
auto foundSlash = splitted1.at(1).find_first_of('/');
auto foundQuestionMark = splitted1.at(1).find_first_of('?');
if (foundSlash == std::string::npos && foundQuestionMark == std::string::npos) {
this->path = "/";
} else if (foundSlash == std::string::npos && foundQuestionMark != std::string::npos) {
this->path = "/" + splitted1.at(1).substr(foundQuestionMark);
} else if (foundSlash != std::string::npos && foundQuestionMark == std::string::npos) {
this->path = splitted1.at(1).substr(foundSlash);
} else {
this->path = splitted1.at(1).substr(foundSlash);
}
auto splitted2 = UtilString::split(UtilString::split(splitted1.at(1), "/").at(0), ":");
this->host = splitted2.at(0);
if (splitted2.size() == 2) {
this->port = splitted2.at(1);
} else {
if (splitted1.at(0) == "https" || splitted1.at(0) == "wss") {
this->port = CCAPI_HTTPS_PORT_DEFAULT;
} else {
this->port = CCAPI_HTTP_PORT_DEFAULT;
}
}
this->setUrlParts();
}
WsConnection() {}
std::string toString() const {
@@ -127,7 +105,10 @@ class WsConnection CCAPI_FINAL {
oss << streamPtr;
std::string output = "WsConnection [id = " + id + ", url = " + url + ", group = " + group + ", subscriptionList = " + ccapi::toString(subscriptionList) +
", credential = " + ccapi::toString(shortCredential) + ", status = " + statusToString(status) +
", headers = " + ccapi::toString(headers) + ", streamPtr = " + oss.str() + "]";
", headers = " + ccapi::toString(headers) + ", streamPtr = " + oss.str() + ", remoteCloseCode = " + std::to_string(remoteCloseCode) +
", remoteCloseReason = " + std::string(remoteCloseReason.reason.c_str()) +
", hostHttpHeaderValue = " + ccapi::toString(hostHttpHeaderValue) + ", path = " + ccapi::toString(path) +
", host = " + ccapi::toString(host) + ", port = " + ccapi::toString(port) + "]";
return output;
}
enum class Status {
@@ -164,8 +145,43 @@ class WsConnection CCAPI_FINAL {
}
return output;
}
std::string getUrl() const { return url; }
void setUrl(const std::string& url) {
this->url = url;
this->setUrlParts();
}
void setUrlParts() {
auto splitted1 = UtilString::split(url, "://");
if (splitted1.size() >= 2) {
auto foundSlash = splitted1.at(1).find_first_of('/');
auto foundQuestionMark = splitted1.at(1).find_first_of('?');
if (foundSlash == std::string::npos && foundQuestionMark == std::string::npos) {
this->path = "/";
} else if (foundSlash == std::string::npos && foundQuestionMark != std::string::npos) {
this->path = "/" + splitted1.at(1).substr(foundQuestionMark);
} else if (foundSlash != std::string::npos && foundQuestionMark == std::string::npos) {
this->path = splitted1.at(1).substr(foundSlash);
} else {
this->path = splitted1.at(1).substr(foundSlash);
}
auto splitted2 = UtilString::split(UtilString::split(splitted1.at(1), "/").at(0), ":");
this->host = splitted2.at(0);
if (splitted2.size() == 2) {
this->port = splitted2.at(1);
} else {
if (splitted1.at(0) == "https" || splitted1.at(0) == "wss") {
this->port = CCAPI_HTTPS_PORT_DEFAULT;
} else {
this->port = CCAPI_HTTP_PORT_DEFAULT;
}
}
}
}
void appendUrlPart(const std::string& urlPart) {
this->url += urlPart;
this->setUrlParts();
}
std::string id;
std::string url;
std::string group;
std::vector<Subscription> subscriptionList;
std::vector<std::string> correlationIdList;
@@ -173,12 +189,16 @@ class WsConnection CCAPI_FINAL {
std::map<std::string, std::string> headers;
std::map<std::string, std::string> credential;
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream> > > streamPtr;
beast::websocket::close_code remoteCloseCode;
beast::websocket::close_reason remoteCloseReason;
beast::websocket::close_code remoteCloseCode{};
beast::websocket::close_reason remoteCloseReason{};
std::string hostHttpHeaderValue;
std::string path;
std::string host;
std::string port;
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
std::string url;
};
} /* namespace ccapi */
#endif
@@ -55,13 +55,13 @@ class ExecutionManagementService : public Service {
if (credential.empty()) {
credential = that->credentialDefault;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection wsConnection(that->baseUrlWs, "", {subscription}, credential);
that->prepareConnect(wsConnection);
#else
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> streamPtr(nullptr);
try {
streamPtr = that->createStream<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>>(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr, that->hostWs);
streamPtr = that->createWsStream(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr);
} catch (const beast::error_code& ec) {
CCAPI_LOGGER_TRACE("fail");
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "create stream", {subscription.getCorrelationId()});
@@ -115,10 +115,11 @@ class ExecutionManagementService : public Service {
Request::Operation operation = request.getOperation();
message.setType(this->requestOperationToMessageTypeMap.at(operation));
auto castedOperation = static_cast<int>(operation);
if (castedOperation >= Request::operationTypeExecutionManagementOrder && castedOperation < Request::operationTypeExecutionManagementAccount) {
if (castedOperation >= CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ORDER &&
castedOperation < CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ACCOUNT) {
this->extractOrderInfoFromRequest(elementList, request, operation, document);
message.setElementList(elementList);
} else if (castedOperation >= Request::operationTypeExecutionManagementAccount) {
} else if (castedOperation >= CCAPI_REQUEST_OPERATION_TYPE_EXECUTION_MANAGEMENT_ACCOUNT) {
this->extractAccountInfoFromRequest(elementList, request, operation, document);
message.setElementList(elementList);
}
@@ -163,8 +164,8 @@ class ExecutionManagementService : public Service {
this->eventHandler(event, eventQueuePtr);
}
}
virtual void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) {
virtual void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) {
for (const auto& y : extractionFieldNameMap) {
auto it = x.FindMember(y.second.first.c_str());
if (it != x.MemberEnd() && !it->value.IsNull()) {
@@ -175,6 +176,10 @@ class ExecutionManagementService : public Service {
if (y.first == CCAPI_EM_ORDER_SIDE) {
value = UtilString::toLower(value).rfind("buy", 0) == 0 ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL;
}
auto it2 = conversionMap.find(y.first);
if (it2 != conversionMap.end()) {
value = it2->second(value);
}
element.insert(y.first, value);
}
}
@@ -185,7 +190,7 @@ class ExecutionManagementService : public Service {
auto errorMessage = "Websocket unimplemented operation " + Request::operationToString(request.getOperation()) + " for exchange " + request.getExchange();
throw std::runtime_error(errorMessage);
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
virtual void logonToExchange(const WsConnection& wsConnection, const TimePoint& now, const std::map<std::string, std::string>& credential) {
CCAPI_LOGGER_INFO("about to logon to exchange");
CCAPI_LOGGER_INFO("exchange is " + this->exchangeName);
@@ -194,7 +199,7 @@ class ExecutionManagementService : public Service {
for (const auto& sendString : sendStringList) {
CCAPI_LOGGER_INFO("sendString = " + sendString);
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -208,7 +213,7 @@ class ExecutionManagementService : public Service {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
this->onTextMessage(wsConnection, subscription, textMessage, timeReceived);
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived);
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived, false);
}
void onOpen(wspp::connection_hdl hdl) override {
CCAPI_LOGGER_FUNCTION_ENTER;
@@ -252,7 +257,7 @@ class ExecutionManagementService : public Service {
void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived) override {
auto subscription = wsConnectionPtr->subscriptionList.at(0);
this->onTextMessage(wsConnectionPtr, subscription, textMessageView, timeReceived);
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, wsConnectionPtr, timeReceived);
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, wsConnectionPtr, timeReceived, false);
}
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override {
CCAPI_LOGGER_FUNCTION_ENTER;
@@ -329,7 +334,7 @@ class ExecutionManagementService : public Service {
that->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, "Websocket connection was not found", {correlationId});
return;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
auto& wsConnection = it->second;
#else
auto wsConnectionPtr = it->second;
@@ -353,7 +358,7 @@ class ExecutionManagementService : public Service {
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
CCAPI_LOGGER_TRACE("sendString = " + sendString);
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
that->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
that->send(wsConnectionPtr, sendString, ec);
@@ -389,10 +394,10 @@ class ExecutionManagementService : public Service {
std::string getAccountBalancesTarget;
std::string getAccountPositionsTarget;
std::map<std::string, std::string> correlationIdByConnectionIdMap;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
std::map<std::string, WsConnection> wsConnectionByCorrelationIdMap;
#else
std::map<std::string, std::shared_ptr<WsConnection> >
std::map<std::string, std::shared_ptr<WsConnection>>
wsConnectionByCorrelationIdMap; // TODO(cryptochassis): for consistency, to be renamed to wsConnectionPtrByCorrelationIdMap
#endif
std::map<std::string, int> wsRequestIdByConnectionIdMap;
@@ -14,19 +14,19 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_ASCENDEX_API_KEY;
this->apiSecretName = CCAPI_ASCENDEX_API_SECRET;
this->apiAccountGroupName = CCAPI_ASCENDEX_API_ACCOUNT_GROUP;
@@ -44,7 +44,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
private:
#endif
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; }
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); }
void onOpen(wspp::connection_hdl hdl) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
@@ -288,7 +288,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
this->extractOrderInfoFromRequest(elementList, document);
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const rj::Value& value) {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -337,8 +337,8 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("cumFilledQty");
@@ -347,7 +347,8 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
auto it1Str = std::string(it1->value.GetString());
auto it2Str = std::string(it2->value.GetString());
if (!it1Str.empty() && !it2Str.empty()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str))).toString());
}
}
}
@@ -363,13 +364,13 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
credential = that->credentialDefault;
}
const auto& accountGroup = mapGetWithDefault(credential, that->apiAccountGroupName);
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection wsConnection(that->baseUrlWs + "/" + accountGroup + "/api/pro/v1/stream", "", {subscription}, credential);
that->prepareConnect(wsConnection);
#else
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> streamPtr(nullptr);
try {
streamPtr = that->createStream<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>>(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr, that->hostWs);
streamPtr = that->createWsStream(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr);
} catch (const beast::error_code& ec) {
CCAPI_LOGGER_TRACE("fail");
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "create stream", {subscription.getCorrelationId()});
@@ -405,7 +406,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -428,7 +429,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -477,7 +478,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(data["t"].GetString()))));
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::INTEGER)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("sd", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("p", JsonDataType::STRING)},
@@ -491,7 +492,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
auto it = data.FindMember("ap");
if (it != data.MemberEnd() && !it->value.IsNull()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(data["cfq"].GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(data["cfq"].GetString()))).toString());
}
info.insert(CCAPI_EM_BASE_ASSET_QUANTITY_AVAILABLE_FOR_TRADING, data["bab"].GetString());
info.insert(CCAPI_EM_BASE_ASSET_QUANTITY_TOTAL, data["btb"].GetString());
@@ -522,8 +523,8 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -537,7 +538,7 @@ class ExecutionManagementServiceAscendex : public ExecutionManagementService {
} else if (m == "connected") {
std::string type = document["type"].GetString();
if (type == "unauth") {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
ExecutionManagementService::onOpen(hdl);
#else
ExecutionManagementService::onOpen(wsConnectionPtr);
@@ -17,19 +17,19 @@ class ExecutionManagementServiceBinance : public ExecutionManagementServiceBinan
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_API_KEY;
this->apiSecretName = CCAPI_BINANCE_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -18,7 +18,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void prepareConnect(WsConnection& wsConnection) override {
auto hostPort = this->extractHostFromUrl(this->baseUrlRest);
std::string host = hostPort.first;
@@ -74,7 +74,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
void onOpen(wspp::connection_hdl hdl) override {
ExecutionManagementService::onOpen(hdl);
@@ -138,7 +138,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
[wsConnection, that_2 = that->shared_from_base<ExecutionManagementServiceBinanceBase>()](const http::response<http::string_body>& res) {
CCAPI_LOGGER_DEBUG("ping listen key success");
},
that->sessionOptions.httpRequestTimeoutMilliSeconds);
that->sessionOptions.httpRequestTimeoutMilliseconds);
});
}
void onClose(wspp::connection_hdl hdl) override {
@@ -189,7 +189,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
std::string listenKey = document["listenKey"].GetString();
std::string url = that->baseUrlWs + "/" + listenKey;
wsConnectionPtr->url = url;
wsConnectionPtr->setUrl(url);
that->connect(wsConnectionPtr);
that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({
{"listenKey", listenKey},
@@ -201,7 +201,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
}
that->onFail_(wsConnectionPtr);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override {
ExecutionManagementService::onOpen(wsConnectionPtr);
@@ -265,7 +265,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
[wsConnectionPtr, that_2 = that->shared_from_base<ExecutionManagementServiceBinanceBase>()](const http::response<http::string_body>& res) {
CCAPI_LOGGER_DEBUG("ping listen key success");
},
that->sessionOptions.httpRequestTimeoutMilliSeconds);
that->sessionOptions.httpRequestTimeoutMilliseconds);
});
this->pingListenKeyTimerMapByConnectionIdMap[wsConnectionPtr->id] = timerPtr;
}
@@ -350,6 +350,11 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
queryString += "timeInForce=GTC&";
}
}
if (param.find("newClientOrderId") == param.end() && param.find(CCAPI_EM_CLIENT_ORDER_ID) == param.end()) {
std::string nonce = std::to_string(this->generateNonce(now, request.getIndex()));
queryString += std::string("newClientOrderId=x-") + (this->isDerivatives ? CCAPI_BINANCE_USDS_FUTURES_API_LINK_ID : CCAPI_BINANCE_API_LINK_ID) + "-" +
nonce + "&";
}
this->signRequest(queryString, param, now, credential);
req.target((request.getMarginType() == CCAPI_EM_MARGIN_TYPE_CROSS_MARGIN || request.getMarginType() == CCAPI_EM_MARGIN_TYPE_ISOLATED_MARGIN
? this->createOrderMarginTarget
@@ -446,6 +451,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair(this->isDerivatives ? "cumQuote" : "cummulativeQuoteQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
{CCAPI_LAST_UPDATED_TIME_SECONDS, std::make_pair("updateTime", JsonDataType::STRING)},
};
if (operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
extractionFieldNameMap.insert({CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("origClientOrderId", JsonDataType::STRING)});
@@ -454,12 +460,20 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
}
if (document.IsObject()) {
Element element;
this->extractOrderInfo(element, document, extractionFieldNameMap);
this->extractOrderInfo(
element, document, extractionFieldNameMap,
{
{CCAPI_LAST_UPDATED_TIME_SECONDS, [](const std::string& input) { return UtilTime::convertMillisecondsStrToSecondsStr(input); }},
});
elementList.emplace_back(std::move(element));
} else {
for (const auto& x : document.GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
this->extractOrderInfo(
element, x, extractionFieldNameMap,
{
{CCAPI_LAST_UPDATED_TIME_SECONDS, [](const std::string& input) { return UtilTime::convertMillisecondsStrToSecondsStr(input); }},
});
elementList.emplace_back(std::move(element));
}
}
@@ -475,6 +489,9 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
element.insert(CCAPI_EM_ASSET, x["asset"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["availableBalance"].GetString());
if (this->isDerivatives) {
element.insert(CCAPI_LAST_UPDATED_TIME_SECONDS, UtilTime::convertMillisecondsStrToSecondsStr(x["updateTime"].GetString()));
}
elementList.emplace_back(std::move(element));
}
} else {
@@ -526,7 +543,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -549,7 +566,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -630,7 +647,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
auto it = data.FindMember("ap");
if (it != data.MemberEnd() && !it->value.IsNull()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(data["z"].GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(data["z"].GetString()))).toString());
}
}
std::vector<Element> elementList;
@@ -639,6 +656,44 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService
messageList.emplace_back(std::move(message));
}
}
} else if (this->isDerivatives && type == "ACCOUNT_UPDATE") {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["a"];
if (fieldSet.find(CCAPI_EM_BALANCE_UPDATE) != fieldSet.end() && !data["B"].Empty()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(document["E"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE);
std::vector<Element> elementList;
for (const auto& x : data["B"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, x["a"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["wb"].GetString());
elementList.emplace_back(std::move(element));
}
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
if (fieldSet.find(CCAPI_EM_POSITION_UPDATE) != fieldSet.end() && !data["P"].Empty()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll((this->isDerivatives ? document : data)["E"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_POSITION_UPDATE);
std::vector<Element> elementList;
for (const auto& x : data["P"].GetArray()) {
Element element;
element.insert(CCAPI_INSTRUMENT, x["s"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["ps"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["pa"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["ep"].GetString());
element.insert(CCAPI_EM_UNREALIZED_PNL, x["up"].GetString());
elementList.emplace_back(std::move(element));
}
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
event.setMessageList(messageList);
return event;
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBinanceCoinFutures : public ExecutionManagementS
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_COIN_FUTURES_API_KEY;
this->apiSecretName = CCAPI_BINANCE_COIN_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -45,6 +45,12 @@ class ExecutionManagementServiceBinanceDerivativesBase : public ExecutionManagem
element.insert(CCAPI_EM_POSITION_QUANTITY, positionAmt);
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["entryPrice"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
if (x.HasMember("unrealizedProfit")) {
element.insert(CCAPI_EM_UNREALIZED_PNL, x["unrealizedProfit"].GetString());
} else {
element.insert(CCAPI_EM_UNREALIZED_PNL, x["unRealizedProfit"].GetString());
}
element.insert(CCAPI_LAST_UPDATED_TIME_SECONDS, UtilTime::convertMillisecondsStrToSecondsStr(x["updateTime"].GetString()));
elementList.emplace_back(std::move(element));
}
} break;
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBinanceUs : public ExecutionManagementServiceBin
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_US_API_KEY;
this->apiSecretName = CCAPI_BINANCE_US_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBinanceUsdsFutures : public ExecutionManagementS
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_USDS_FUTURES_API_KEY;
this->apiSecretName = CCAPI_BINANCE_USDS_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
this->baseUrlRest = CCAPI_BITFINEX_PRIVATE_URL_REST_BASE;
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITFINEX_API_KEY;
this->apiSecretName = CCAPI_BITFINEX_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -42,7 +42,7 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl, "{\"cid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec);
@@ -360,7 +360,7 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -383,7 +383,7 @@ class ExecutionManagementServiceBitfinex : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived){
#else
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITGET_API_KEY;
this->apiSecretName = CCAPI_BITGET_API_SECRET;
this->apiPassphraseName = CCAPI_BITGET_API_PASSPHRASE;
@@ -167,7 +167,7 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOrderId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -211,8 +211,8 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("accFillSz");
@@ -221,7 +221,8 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget
auto it1Str = std::string(it1->value.GetString());
auto it2Str = std::string(it2->value.GetString());
if (!it1Str.empty() && !it2Str.empty()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str))).toString());
}
}
}
@@ -254,7 +255,7 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
const TimePoint& timeReceived) override{
#else
@@ -295,7 +296,7 @@ class ExecutionManagementServiceBitget : public ExecutionManagementServiceBitget
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -365,7 +366,7 @@ Event createEvent(const Subscription& subscription, const std::string& textMessa
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -8,13 +8,15 @@ class ExecutionManagementServiceBitgetBase : public ExecutionManagementService {
public:
ExecutionManagementServiceBitgetBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->hostHttpHeaderValueIgnorePort = true;
}
virtual ~ExecutionManagementServiceBitgetBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); }
@@ -10,36 +10,36 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/mix/v1/stream";
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/ws/private";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITGET_FUTURES_API_KEY;
this->apiSecretName = CCAPI_BITGET_FUTURES_API_SECRET;
this->apiPassphraseName = CCAPI_BITGET_FUTURES_API_PASSPHRASE;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
this->createOrderTarget = "/api/mix/v1/order/placeOrder";
this->cancelOrderTarget = "/api/mix/v1/order/cancel-order";
this->getOrderTarget = "/api/mix/v1/order/detail";
this->getOpenOrdersTarget = "/api/mix/v1/order/current";
this->getAllOpenOrdersTarget = "/api/mix/v1/order/marginCoinCurrent";
this->cancelOpenOrdersTarget = "/api/mix/v1/order/cancel-all-orders";
this->getAccountBalancesTarget = "/api/mix/v1/account/accounts";
this->getAccountPositionsTarget = "/api/mix/v1/position/singlePosition";
this->getAccountAllPositionsTarget = "/api/mix/v1/position/allPosition";
this->createOrderTarget = "/api/v2/mix/order/place-order";
this->cancelOrderTarget = "/api/v2/mix/order/cancel-order";
this->getOrderTarget = "/api/v2/mix/order/detail";
this->getOpenOrdersTarget = "/api/v2/mix/order/orders-pending";
this->getAllOpenOrdersTarget = "/api/v2/mix/order/orders-pending";
this->cancelOpenOrdersTarget = "/api/v2/mix/order/cancel-all-orders";
this->getAccountBalancesTarget = "/api/v2/mix/account/accounts";
this->getAccountPositionsTarget = "/api/v2/mix/position/single-position";
this->getAccountAllPositionsTarget = "/api/v2/mix/position/all-position";
}
virtual ~ExecutionManagementServiceBitgetFutures() {}
#ifndef CCAPI_EXPOSE_INTERNAL
@@ -49,6 +49,7 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_MARGIN_ASSET, "marginCoin"},
{CCAPI_MARGIN_MODE, "marginMode"},
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_ORDER_QUANTITY, "size"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
@@ -65,8 +66,9 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
}
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_MARGIN_ASSET, "marginCoin"},
{CCAPI_EM_ORDER_ID, "orderId"},
{CCAPI_EM_CLIENT_ORDER_ID, "clientOrderId"},
{CCAPI_EM_CLIENT_ORDER_ID, "clientOid"},
{CCAPI_SYMBOL_ID, "symbol"},
{CCAPI_INSTRUMENT_TYPE, "productType"},
}) {
@@ -97,9 +99,6 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
if (param.find("orderType") == param.end()) {
document.AddMember("orderType", rj::Value("limit").Move(), allocator);
}
if (param.find("timeInForceValue") == param.end()) {
document.AddMember("timeInForceValue", rj::Value("normal").Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(document, allocator, symbolId);
}
@@ -213,26 +212,40 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("filledQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("baseVolume", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}};
const rj::Value& data = document["data"];
if (operation == Request::Operation::CREATE_ORDER || operation == Request::Operation::CANCEL_ORDER || operation == Request::Operation::GET_ORDER) {
const rj::Value& data = document["data"];
Element element;
this->extractOrderInfo(element, data, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
} else if (operation == Request::Operation::GET_OPEN_ORDERS) {
const rj::Value& data = document["data"]["entrustedList"];
for (const auto& x : data.GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
} else if (operation == Request::Operation::CANCEL_OPEN_ORDERS) {
const rj::Value& successList = document["data"]["successList"];
for (const auto& x : successList.GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
const rj::Value& failureList = document["data"]["failureList"];
for (const auto& x : failureList.GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
}
}
void extractAccountInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
@@ -241,12 +254,11 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
case Request::Operation::GET_ACCOUNT_BALANCES: {
for (const auto& x : document["data"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, x["coinName"].GetString());
std::string available = x["available"].GetString();
element.insert(CCAPI_EM_ASSET, x["marginCoin"].GetString());
std::string available = x["crossedMaxAvailable"].GetString();
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, available);
std::string frozen = x["frozen"].GetString();
std::string lock = x["lock"].GetString();
element.insert(CCAPI_EM_QUANTITY_TOTAL, (Decimal(available).add(Decimal(frozen)).add(Decimal(lock))).toString());
std::string locked = x["locked"].GetString();
element.insert(CCAPI_EM_QUANTITY_TOTAL, (Decimal(available).add(Decimal(locked))).toString());
elementList.emplace_back(std::move(element));
}
} break;
@@ -257,8 +269,9 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
element.insert(CCAPI_MARGIN_ASSET, x["marginCoin"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["holdSide"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["total"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["averageOpenPrice"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["openPriceAvg"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
element.insert(CCAPI_EM_UNREALIZED_PNL, x["unrealizedPL"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
@@ -266,17 +279,18 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("accFillSz");
auto it2 = x.FindMember("avgPx");
auto it1 = x.FindMember("accBaseVolume");
auto it2 = x.FindMember("priceAvg");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
auto it1Str = std::string(it1->value.GetString());
auto it2Str = std::string(it2->value.GetString());
if (!it1Str.empty() && !it2Str.empty()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str))).toString());
}
}
}
@@ -309,7 +323,7 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
const TimePoint& timeReceived) override {
#else
@@ -330,18 +344,29 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
rj::Value args(rj::kArrayType);
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
const auto& instrumentType = subscription.getInstrumentType();
for (const auto& field : fieldSet) {
std::string channel;
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
channel = "orders";
}
for (const auto& instrument : instrumentSet) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator);
arg.AddMember("instId", rj::Value(instrument.c_str(), allocator).Move(), allocator);
arg.AddMember("instType", rj::Value("spbl").Move(), allocator);
args.PushBack(arg, allocator);
}
if (field == CCAPI_EM_ORDER_UPDATE || field == CCAPI_EM_PRIVATE_TRADE) {
for (const auto& instrument : instrumentSet) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("orders", allocator).Move(), allocator);
arg.AddMember("instId", rj::Value(instrument.c_str(), allocator).Move(), allocator);
arg.AddMember("instType", rj::Value(instrumentType.c_str(), allocator).Move(), allocator);
args.PushBack(arg, allocator);
}
} else if (field == CCAPI_EM_POSITION_UPDATE) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("positions", allocator).Move(), allocator);
arg.AddMember("instId", rj::Value("default", allocator).Move(), allocator);
arg.AddMember("instType", rj::Value(instrumentType.c_str(), allocator).Move(), allocator);
args.PushBack(arg, allocator);
} else if (field == CCAPI_EM_BALANCE_UPDATE) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("account", allocator).Move(), allocator);
arg.AddMember("coin", rj::Value("default", allocator).Move(), allocator);
arg.AddMember("instType", rj::Value(instrumentType.c_str(), allocator).Move(), allocator);
args.PushBack(arg, allocator);
}
}
document.AddMember("args", args, allocator);
rj::StringBuffer stringBufferSubscribe;
@@ -349,7 +374,7 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -358,7 +383,7 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
}
} else {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event event = this->createEvent(wsConnection, wsConnection.hdl, subscription, textMessage, document, eventStr, timeReceived);
#else
Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, eventStr, timeReceived);
@@ -369,7 +394,7 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
}
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const std::string& eventStr, const TimePoint& timeReceived) {
#else
@@ -389,8 +414,9 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
const rj::Value& arg = document["arg"];
std::string channel = std::string(arg["channel"].GetString());
event.setType(Event::Type::SUBSCRIPTION_DATA);
std::string instrument = arg["instId"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
std::string instId = (channel == "account") ? "coin" : "instId";
std::string instrument = arg[instId.c_str()].GetString();
if (instrumentSet.empty() || instrument == "default" || instrumentSet.find(instrument) != instrumentSet.end()) {
if (channel == "orders") {
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
const rj::Value& data = document["data"];
@@ -406,15 +432,19 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, tradeId);
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["fillPx"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["fillSz"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["fillPrice"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["baseVolume"].GetString()));
element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_IS_MAKER, std::string(x["execType"].GetString()) == "M" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["ordId"].GetString()));
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdId"].GetString()));
element.insert(CCAPI_IS_MAKER, std::string(x["tradeScope"].GetString()) == "M" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["orderId"].GetString()));
auto itClientOId = x.FindMember("clientOId");
std::string clientOId = itClientOId != x.MemberEnd() ? itClientOId->value.GetString() : "";
if(!clientOId.empty()){
element.insert(CCAPI_EM_CLIENT_ORDER_ID, clientOId);
}
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fillFee"].GetString()));
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCcy"].GetString()));
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCoin"].GetString()));
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
@@ -429,13 +459,13 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)},
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("px", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("sz", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accFillSz", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("size", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accBaseVolume", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
};
Element info;
@@ -447,6 +477,42 @@ class ExecutionManagementServiceBitgetFutures : public ExecutionManagementServic
messageList.emplace_back(std::move(message));
}
}
} else if (channel == "positions"){
const rj::Value& data = document["data"];
for (const auto& x : data.GetArray()) {
auto time = TimePoint(std::chrono::milliseconds(std::stoll(x["uTime"].GetString())));
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(time);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_POSITION_UPDATE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_INSTRUMENT, x["instId"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["holdSide"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["total"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["openPriceAvg"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
} else if (channel == "account"){
const rj::Value& data = document["data"];
for (const auto& x : data.GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_EM_ASSET, x["marginCoin"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["equity"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["available"].GetString());
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
} else if (eventStr == "subscribe") {
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITMART_API_KEY;
this->apiSecretName = CCAPI_BITMART_API_SECRET;
this->apiMemoName = CCAPI_BITMART_API_MEMO;
@@ -38,7 +38,7 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService {
this->cancelOpenOrdersTarget = "/spot/v1/cancel_orders";
this->getAccountBalancesTarget = "/spot/v1/wallet";
this->needDecompressWebsocketMessage = true;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
ErrorCode ec = this->inflater.init(false);
#else
ErrorCode ec = this->inflater.init();
@@ -52,7 +52,7 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService {
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); }
@@ -141,6 +141,7 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService {
case Request::Operation::CREATE_ORDER: {
req.method(http::verb::post);
req.target(this->createOrderTarget);
req.set("X-BM-BROKER-ID", CCAPI_BITMART_BROKER_ID);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
rj::Document document;
document.SetObject();
@@ -301,7 +302,7 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
const TimePoint& timeReceived) override {
#else
@@ -338,7 +339,7 @@ class ExecutionManagementServiceBitmart : public ExecutionManagementService {
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITMEX_API_KEY;
this->apiSecretName = CCAPI_BITMEX_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -224,7 +224,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderID", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdID", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -272,15 +272,17 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("cumQty");
auto it2 = x.FindMember("avgPx");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))));
element.insert(
CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))))
.toString());
}
}
}
@@ -311,7 +313,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -334,7 +336,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived){
#else
@@ -404,7 +406,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -448,7 +450,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
}
} else if (table == "order" && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderID", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdID", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -464,7 +466,7 @@ class ExecutionManagementServiceBitmex : public ExecutionManagementService {
auto it = x.FindMember("avgPx");
if (it != x.MemberEnd() && !it->value.IsNull()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it->value.GetString()) * std::stod(x["cumQty"].GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it->value.GetString()) * std::stod(x["cumQty"].GetString()))).toString());
}
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
@@ -14,19 +14,19 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITSTAMP_API_KEY;
this->apiSecretName = CCAPI_BITSTAMP_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -44,7 +44,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
this->send(hdl, R"({"event": "bts:heartbeat"})", wspp::frame::opcode::text, ec);
}
@@ -204,8 +204,8 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("type");
@@ -274,7 +274,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void prepareConnect(WsConnection& wsConnection) override {
auto now = UtilTime::now();
auto hostPort = this->extractHostFromUrl(this->baseUrlRest);
@@ -329,7 +329,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#else
void prepareConnect(std::shared_ptr<WsConnection> wsConnectionPtr) override {
@@ -367,7 +367,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
if (document.HasMember("token") && document.HasMember("user_id")) {
std::string token = document["token"].GetString();
std::string userId = document["user_id"].GetString();
wsConnectionPtr->url = that->baseUrlWs;
wsConnectionPtr->setUrl(that->baseUrlWs);
that->connect(wsConnectionPtr);
that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({
{"token", token},
@@ -381,7 +381,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
}
that->onFail_(wsConnectionPtr);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#endif
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
@@ -416,7 +416,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
}
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -439,7 +439,7 @@ class ExecutionManagementServiceBitstamp : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -2,51 +2,134 @@
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
#include "ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h"
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBase {
class ExecutionManagementServiceBybit : public ExecutionManagementService {
public:
ExecutionManagementServiceBybit(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/private/v3";
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v5/private";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
this->apiKeyName = CCAPI_BYBIT_API_KEY;
this->apiSecretName = CCAPI_BYBIT_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = "/spot/v3/private/order";
this->cancelOrderTarget = "/spot/v3/private/cancel-order";
this->getOrderTarget = "/spot/v3/private/order";
this->getOpenOrdersTarget = "/spot/v3/private/open-orders";
this->cancelOpenOrdersTarget = "/spot/v3/private/cancel-orders";
this->getAccountBalancesTarget = "/spot/v3/private/account";
this->createOrderTarget = "/v5/order/create";
this->cancelOrderTarget = "/v5/order/cancel";
this->getOrderTarget = "/v5/order/realtime";
this->getOpenOrdersTarget = "/v5/order/realtime";
this->cancelOpenOrdersTarget = "/v5/order/cancel-all";
this->getAccountBalancesTarget = "/v5/account/wallet-balance";
this->getAccountPositionsTarget = "/v5/position/list";
}
virtual ~ExecutionManagementServiceBybit() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("retCode":0)") == std::string::npos; }
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); }
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& req, const Request& request, std::string& methodString,
std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("X-BAPI-TIMESTAMP").to_string();
preSignedText += apiKey;
preSignedText += req.base().at("X-BAPI-RECV-WINDOW").to_string();
std::string aString;
if (methodString == "GET") {
aString = queryString;
} else if (methodString == "POST") {
aString = body;
}
preSignedText += aString;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
req.set("X-BAPI-SIGN", signature);
}
void signRequest(http::request<http::string_body>& req, const std::string aString, const TimePoint& now,
const std::map<std::string, std::string>& credential) {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("X-BAPI-TIMESTAMP").to_string();
preSignedText += apiKey;
preSignedText += req.base().at("X-BAPI-RECV-WINDOW").to_string();
preSignedText += aString;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
req.set("X-BAPI-SIGN", signature);
}
void appendParamToQueryString(std::string& queryString, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"},
{CCAPI_EM_ORDER_ID, "orderId"},
{CCAPI_SETTLE_ASSET, "settleCoin"},
{CCAPI_EM_ACCOUNT_TYPE, "accountType"},
}) {
for (const auto& kv : param) {
queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
queryString += "=";
queryString += Url::urlEncode(kv.second);
queryString += "&";
}
}
void prepareReq(http::request<http::string_body>& req, const TimePoint& now, const std::map<std::string, std::string>& credential) {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("X-BAPI-API-KEY", apiKey);
req.set("X-BAPI-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
req.set("X-BAPI-RECV-WINDOW", std::to_string(CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS));
req.set("X-Referer", CCAPI_BYBIT_API_BROKER_ID);
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
std::vector<std::string> sendStringList;
rj::Document document;
document.SetObject();
auto& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("auth").Move(), allocator);
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto expires = std::chrono::duration_cast<std::chrono::milliseconds>(
(now + std::chrono::milliseconds(CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS)).time_since_epoch())
.count();
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string preSignedText = "GET";
preSignedText += "/realtime";
preSignedText += std::to_string(expires);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
rj::Value args(rj::kArrayType);
args.PushBack(rj::Value(apiKey.c_str(), allocator).Move(), allocator);
args.PushBack(rj::Value(expires).Move(), allocator);
args.PushBack(rj::Value(signature.c_str(), allocator).Move(), allocator);
document.AddMember("args", args, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
return sendStringList;
}
void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const TimePoint& timeReceived) override {
std::string textMessage(textMessageView);
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived);
if (!event.getMessageList().empty()) {
this->eventHandler(event, nullptr);
}
}
void appendParam(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_ORDER_QUANTITY, "orderQty"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "orderPrice"},
{CCAPI_EM_ORDER_QUANTITY, "qty"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"},
{CCAPI_EM_ORDER_ID, "orderId"},
{CCAPI_LIMIT, "limit"},
@@ -58,11 +141,7 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
value = value == CCAPI_EM_ORDER_SIDE_BUY ? "Buy" : "Sell";
}
if (value != "null") {
if (key == "orderCategory") {
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), std::stoi(value), allocator);
} else {
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
}
}
@@ -82,8 +161,11 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
if (param.find("category") == param.end()) {
document.AddMember("category", rj::Value("spot").Move(), allocator);
}
if (param.find("orderType") == param.end()) {
document.AddMember("orderType", rj::Value("LIMIT").Move(), allocator);
document.AddMember("orderType", rj::Value("Limit").Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(document, allocator, symbolId, "symbol");
@@ -105,6 +187,12 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
if (param.find("category") == param.end()) {
document.AddMember("category", rj::Value("spot").Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(document, allocator, symbolId, "symbol");
}
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
@@ -118,6 +206,9 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param);
if (param.find("category") == param.end()) {
queryString += "category=spot&";
}
req.target(this->getOrderTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
@@ -126,6 +217,9 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param);
if (param.find("category") == param.end()) {
queryString += "category=spot&";
}
if (!symbolId.empty()) {
this->appendSymbolId(queryString, symbolId, "symbol");
}
@@ -141,6 +235,9 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
if (param.find("category") == param.end()) {
document.AddMember("category", rj::Value("spot").Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(document, allocator, symbolId, "symbol");
}
@@ -155,8 +252,20 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
case Request::Operation::GET_ACCOUNT_BALANCES: {
req.method(http::verb::get);
std::string queryString;
this->appendParamToQueryString(queryString, {});
req.target(this->getAccountBalancesTarget);
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param);
if (param.find("accountType") == param.end()) {
queryString += "accountType=UNIFIED&";
}
req.target(this->getAccountBalancesTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
req.method(http::verb::get);
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param);
req.target(this->getAccountPositionsTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
default:
@@ -169,14 +278,14 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("orderLinkId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("orderQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("orderPrice", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("execQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cummulativeQuoteQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("status", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("qty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumExecQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cumExecValue", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("orderStatus", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
};
if (operation == Request::Operation::GET_OPEN_ORDERS) {
if (operation == Request::Operation::GET_OPEN_ORDERS || operation == Request::Operation::GET_ORDER || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
for (const auto& x : document["result"]["list"].GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
@@ -192,11 +301,22 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
const rj::Document& document) override {
switch (request.getOperation()) {
case Request::Operation::GET_ACCOUNT_BALANCES: {
for (const auto& x : document["result"]["balances"].GetArray()) {
for (const auto& x : document["result"]["list"][0]["coin"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, x["coin"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["total"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["free"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["equity"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
for (const auto& x : document["result"]["list"].GetArray()) {
Element element;
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["side"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgPrice"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
@@ -204,79 +324,41 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) override{
#else
Event createEvent(const std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const rj::Document& document, const TimePoint& timeReceived) override {
const rj::Document& document, const TimePoint& timeReceived) {
std::string textMessage(textMessageView);
#endif
Event event;
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
if (document.HasMember("topic")) {
std::string topic = document["topic"].GetString();
if (topic == "order") {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"];
for (const auto& x : data.GetArray()) {
std::string instrument = x["s"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
auto time = TimePoint(std::chrono::milliseconds(std::stoll(x["E"].GetString())));
auto itTradeId = x.FindMember("t");
if (itTradeId != x.MemberEnd() && !itTradeId->value.IsNull() && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(time);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, itTradeId->value.GetString());
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["L"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["l"].GetString()));
element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["S"].GetString()) == "BUY" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_IS_MAKER, x["m"].GetBool() ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["i"].GetString()));
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["c"].GetString()));
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
{
auto it = x.FindMember("n");
if (it != x.MemberEnd() && !it->value.IsNull()) {
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(it->value.GetString()));
}
}
{
auto it = x.FindMember("N");
if (it != x.MemberEnd() && !it->value.IsNull()) {
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(it->value.GetString()));
}
}
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
Event event;
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
if (document.HasMember("topic")) {
std::string topic = document["topic"].GetString();
if (topic.rfind("order", 0) == 0) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"];
for (const auto& x : data.GetArray()) {
std::string instrument = x["symbol"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
auto time = TimePoint(std::chrono::milliseconds(std::stoll(x["updatedTime"].GetString())));
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(time);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("i", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("c", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("S", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("p", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("q", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("z", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("Z", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("X", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("s", JsonDataType::STRING)},
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("orderLinkId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("qty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumExecQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cumExecValue", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("orderStatus", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
};
Element info;
this->extractOrderInfo(info, x, extractionFieldNameMap);
@@ -286,57 +368,127 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa
messageList.emplace_back(std::move(message));
}
}
}
}
} else if (document.HasMember("op")) {
std::string op = document["op"].GetString();
if (op == "auth") {
bool success = document["success"].GetBool();
if (success) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
rj::Value args(rj::kArrayType);
args.PushBack(rj::Value("order").Move(), allocator);
document.AddMember("args", args, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
this->send(hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
#endif
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
} else if (topic.rfind("execution", 0) == 0) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"];
for (const auto& x : data.GetArray()) {
std::string instrument = x["symbol"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
auto time = TimePoint(std::chrono::milliseconds(std::stoll(x["execTime"].GetString())));
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(time);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, x["execId"].GetString());
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["execPrice"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["execQty"].GetString()));
element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "Buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_IS_MAKER, x["isMaker"].GetBool() ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["orderId"].GetString()));
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["orderLinkId"].GetString()));
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
{
auto it = x.FindMember("execFee");
if (it != x.MemberEnd() && !it->value.IsNull()) {
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(it->value.GetString()));
}
}
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
} else if (topic == "wallet") {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"];
for (const auto& x : data[0]["coin"].GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_EM_ASSET, x["coin"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["equity"].GetString());
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
} else if (topic.rfind("position", 0) == 0) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"];
for (const auto& x : data.GetArray()) {
std::string instrument = x["symbol"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
auto time = TimePoint(std::chrono::milliseconds(std::stoll(x["updatedTime"].GetString())));
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(time);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_POSITION_UPDATE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["side"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["entryPrice"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
} else if (op == "subscribe") {
bool success = document["success"].GetBool();
event.setType(Event::Type::SUBSCRIPTION_STATUS);
message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
}
} else if (document.HasMember("ret_code")) {
std::string ret_code = document["ret_code"].GetString();
if (ret_code != "0") {
event.setType(Event::Type::SUBSCRIPTION_STATUS);
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
} else if (document.HasMember("op")) {
std::string op = document["op"].GetString();
if (op == "auth") {
bool success = document["success"].GetBool();
if (success) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
rj::Value args(rj::kArrayType);
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
args.PushBack(rj::Value(("order." + subscription.getInstrumentType()).c_str(), allocator).Move(), allocator);
}
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
args.PushBack(rj::Value(("execution." + subscription.getInstrumentType()).c_str(), allocator).Move(), allocator);
}
if (fieldSet.find(CCAPI_EM_POSITION_UPDATE) != fieldSet.end() && subscription.getInstrumentType() != "spot") {
args.PushBack(rj::Value(("position." + subscription.getInstrumentType()).c_str(), allocator).Move(), allocator);
}
if (fieldSet.find(CCAPI_EM_BALANCE_UPDATE) != fieldSet.end()) {
args.PushBack(rj::Value("wallet").Move(), allocator);
}
document.AddMember("args", args, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
ErrorCode ec;
this->send(wsConnectionPtr, sendString, ec);
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
}
}
} else if (op == "subscribe") {
bool success = document["success"].GetBool();
event.setType(Event::Type::SUBSCRIPTION_STATUS);
message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
}
}
event.setMessageList(messageList);
return event;
}
event.setMessageList(messageList);
return event;
}
}; // namespace ccapi
} /* namespace ccapi */
#endif
@@ -1,140 +0,0 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#if defined(CCAPI_ENABLE_EXCHANGE_BYBIT) || defined(CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES)
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceBybitBase : public ExecutionManagementService {
public:
ExecutionManagementServiceBybitBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
ServiceContextPtr serviceContextPtr)
: ExecutionManagementService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~ExecutionManagementServiceBybitBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("retCode":0)") == std::string::npos; }
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); }
#endif
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& req, const Request& request, std::string& methodString,
std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("X-BAPI-TIMESTAMP").to_string();
preSignedText += apiKey;
preSignedText += req.base().at("X-BAPI-RECV-WINDOW").to_string();
std::string aString;
if (methodString == "GET") {
aString = queryString;
} else if (methodString == "POST") {
aString = body;
}
preSignedText += aString;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
req.set("X-BAPI-SIGN", signature);
}
void signRequest(http::request<http::string_body>& req, const std::string aString, const TimePoint& now,
const std::map<std::string, std::string>& credential) {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("X-BAPI-TIMESTAMP").to_string();
preSignedText += apiKey;
preSignedText += req.base().at("X-BAPI-RECV-WINDOW").to_string();
preSignedText += aString;
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
req.set("X-BAPI-SIGN", signature);
}
void appendParamToQueryString(std::string& queryString, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {}) {
for (const auto& kv : param) {
queryString += standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
queryString += "=";
queryString += Url::urlEncode(kv.second);
queryString += "&";
}
}
// void appendSymbolId(std::string& queryString, const std::string& symbolId) {
// queryString += "symbol=";
// queryString += Url::urlEncode(symbolId);
// queryString += "&";
// }
// void appendSymbolId(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
// rjValue.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
// }
void prepareReq(http::request<http::string_body>& req, const TimePoint& now, const std::map<std::string, std::string>& credential) {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("X-BAPI-SIGN-TYPE", "2");
req.set("X-BAPI-API-KEY", apiKey);
req.set("X-BAPI-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
req.set("X-BAPI-RECV-WINDOW", std::to_string(CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS));
req.set("Referer", CCAPI_BYBIT_API_BROKER_ID);
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
std::vector<std::string> sendStringList;
rj::Document document;
document.SetObject();
auto& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("auth").Move(), allocator);
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
auto expires = std::chrono::duration_cast<std::chrono::milliseconds>(
(now + std::chrono::milliseconds(CCAPI_BYBIT_BASE_API_RECEIVE_WINDOW_MILLISECONDS)).time_since_epoch())
.count();
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
std::string preSignedText = "GET";
preSignedText += "/realtime";
preSignedText += std::to_string(expires);
auto signature = Hmac::hmac(Hmac::ShaVersion::SHA256, apiSecret, preSignedText, true);
rj::Value args(rj::kArrayType);
args.PushBack(rj::Value(apiKey.c_str(), allocator).Move(), allocator);
args.PushBack(rj::Value(expires).Move(), allocator);
args.PushBack(rj::Value(signature.c_str(), allocator).Move(), allocator);
document.AddMember("args", args, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
Event event = this->createEvent(wsConnection, hdl, subscription, textMessage, document, timeReceived);
if (!event.getMessageList().empty()) {
this->eventHandler(event, nullptr);
}
}
virtual Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
return {};
}
#else
void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const TimePoint& timeReceived) override {
std::string textMessage(textMessageView);
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived);
if (!event.getMessageList().empty()) {
this->eventHandler(event, nullptr);
}
}
virtual Event createEvent(std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const rj::Document& document, const TimePoint& timeReceived) {
return {};
}
#endif
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_
@@ -1,389 +0,0 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_DERIVATIVES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_DERIVATIVES_H_
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES
#include "ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h"
namespace ccapi {
class ExecutionManagementServiceBybitDerivatives : public ExecutionManagementServiceBybitBase {
public:
ExecutionManagementServiceBybitDerivatives(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions,
SessionConfigs sessionConfigs, ServiceContextPtr serviceContextPtr)
: ExecutionManagementServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/unified/private/v3";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
this->apiKeyName = CCAPI_BYBIT_DERIVATIVES_API_KEY;
this->apiSecretName = CCAPI_BYBIT_DERIVATIVES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
this->createOrderTarget = "/unified/v3/private/order/create";
this->cancelOrderTarget = "/unified/v3/private/order/cancel";
this->getOrderTarget = "/unified/v3/private/order/list";
this->getOpenOrdersTarget = "/unified/v3/private/order/unfilled-orders";
this->cancelOpenOrdersTarget = "/unified/v3/private/order/cancel-all";
this->getAccountBalancesTarget = "/unified/v3/private/account/wallet/balance";
this->getAccountPositionsTarget = "/unified/v3/private/position/list";
}
virtual ~ExecutionManagementServiceBybitDerivatives() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
void appendParam(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_EM_ORDER_SIDE, "side"},
{CCAPI_EM_ORDER_QUANTITY, "qty"},
{CCAPI_EM_ORDER_LIMIT_PRICE, "price"},
{CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"},
{CCAPI_EM_ORDER_ID, "orderId"},
{CCAPI_LIMIT, "limit"},
{CCAPI_INSTRUMENT_TYPE, "category"},
}) {
for (const auto& kv : param) {
auto key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first;
auto value = kv.second;
if (key == "side") {
value = value == CCAPI_EM_ORDER_SIDE_BUY ? "Buy" : "Sell";
}
if (value != "null") {
if (key == "reduceOnly" || key == "closeOnTrigger" || key == "mmp") {
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), value == "true", allocator);
} else {
rjValue.AddMember(rj::Value(key.c_str(), allocator).Move(), rj::Value(value.c_str(), allocator).Move(), allocator);
}
}
}
}
void convertRequestForRest(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
this->prepareReq(req, now, credential);
switch (request.getOperation()) {
case Request::Operation::GENERIC_PRIVATE_REQUEST: {
ExecutionManagementService::convertRequestForRestGenericPrivateRequest(req, request, now, symbolId, credential);
} break;
case Request::Operation::CREATE_ORDER: {
req.method(http::verb::post);
req.set(beast::http::field::content_type, "application/json");
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->createOrderTarget);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
if (param.find("orderType") == param.end()) {
document.AddMember("orderType", rj::Value("Limit").Move(), allocator);
}
if (!symbolId.empty()) {
this->appendSymbolId(document, allocator, symbolId, "symbol");
}
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
auto body = stringBuffer.GetString();
req.body() = body;
req.prepare_payload();
this->signRequest(req, body, now, credential);
} break;
case Request::Operation::CANCEL_ORDER: {
req.method(http::verb::post);
req.set(beast::http::field::content_type, "application/json");
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->cancelOrderTarget);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
this->appendSymbolId(document, allocator, symbolId, "symbol");
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
auto body = stringBuffer.GetString();
req.body() = body;
req.prepare_payload();
this->signRequest(req, body, now, credential);
} break;
case Request::Operation::GET_ORDER: {
req.method(http::verb::get);
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param,
{
{CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"},
{CCAPI_EM_ORDER_ID, "orderId"},
{CCAPI_LIMIT, "limit"},
{CCAPI_INSTRUMENT_TYPE, "category"},
});
req.target(this->getOrderTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
case Request::Operation::GET_OPEN_ORDERS: {
req.method(http::verb::get);
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param,
{
{CCAPI_EM_CLIENT_ORDER_ID, "orderLinkId"},
{CCAPI_EM_ORDER_ID, "orderId"},
{CCAPI_LIMIT, "limit"},
{CCAPI_INSTRUMENT_TYPE, "category"},
});
if (!symbolId.empty()) {
this->appendSymbolId(queryString, symbolId, "symbol");
}
req.target(this->getOpenOrdersTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
case Request::Operation::CANCEL_OPEN_ORDERS: {
req.method(http::verb::post);
req.set(beast::http::field::content_type, "application/json");
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
req.target(this->cancelOpenOrdersTarget);
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
this->appendParam(document, allocator, param);
if (!symbolId.empty()) {
this->appendSymbolId(document, allocator, symbolId, "symbol");
}
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
auto body = stringBuffer.GetString();
req.body() = body;
req.prepare_payload();
this->signRequest(req, body, now, credential);
} break;
case Request::Operation::GET_ACCOUNT_BALANCES: {
req.method(http::verb::get);
std::string queryString;
this->appendParamToQueryString(queryString, {});
req.target(queryString.empty() ? this->getAccountBalancesTarget : this->getAccountBalancesTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
req.method(http::verb::get);
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParamToQueryString(queryString, param);
req.target(this->getAccountPositionsTarget + "?" + queryString);
this->signRequest(req, queryString, now, credential);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
std::map<std::string, std::pair<std::string, JsonDataType> > extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("qty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumExecQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cumExecValue", JsonDataType::STRING)},
{CCAPI_EM_ORDER_REMAINING_QUANTITY, std::make_pair("leavesQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("orderStatus", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
};
if (operation == Request::Operation::GET_ORDER || operation == Request::Operation::GET_OPEN_ORDERS || operation == Request::Operation::CANCEL_OPEN_ORDERS) {
for (const auto& x : document["result"]["list"].GetArray()) {
Element element;
this->extractOrderInfo(element, x, extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
} else {
Element element;
this->extractOrderInfo(element, document["result"], extractionFieldNameMap);
elementList.emplace_back(std::move(element));
}
}
void extractAccountInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
switch (request.getOperation()) {
case Request::Operation::GET_ACCOUNT_BALANCES: {
for (const auto& x : document["result"]["coin"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, x["currencyCoin"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["walletBalance"].GetString());
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, x["availableBalance"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
case Request::Operation::GET_ACCOUNT_POSITIONS: {
for (const auto& x : document["result"]["list"].GetArray()) {
Element element;
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["side"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["entryPrice"].GetString());
element.insert(CCAPI_EM_POSITION_LEVERAGE, x["leverage"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) override{
#else
Event createEvent(const std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const rj::Document& document, const TimePoint& timeReceived) override {
std::string textMessage(textMessageView);
#endif
Event event;
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
if (document.HasMember("topic")) {
std::string topic = document["topic"].GetString();
if (topic == "user.order.unifiedAccount") {
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"]["result"];
for (const auto& x : data.GetArray()) {
std::string instrument = x["symbol"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["updatedTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::INTEGER)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("orderLinkId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("qty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumExecQty", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cumExecValue", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("orderStatus", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)},
};
Element info;
this->extractOrderInfo(info, x, extractionFieldNameMap);
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
} else if (topic == "user.execution.unifiedAccount") {
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
event.setType(Event::Type::SUBSCRIPTION_DATA);
const rj::Value& data = document["data"]["result"];
for (const auto& x : data.GetArray()) {
std::string execType = x["execType"].GetString();
if (execType == "TRADE") {
std::string instrument = x["symbol"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["execTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, x["execId"].GetString());
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, x["execPrice"].GetString());
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, x["execQty"].GetString());
element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "Buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_IS_MAKER, std::string(x["lastLiquidityInd"].GetString()) == "MAKER" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, x["orderId"].GetString());
element.insert(CCAPI_EM_CLIENT_ORDER_ID, x["orderLinkId"].GetString());
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
{
auto it = x.FindMember("execFee");
if (it != x.MemberEnd() && !it->value.IsNull()) {
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(it->value.GetString()));
}
}
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
}
}
} else if (document.HasMember("type")) {
std::string type = document["type"].GetString();
if (type == "AUTH_RESP") {
bool success = document["success"].GetBool();
if (success) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
rj::Value args(rj::kArrayType);
for (const auto& field : subscription.getFieldSet()) {
std::string channelId;
if (field == CCAPI_EM_ORDER_UPDATE) {
channelId = "user.order.unifiedAccount";
} else if (field == CCAPI_EM_PRIVATE_TRADE) {
channelId = "user.execution.unifiedAccount";
}
args.PushBack(rj::Value(channelId.c_str(), allocator).Move(), allocator);
}
document.AddMember("args", args, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
this->send(hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
#endif
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
}
}
} else if (type == "COMMAND_RESP") {
bool success = document["success"].GetBool();
event.setType(Event::Type::SUBSCRIPTION_STATUS);
message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
}
} else if (document.HasMember("ret_code")) {
std::string ret_code = document["ret_code"].GetString();
if (ret_code != "0") {
event.setType(Event::Type::SUBSCRIPTION_STATUS);
message.setType(Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
}
}
event.setMessageList(messageList);
return event;
}
}; // namespace ccapi
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_DERIVATIVES_H_
@@ -14,19 +14,19 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_COINBASE_API_KEY;
this->apiSecretName = CCAPI_COINBASE_API_SECRET;
this->apiPassphraseName = CCAPI_COINBASE_API_PASSPHRASE;
@@ -293,7 +293,7 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -316,7 +316,7 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -358,14 +358,16 @@ class ExecutionManagementServiceCoinbase : public ExecutionManagementService {
element.insert(CCAPI_EM_ORDER_SIDE, makerSide == "buy" ? CCAPI_EM_ORDER_SIDE_SELL : CCAPI_EM_ORDER_SIDE_BUY);
element.insert(CCAPI_IS_MAKER, "0");
element.insert(CCAPI_EM_ORDER_ID, document["taker_order_id"].GetString());
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY,
UtilString::printDoubleScientific(std::stod(priceStr) * std::stod(sizeStr) * std::stod(document["taker_fee_rate"].GetString())));
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, Decimal(UtilString::printDoubleScientific(std::stod(priceStr) * std::stod(sizeStr) *
std::stod(document["taker_fee_rate"].GetString())))
.toString());
} else if (document.FindMember("maker_user_id") != document.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_SIDE, makerSide == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_IS_MAKER, "1");
element.insert(CCAPI_EM_ORDER_ID, document["maker_order_id"].GetString());
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY,
UtilString::printDoubleScientific(std::stod(priceStr) * std::stod(sizeStr) * std::stod(document["maker_fee_rate"].GetString())));
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, Decimal(UtilString::printDoubleScientific(std::stod(priceStr) * std::stod(sizeStr) *
std::stod(document["maker_fee_rate"].GetString())))
.toString());
}
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
elementList.emplace_back(std::move(element));
@@ -14,19 +14,19 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_CRYPTOCOM_API_KEY;
this->apiSecretName = CCAPI_CRYPTOCOM_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -331,7 +331,7 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
sendStringList.push_back(body);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -354,7 +354,7 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -486,7 +486,7 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
std::string id = document["id"].GetString();
std::string msg = R"({"id":)" + id + R"(,"method":"public/respond-heartbeat"})";
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, msg, ec);
@@ -551,7 +551,7 @@ class ExecutionManagementServiceCryptocom : public ExecutionManagementService {
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -14,19 +14,19 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->clientIdName = CCAPI_DERIBIT_CLIENT_ID;
this->clientSecretName = CCAPI_DERIBIT_CLIENT_SECRET;
this->setupCredential({this->clientIdName, this->clientSecretName});
@@ -45,7 +45,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onOpen(wspp::connection_hdl hdl) override {
ExecutionManagementService::onOpen(hdl);
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
@@ -315,15 +315,17 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("filled_amount");
auto it2 = x.FindMember("average_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))));
element.insert(
CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))))
.toString());
}
}
}
@@ -356,7 +358,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -379,7 +381,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -448,7 +450,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -533,7 +535,9 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
auto it2 = x.FindMember("average_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) *
(it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))))
.toString());
}
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
@@ -554,7 +558,7 @@ class ExecutionManagementServiceDeribit : public ExecutionManagementService {
document.Accept(writer);
std::string msg = stringBuffer.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, msg, ec);
@@ -15,19 +15,19 @@ class ExecutionManagementServiceErisx : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_ERISX_API_KEY;
this->apiSecretName = CCAPI_ERISX_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -192,7 +192,7 @@ class ExecutionManagementServiceErisx : public ExecutionManagementService {
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderID", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdID", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -221,15 +221,15 @@ class ExecutionManagementServiceErisx : public ExecutionManagementService {
}
void extractAccountInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("cumQty");
auto it2 = x.FindMember("avgPrice");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
}
}
@@ -19,7 +19,7 @@ class ExecutionManagementServiceFtx : public ExecutionManagementServiceFtxBase {
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -22,7 +22,7 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); }
@@ -213,7 +213,7 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -259,8 +259,8 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("filledSize");
@@ -324,7 +324,7 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
}
void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const TimePoint& timeReceived) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -376,7 +376,7 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService {
} else if (channel == "orders" && fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
message.setTime(timeReceived);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -19,7 +19,7 @@ class ExecutionManagementServiceFtxUs : public ExecutionManagementServiceFtxBase
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -14,19 +14,19 @@ class ExecutionManagementServiceGateio : public ExecutionManagementServiceGateio
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_GATEIO_API_KEY;
this->apiSecretName = CCAPI_GATEIO_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -14,7 +14,7 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl,
@@ -352,7 +352,7 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService {
}
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -375,7 +375,7 @@ class ExecutionManagementServiceGateioBase : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -14,19 +14,19 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY;
this->apiSecretName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -74,7 +74,8 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem
Element element;
element.insert(CCAPI_INSTRUMENT, x["contract"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["size"].GetString());
element.insert(CCAPI_EM_POSITION_COST, std::to_string(std::stod(x["entry_price"].GetString()) * std::stod(x["size"].GetString())));
element.insert(CCAPI_EM_POSITION_COST,
Decimal(UtilString::printDoubleScientific(std::stod(x["entry_price"].GetString()) * std::stod(x["size"].GetString()))).toString());
elementList.emplace_back(std::move(element));
}
} break;
@@ -105,13 +106,13 @@ class ExecutionManagementServiceGateioPerpetualFutures : public ExecutionManagem
if (credential.empty()) {
credential = that->credentialDefault;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection wsConnection(that->baseUrlWs + settle, "", {subscription}, credential);
that->prepareConnect(wsConnection);
#else
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> streamPtr(nullptr);
try {
streamPtr = that->createStream<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>>(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr, that->hostWs);
streamPtr = that->createWsStream(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr);
} catch (const beast::error_code& ec) {
CCAPI_LOGGER_TRACE("fail");
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "create stream", {subscription.getCorrelationId()});
@@ -14,19 +14,19 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_GEMINI_API_KEY;
this->apiSecretName = CCAPI_GEMINI_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -200,7 +200,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("order_id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -249,15 +249,15 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("executed_amount");
auto it2 = x.FindMember("avg_execution_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
}
{
@@ -273,7 +273,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
}
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void prepareConnect(WsConnection& wsConnection) override {
auto now = UtilTime::now();
auto subscription = wsConnection.subscriptionList.at(0);
@@ -315,16 +315,16 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
credential = this->credentialDefault;
}
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
wsConnectionPtr->url += "?heartbeat=true";
wsConnectionPtr->appendUrlPart("?heartbeat=true");
if (fieldSet == std::set<std::string>({CCAPI_EM_PRIVATE_TRADE})) {
wsConnectionPtr->url += "&eventTypeFilter=fill";
wsConnectionPtr->appendUrlPart("&eventTypeFilter=fill");
}
if (!instrumentSet.empty()) {
for (const auto& instrument : instrumentSet) {
wsConnectionPtr->url += "&symbolFilter=" + instrument;
wsConnectionPtr->appendUrlPart("&symbolFilter=" + instrument);
}
}
wsConnectionPtr->url += "&apiSessionFilter=" + apiKey;
wsConnectionPtr->appendUrlPart("&apiSessionFilter=" + apiKey);
wsConnectionPtr->headers.insert({"X-GEMINI-APIKEY", apiKey});
int64_t nonce = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
std::string payload = R"({"request":"/v1/order/events","nonce":)" + std::to_string(nonce) + "}";
@@ -336,7 +336,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
this->connect(wsConnectionPtr);
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -359,7 +359,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -419,7 +419,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
}
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("order_id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -436,7 +436,7 @@ class ExecutionManagementServiceGemini : public ExecutionManagementService {
auto it2 = x.FindMember("avg_execution_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
}
{
@@ -14,19 +14,19 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_HUOBI_API_KEY;
this->apiSecretName = CCAPI_HUOBI_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -235,7 +235,8 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now, "%FT%T");
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now);
timestamp.pop_back();
std::string signature;
std::string queryString;
std::map<std::string, std::string> queryParamMap;
@@ -265,7 +266,7 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
const TimePoint& timeReceived) override {
#else
@@ -308,7 +309,7 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -330,7 +331,7 @@ class ExecutionManagementServiceHuobi : public ExecutionManagementServiceHuobiBa
std::string toReplace("ping");
sendString.replace(sendString.find(toReplace), toReplace.length(), "pong");
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -51,7 +51,8 @@ class ExecutionManagementServiceHuobiBase : public ExecutionManagementService {
queryParamMap.insert(std::make_pair("AccessKeyId", apiKey));
queryParamMap.insert(std::make_pair("SignatureMethod", "HmacSHA256"));
queryParamMap.insert(std::make_pair("SignatureVersion", "2"));
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now, "%FT%T");
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now);
timestamp.pop_back();
queryParamMap.insert(std::make_pair("Timestamp", Url::urlEncode(timestamp)));
std::string signature;
this->createSignature(signature, queryString, methodString, this->hostRest, path, queryParamMap, credential);
@@ -111,7 +112,8 @@ class ExecutionManagementServiceHuobiBase : public ExecutionManagementService {
queryParamMap.insert(std::make_pair("AccessKeyId", apiKey));
queryParamMap.insert(std::make_pair("SignatureMethod", "HmacSHA256"));
queryParamMap.insert(std::make_pair("SignatureVersion", "2"));
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now, "%FT%T");
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now);
timestamp.pop_back();
queryParamMap.insert(std::make_pair("Timestamp", Url::urlEncode(timestamp)));
this->convertReqDetail(req, request, now, symbolId, credential, queryParamMap);
}
@@ -14,19 +14,19 @@ class ExecutionManagementServiceHuobiCoinSwap : public ExecutionManagementServic
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_HUOBI_COIN_SWAP_API_KEY;
this->apiSecretName = CCAPI_HUOBI_COIN_SWAP_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -13,7 +13,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
this->isDerivatives = true;
// this->convertNumberToStringInJsonRegex = std::regex("(\\[|,|\":)\\s?(-?\\d+\\.?\\d*[eE]?-?\\d*)");
this->needDecompressWebsocketMessage = true;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
ErrorCode ec = this->inflater.init(false, 31);
#else
this->inflater.setWindowBitsOverride(31);
@@ -142,7 +142,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("order_id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("direction", JsonDataType::STRING)},
@@ -202,22 +202,25 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("trade_volume");
auto it2 = x.FindMember("trade_avg_price");
if (it1 != x.MemberEnd() && it2 != x.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))));
element.insert(
CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * (it2->value.IsNull() ? 0 : std::stod(it2->value.GetString()))))
.toString());
}
}
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now, "%FT%T");
std::string timestamp = UtilTime::getISOTimestamp<std::chrono::seconds>(now);
timestamp.pop_back();
std::string signature;
std::string queryString;
std::map<std::string, std::string> queryParamMap;
@@ -244,7 +247,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage,
const TimePoint& timeReceived) override {
#else
@@ -279,7 +282,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -300,7 +303,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
std::string toReplace("ping");
sendString.replace(sendString.find(toReplace), toReplace.length(), "pong");
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -335,7 +338,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(document["ts"].GetString())));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("order_id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("client_order_id", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("direction", JsonDataType::STRING)},
@@ -352,7 +355,7 @@ class ExecutionManagementServiceHuobiDerivativesBase : public ExecutionManagemen
auto it2 = document.FindMember("trade_avg_price");
if (it1 != document.MemberEnd() && it2 != document.MemberEnd()) {
info.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
}
for (const auto& x : document["trade"].GetArray()) {
@@ -14,19 +14,19 @@ class ExecutionManagementServiceHuobiUsdtSwap : public ExecutionManagementServic
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_HUOBI_USDT_SWAP_API_KEY;
this->apiSecretName = CCAPI_HUOBI_USDT_SWAP_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -15,19 +15,19 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_KRAKEN_API_KEY;
this->apiSecretName = CCAPI_KRAKEN_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -46,7 +46,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl, "{\"reqid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec);
@@ -231,7 +231,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
auto it2 = itr->value.FindMember("price");
if (it1 != itr->value.MemberEnd() && it2 != itr->value.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
element.insert(CCAPI_EM_ORDER_ID, itr->name.GetString());
elementList.emplace_back(std::move(element));
@@ -271,7 +271,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void prepareConnect(WsConnection& wsConnection) override {
auto now = UtilTime::now();
auto hostPort = this->extractHostFromUrl(this->baseUrlRest);
@@ -324,7 +324,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#else
void prepareConnect(std::shared_ptr<WsConnection> wsConnectionPtr) override {
@@ -361,7 +361,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
if (document.HasMember("result") && document["result"].HasMember("token")) {
std::string token = document["result"]["token"].GetString();
wsConnectionPtr->url = that->baseUrlWs;
wsConnectionPtr->setUrl(that->baseUrlWs);
that->connect(wsConnectionPtr);
that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({
{"token", token},
@@ -374,7 +374,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
}
that->onFail_(wsConnectionPtr);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#endif
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
@@ -404,7 +404,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
}
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -427,7 +427,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -500,8 +500,9 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
auto it1 = itr->value.FindMember("vol_exec");
auto it2 = itr->value.FindMember("avg_price");
if (it1 != itr->value.MemberEnd() && it2 != itr->value.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
element.insert(
CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
element.insert(CCAPI_EM_ORDER_ID, itr->name.GetString());
elementList.emplace_back(std::move(element));
@@ -513,7 +514,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService {
auto it2 = itr->value.FindMember("avg_price");
if (it1 != itr->value.MemberEnd() && it2 != itr->value.MemberEnd()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
std::to_string(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString())));
Decimal(UtilString::printDoubleScientific(std::stod(it1->value.GetString()) * std::stod(it2->value.GetString()))).toString());
}
element.insert(CCAPI_EM_ORDER_ID, itr->name.GetString());
elementList.emplace_back(std::move(element));
@@ -15,19 +15,19 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_KRAKEN_FUTURES_API_KEY;
this->apiSecretName = CCAPI_KRAKEN_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -273,7 +273,7 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -296,7 +296,7 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -420,7 +420,7 @@ class ExecutionManagementServiceKrakenFutures : public ExecutionManagementServic
}
for (const auto& sendString : sendStringList) {
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -12,12 +12,12 @@ class ExecutionManagementServiceKucoin : public ExecutionManagementServiceKucoin
this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN;
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
// #ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -15,7 +15,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
protected:
#endif
bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"200000\"")); }
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onOpen(wspp::connection_hdl hdl) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
wsConnection.status = WsConnection::Status::OPEN;
@@ -69,7 +69,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#else
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override { wsConnectionPtr->status = WsConnection::Status::OPEN; }
@@ -105,7 +105,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
urlWebsocketBase += std::string(instanceServer["endpoint"].GetString());
urlWebsocketBase += "?token=";
urlWebsocketBase += std::string(document["data"]["token"].GetString());
wsConnectionPtr->url = urlWebsocketBase;
wsConnectionPtr->setUrl(urlWebsocketBase);
that->connect(wsConnectionPtr);
that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({
{"pingInterval", std::string(instanceServer["pingInterval"].GetString())},
@@ -118,7 +118,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
}
that->onFail_(wsConnectionPtr);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
#endif
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& req, const Request& request, std::string& methodString,
@@ -146,6 +146,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
preSignedText += req.base().at("KC-API-KEY").to_string();
auto signature = UtilAlgorithm::base64Encode(Hmac::hmac(Hmac::ShaVersion::SHA256, CCAPI_KUCOIN_API_PARTNER_PRIVATE_KEY, preSignedText));
req.set("KC-API-PARTNER-SIGN", signature);
req.set("KC-API-PARTNER-VERIFY", "true");
}
void signRequest(http::request<http::string_body>& req, const std::string& body, const std::map<std::string, std::string>& credential) {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
@@ -202,7 +203,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
req.set("KC-API-KEY", apiKey);
req.set("KC-API-TIMESTAMP", std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()));
// auto apiKeyVersion = mapGetWithDefault(credential, this->apiKeyVersionName);
req.set("KC-API-KEY-VERSION", "2");
req.set("KC-API-KEY-VERSION", "3");
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
this->signApiPassphrase(req, apiPassphrase, apiSecret);
@@ -332,7 +333,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("id", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -371,8 +372,8 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
elementList.emplace_back(std::move(element));
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it = x.FindMember("isActive");
@@ -407,7 +408,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -430,7 +431,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -483,7 +484,7 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(time);
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
std::map<std::string, std::pair<std::string, JsonDataType> > extractionFieldNameMap = {
std::map<std::string, std::pair<std::string, JsonDataType>> extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clientOid", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -519,16 +520,16 @@ class ExecutionManagementServiceKucoinBase : public ExecutionManagementService {
message.setElementList({element});
messageList.emplace_back(std::move(message));
} else if (type == "welcome") {
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingInterval"));
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingTimeout"));
if (this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <=
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) {
this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1;
if (this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <=
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) {
this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] =
this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
ExecutionManagementService::onOpen(hdl);
#else
ExecutionManagementService::onOpen(wsConnectionPtr);
@@ -12,12 +12,12 @@ class ExecutionManagementServiceKucoinFutures : public ExecutionManagementServic
this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES;
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
// #ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -15,19 +15,19 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_MEXC_API_KEY;
this->apiSecretName = CCAPI_MEXC_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -45,7 +45,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
protected:
#endif
// bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; }
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"method":"PING"})", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override {
@@ -226,7 +226,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void prepareConnect(WsConnection& wsConnection) override {
auto now = UtilTime::now();
auto hostPort = this->extractHostFromUrl(this->baseUrlRest);
@@ -274,7 +274,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
}
that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
void onOpen(wspp::connection_hdl hdl) override {
ExecutionManagementService::onOpen(hdl);
@@ -318,7 +318,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
[wsConnection, that_2 = that->shared_from_base<ExecutionManagementServiceMexc>()](const http::response<http::string_body>& res) {
CCAPI_LOGGER_DEBUG("ping listen key success");
},
that->sessionOptions.httpRequestTimeoutMilliSeconds);
that->sessionOptions.httpRequestTimeoutMilliseconds);
});
}
void onClose(wspp::connection_hdl hdl) override {
@@ -360,7 +360,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
document.Parse<rj::kParseNumbersAsStringsFlag>(body.c_str());
std::string listenKey = document["listenKey"].GetString();
std::string url = that->baseUrlWs + "?listenKey=" + listenKey;
wsConnectionPtr->url = url;
wsConnectionPtr->setUrl(url);
that->connect(wsConnectionPtr);
that->extraPropertyByConnectionIdMap[wsConnectionPtr->id].insert({
{"listenKey", listenKey},
@@ -372,7 +372,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
}
that->onFail_(wsConnectionPtr);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override {
ExecutionManagementService::onOpen(wsConnectionPtr);
@@ -416,7 +416,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
[wsConnectionPtr, that_2 = that->shared_from_base<ExecutionManagementServiceMexc>()](const http::response<http::string_body>& res) {
CCAPI_LOGGER_DEBUG("ping listen key success");
},
that->sessionOptions.httpRequestTimeoutMilliSeconds);
that->sessionOptions.httpRequestTimeoutMilliseconds);
});
this->pingListenKeyTimerMapByConnectionIdMap[wsConnectionPtr->id] = timerPtr;
}
@@ -454,7 +454,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
auto subscription = wsConnection.subscriptionList.at(0);
@@ -477,7 +477,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService {
}
}
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage,
const rj::Document& document, const TimePoint& timeReceived) {
#else
@@ -14,19 +14,19 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_MEXC_FUTURES_API_KEY;
this->apiSecretName = CCAPI_MEXC_FUTURES_API_SECRET;
this->setupCredential({this->apiKeyName, this->apiSecretName});
@@ -45,7 +45,7 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"method":"ping"})", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override {
@@ -319,8 +319,8 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService
// CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
// }
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
// ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
// {
// auto it1 = x.FindMember("accFillSz");
@@ -329,7 +329,8 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService
// auto it1Str = std::string(it1->value.GetString());
// auto it2Str = std::string(it2->value.GetString());
// if (!it1Str.empty() && !it2Str.empty()) {
// element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
// element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, Decimal(UtilString::printDoubleScientific(std::stod(it1Str) *
// std::stod(it2Str))).toString());
// }
// }
// }
@@ -364,7 +365,7 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService
}
void onTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView,
const TimePoint& timeReceived) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -401,7 +402,7 @@ class ExecutionManagementServiceMexcFutures : public ExecutionManagementService
// document.Accept(writerSubscribe);
// std::string sendString = stringBufferSubscribe.GetString();
// ErrorCode ec;
// #ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -3,6 +3,7 @@
#ifdef CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
#ifdef CCAPI_ENABLE_EXCHANGE_OKX
#include "ccapi_cpp/service/ccapi_execution_management_service.h"
namespace ccapi {
class ExecutionManagementServiceOkx : public ExecutionManagementService {
public:
@@ -14,19 +15,19 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_OKX_API_KEY;
this->apiSecretName = CCAPI_OKX_API_SECRET;
this->apiPassphraseName = CCAPI_OKX_API_PASSPHRASE;
@@ -39,17 +40,19 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
this->getAccountBalancesTarget = "/api/v5/account/balance";
this->getAccountPositionsTarget = "/api/v5/account/positions";
}
virtual ~ExecutionManagementServiceOkx() {}
#ifndef CCAPI_EXPOSE_INTERNAL
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); }
#endif
bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); }
void signReqeustForRestGenericPrivateRequest(http::request<http::string_body>& req, const Request& request, std::string& methodString,
std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
@@ -68,6 +71,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
}
headerString += "OK-ACCESS-SIGN:" + signature;
}
void signRequest(http::request<http::string_body>& req, const std::string& body, const std::map<std::string, std::string>& credential) {
auto apiSecret = mapGetWithDefault(credential, this->apiSecretName);
auto preSignedText = req.base().at("OK-ACCESS-TIMESTAMP").to_string();
@@ -79,6 +83,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
req.body() = body;
req.prepare_payload();
}
void appendParam(Request::Operation operation, rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {
{CCAPI_EM_ORDER_SIDE, "side"},
@@ -100,6 +105,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
rjValue.AddMember("tag", CCAPI_OKX_API_BROKER_CODE, allocator);
}
}
void appendParam(std::string& queryString, const std::map<std::string, std::string>& param,
const std::map<std::string, std::string> standardizationMap = {}) {
for (const auto& kv : param) {
@@ -109,21 +115,24 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
queryString += "&";
}
}
void appendSymbolId(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::string& symbolId) {
rjValue.AddMember("instId", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
void appendSymbolId(std::string& queryString, const std::string& symbolId) {
queryString += "instId=";
queryString += Url::urlEncode(symbolId);
queryString += "&";
}
void convertRequestForRest(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
req.set(beast::http::field::content_type, "application/json");
auto apiKey = mapGetWithDefault(credential, this->apiKeyName);
req.set("OK-ACCESS-KEY", apiKey);
std::string timeStr = UtilTime::getISOTimestamp(now);
req.set("OK-ACCESS-TIMESTAMP", timeStr.substr(0, timeStr.length() - 7) + "Z");
std::string timeStr = UtilTime::getISOTimestamp<std::chrono::milliseconds>(now);
req.set("OK-ACCESS-TIMESTAMP", timeStr);
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
req.set("OK-ACCESS-PASSPHRASE", apiPassphrase);
auto apiXSimulatedTrading = mapGetWithDefault(credential, this->apiXSimulatedTradingName);
@@ -226,6 +235,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void convertRequestForWebsocket(rj::Document& document, rj::Document::AllocatorType& allocator, const WsConnection& wsConnection, const Request& request,
int wsRequestId, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
@@ -269,12 +279,14 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
this->convertRequestForWebsocketCustom(document, allocator, wsConnection, request, wsRequestId, now, symbolId, credential);
}
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
this->extractOrderInfoFromRequest(elementList, document);
}
void extractOrderInfoFromRequest(std::vector<Element>& elementList, const rj::Document& document) {
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
@@ -296,6 +308,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
}
}
}
void extractAccountInfoFromRequest(std::vector<Element>& elementList, const Request& request, const Request::Operation operation,
const rj::Document& document) override {
switch (request.getOperation()) {
@@ -305,7 +318,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
element.insert(CCAPI_EM_ASSET, x["ccy"].GetString());
std::string availEq = x["availEq"].GetString();
element.insert(CCAPI_EM_QUANTITY_AVAILABLE_FOR_TRADING, availEq.empty() ? x["availBal"].GetString() : availEq);
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["eq"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, x["cashBal"].GetString());
elementList.emplace_back(std::move(element));
}
} break;
@@ -326,8 +339,9 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
void extractOrderInfo(Element& element, const rj::Value& x,
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap) override {
void extractOrderInfo(Element& element, const rj::Value& x, const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap,
const std::map<std::string, std::function<std::string(const std::string&)>> conversionMap = {}) override {
ExecutionManagementService::extractOrderInfo(element, x, extractionFieldNameMap);
{
auto it1 = x.FindMember("accFillSz");
@@ -336,11 +350,13 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
auto it1Str = std::string(it1->value.GetString());
auto it2Str = std::string(it2->value.GetString());
if (!it1Str.empty() && !it2Str.empty()) {
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str)));
element.insert(CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY,
Decimal(UtilString::printDoubleScientific(std::stod(it1Str) * std::stod(it2Str))).toString());
}
}
}
}
std::vector<std::string> createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now,
const std::map<std::string, std::string>& credential) override {
std::vector<std::string> sendStringList;
@@ -369,15 +385,16 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
sendStringList.push_back(sendString);
return sendStringList;
}
void onTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
const WsConnection& wsConnection, const Subscription& subscription, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
std::string textMessage(textMessageView);
#endif
@@ -394,15 +411,40 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
rj::Value args(rj::kArrayType);
const auto& fieldSet = subscription.getFieldSet();
const auto& instrumentSet = subscription.getInstrumentSet();
std::string channel;
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
channel = "orders";
if (instrumentSet.empty()) {
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("orders").Move(), allocator);
arg.AddMember("instType", rj::Value("ANY").Move(), allocator);
args.PushBack(arg, allocator);
}
if (fieldSet.find(CCAPI_EM_POSITION_UPDATE) != fieldSet.end()) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("positions").Move(), allocator);
arg.AddMember("instType", rj::Value("ANY").Move(), allocator);
args.PushBack(arg, allocator);
}
} else {
for (const auto& instrument : instrumentSet) {
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end() || fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("orders").Move(), allocator);
arg.AddMember("instId", rj::Value(instrument.c_str(), allocator).Move(), allocator);
arg.AddMember("instType", rj::Value("ANY").Move(), allocator);
args.PushBack(arg, allocator);
}
if (fieldSet.find(CCAPI_EM_POSITION_UPDATE) != fieldSet.end()) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value("positions").Move(), allocator);
arg.AddMember("instId", rj::Value(instrument.c_str(), allocator).Move(), allocator);
arg.AddMember("instType", rj::Value("ANY").Move(), allocator);
args.PushBack(arg, allocator);
}
}
}
for (const auto& instrument : instrumentSet) {
if (fieldSet.find(CCAPI_EM_BALANCE_UPDATE) != fieldSet.end()) {
rj::Value arg(rj::kObjectType);
arg.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator);
arg.AddMember("instId", rj::Value(instrument.c_str(), allocator).Move(), allocator);
arg.AddMember("instType", rj::Value("ANY").Move(), allocator);
arg.AddMember("channel", rj::Value("balance_and_position").Move(), allocator);
args.PushBack(arg, allocator);
}
document.AddMember("args", args, allocator);
@@ -411,8 +453,8 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
document.Accept(writerSubscribe);
std::string sendString = stringBufferSubscribe.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -431,6 +473,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
}
}
}
Event createEvent(const Subscription& subscription, const std::string& textMessage, const rj::Document& document, const std::string& eventStr,
const TimePoint& timeReceived) {
Event event;
@@ -475,64 +518,98 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
const rj::Value& data = document["data"];
std::string channel = std::string(arg["channel"].GetString());
event.setType(Event::Type::SUBSCRIPTION_DATA);
std::string instrument = arg["instId"].GetString();
if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) {
if (channel == "orders") {
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
for (const auto& x : data.GetArray()) {
std::string tradeId = x["tradeId"].GetString();
if (!tradeId.empty()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_TRADE_ID, tradeId);
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["fillPx"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["fillSz"].GetString()));
element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_EM_POSITION_SIDE, std::string(x["posSide"].GetString()));
element.insert(CCAPI_IS_MAKER, std::string(x["execType"].GetString()) == "M" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["ordId"].GetString()));
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdId"].GetString()));
element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fillFee"].GetString()));
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCcy"].GetString()));
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
for (const auto& x : data.GetArray()) {
if (channel == "orders") {
if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) {
for (const auto& x : data.GetArray()) {
std::string tradeId = x["tradeId"].GetString();
if (!tradeId.empty()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType> >& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("px", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("sz", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accFillSz", JsonDataType::STRING)},
{CCAPI_EM_ORDER_AVERAGE_FILLED_PRICE, std::make_pair("avgPx", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)},
};
Element info;
this->extractOrderInfo(info, x, extractionFieldNameMap);
info.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument);
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["fillTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE);
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
Element element;
element.insert(CCAPI_TRADE_ID, tradeId);
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["fillPx"].GetString()));
element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["fillSz"].GetString()));
element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL);
element.insert(CCAPI_EM_POSITION_SIDE, std::string(x["posSide"].GetString()));
element.insert(CCAPI_IS_MAKER, std::string(x["execType"].GetString()) == "M" ? "1" : "0");
element.insert(CCAPI_EM_ORDER_ID, std::string(x["ordId"].GetString()));
element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["clOrdId"].GetString()));
element.insert(CCAPI_EM_ORDER_INSTRUMENT, x["instId"].GetString());
element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(x["fillFee"].GetString()));
element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(x["fillFeeCcy"].GetString()));
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) {
for (const auto& x : data.GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(UtilTime::makeTimePointFromMilliseconds(std::stoll(std::string(x["uTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE);
const std::map<std::string, std::pair<std::string, JsonDataType>>& extractionFieldNameMap = {
{CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)},
{CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)},
{CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)},
{CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("px", JsonDataType::STRING)},
{CCAPI_EM_ORDER_QUANTITY, std::make_pair("sz", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("accFillSz", JsonDataType::STRING)},
{CCAPI_EM_ORDER_AVERAGE_FILLED_PRICE, std::make_pair("avgPx", JsonDataType::STRING)},
{CCAPI_EM_ORDER_STATUS, std::make_pair("state", JsonDataType::STRING)},
{CCAPI_EM_ORDER_CUMULATIVE_FEE_QUANTITY, std::make_pair("fee", JsonDataType::STRING)},
{CCAPI_EM_ORDER_FEE_ASSET, std::make_pair("feeCcy", JsonDataType::STRING)},
{CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("instId", JsonDataType::STRING)},
};
Element info;
this->extractOrderInfo(info, x, extractionFieldNameMap);
std::vector<Element> elementList;
elementList.emplace_back(std::move(info));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
} else if (channel == "balance_and_position") {
for (const auto& x : data.GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["pTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_BALANCE_UPDATE);
std::vector<Element> elementList;
for (const auto& y : x["balData"].GetArray()) {
Element element;
element.insert(CCAPI_EM_ASSET, y["ccy"].GetString());
element.insert(CCAPI_EM_QUANTITY_TOTAL, y["cashBal"].GetString());
elementList.emplace_back(std::move(element));
}
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
} else if (channel == "positions") {
for (const auto& x : data.GetArray()) {
Message message;
message.setTimeReceived(timeReceived);
message.setCorrelationIdList({subscription.getCorrelationId()});
message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["uTime"].GetString()))));
message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_POSITION_UPDATE);
std::vector<Element> elementList;
Element element;
element.insert(CCAPI_INSTRUMENT, x["instId"].GetString());
element.insert(CCAPI_EM_POSITION_SIDE, x["posSide"].GetString());
element.insert(CCAPI_EM_POSITION_QUANTITY, x["pos"].GetString());
element.insert(CCAPI_EM_POSITION_ENTRY_PRICE, x["avgPx"].GetString());
element.insert(CCAPI_EM_UNREALIZED_PNL, x["upl"].GetString());
elementList.emplace_back(std::move(element));
message.setElementList(elementList);
messageList.emplace_back(std::move(message));
}
}
}
} else if (eventStr == "subscribe") {
@@ -553,6 +630,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService {
event.setMessageList(messageList);
return event;
}
std::string apiPassphraseName;
std::string apiXSimulatedTradingName;
};
@@ -11,11 +11,11 @@
#include "hffix.hpp"
namespace hff = hffix;
namespace ccapi {
template <class T>
/**
* Defines a service which provides access to exchange API and normalizes them. This is a base class that implements generic functionalities for dealing with
* exchange FIX APIs. The Session object is responsible for routing requests and subscriptions to the desired concrete service.
*/
template <class T>
class FixService : public Service {
public:
FixService(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
@@ -105,7 +105,7 @@ class FixService : public Service {
});
this->connectRetryOnFailTimerByConnectionIdMap[fixConnectionPtr->id] = timerPtr;
}
std::shared_ptr<T> createStreamFix(std::shared_ptr<net::io_context> iocPtr, std::shared_ptr<net::ssl::context> ctxPtr, const std::string& host);
std::shared_ptr<T> createStreamFix(net::io_context* iocPtr, net::ssl::context* ctxPtr, const std::string& host);
void connect(Subscription& subscription) {
std::string aHostFix = this->hostFix;
std::string aPortFix = this->portFix;
@@ -454,11 +454,11 @@ class FixService : public Service {
std::function<void(std::shared_ptr<FixConnection<T>>)> pingMethod, bool pingNow = false) {
CCAPI_LOGGER_FUNCTION_ENTER;
CCAPI_LOGGER_TRACE("method = " + pingPongMethodToString(method));
auto pingIntervalMilliSeconds = this->pingIntervalMilliSecondsByMethodMap[method];
auto pongTimeoutMilliSeconds = this->pongTimeoutMilliSecondsByMethodMap[method];
CCAPI_LOGGER_TRACE("pingIntervalMilliSeconds = " + toString(pingIntervalMilliSeconds));
CCAPI_LOGGER_TRACE("pongTimeoutMilliSeconds = " + toString(pongTimeoutMilliSeconds));
if (pingIntervalMilliSeconds <= pongTimeoutMilliSeconds) {
auto pingIntervalMilliseconds = this->pingIntervalMillisecondsByMethodMap[method];
auto pongTimeoutMilliseconds = this->pongTimeoutMillisecondsByMethodMap[method];
CCAPI_LOGGER_TRACE("pingIntervalMilliseconds = " + toString(pingIntervalMilliseconds));
CCAPI_LOGGER_TRACE("pongTimeoutMilliseconds = " + toString(pongTimeoutMilliseconds));
if (pingIntervalMilliseconds <= pongTimeoutMilliseconds) {
return;
}
if (fixConnectionPtr->status == FixConnection<T>::Status::OPEN) {
@@ -471,8 +471,8 @@ class FixService : public Service {
this->pingTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method)->cancel();
}
TimerPtr timerPtr(
new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliSeconds - pongTimeoutMilliSeconds)));
timerPtr->async_wait([fixConnectionPtr, that = shared_from_base<FixService>(), pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliseconds - pongTimeoutMilliseconds)));
timerPtr->async_wait([fixConnectionPtr, that = shared_from_base<FixService>(), pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) {
if (that->fixConnectionPtrByIdMap.find(fixConnectionPtr->id) != that->fixConnectionPtrByIdMap.end()) {
if (ec) {
CCAPI_LOGGER_ERROR("fixConnectionPtr = " + toString(*fixConnectionPtr) + ", ping timer error: " + ec.message());
@@ -484,7 +484,7 @@ class FixService : public Service {
if (ec) {
that->onError(Event::Type::FIX_STATUS, Message::Type::GENERIC_ERROR, ec, "ping");
}
if (pongTimeoutMilliSeconds <= 0) {
if (pongTimeoutMilliseconds <= 0) {
return;
}
if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(fixConnectionPtr->id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() &&
@@ -492,8 +492,8 @@ class FixService : public Service {
that->pongTimeOutTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).end()) {
that->pongTimeOutTimerByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method)->cancel();
}
TimerPtr timerPtr(new boost::asio::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliSeconds)));
timerPtr->async_wait([fixConnectionPtr, that, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) {
TimerPtr timerPtr(new boost::asio::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliseconds)));
timerPtr->async_wait([fixConnectionPtr, that, pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) {
if (that->fixConnectionPtrByIdMap.find(fixConnectionPtr->id) != that->fixConnectionPtrByIdMap.end()) {
if (ec) {
CCAPI_LOGGER_ERROR("fixConnectionPtr = " + toString(*fixConnectionPtr) + ", pong timeout timer error: " + ec.message());
@@ -506,7 +506,7 @@ class FixService : public Service {
that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).end() &&
std::chrono::duration_cast<std::chrono::milliseconds>(now -
that->lastPongTpByMethodByConnectionIdMap.at(fixConnectionPtr->id).at(method))
.count() >= pongTimeoutMilliSeconds) {
.count() >= pongTimeoutMilliseconds) {
auto thisFixConnectionPtr = fixConnectionPtr;
that->onFail(fixConnectionPtr, "pong timeout");
} else {
@@ -558,8 +558,9 @@ class FixService : public Service {
std::string targetCompID;
};
template <>
inline std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> FixService<beast::ssl_stream<beast::tcp_stream>>::createStreamFix(
std::shared_ptr<net::io_context> iocPtr, std::shared_ptr<net::ssl::context> ctxPtr, const std::string& host) {
inline std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> FixService<beast::ssl_stream<beast::tcp_stream>>::createStreamFix(net::io_context* iocPtr,
net::ssl::context* ctxPtr,
const std::string& host) {
std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> streamPtr(new beast::ssl_stream<beast::tcp_stream>(*iocPtr, *ctxPtr));
// Set SNI Hostname (many hosts need this to handshake successfully)
if (!SSL_set_tlsext_host_name(streamPtr->native_handle(), host.c_str())) {
@@ -570,8 +571,8 @@ inline std::shared_ptr<beast::ssl_stream<beast::tcp_stream>> FixService<beast::s
return streamPtr;
}
template <>
inline std::shared_ptr<beast::tcp_stream> FixService<beast::tcp_stream>::createStreamFix(std::shared_ptr<net::io_context> iocPtr,
std::shared_ptr<net::ssl::context> ctxPtr, const std::string& host) {
inline std::shared_ptr<beast::tcp_stream> FixService<beast::tcp_stream>::createStreamFix(net::io_context* iocPtr, net::ssl::context* ctxPtr,
const std::string& host) {
std::shared_ptr<beast::tcp_stream> streamPtr(new beast::tcp_stream(*iocPtr));
return streamPtr;
}
@@ -44,7 +44,7 @@ class FixServiceCoinbase : public FixService<beast::ssl_stream<beast::tcp_stream
auto msgType = "A";
param.push_back({hff::tag::MsgType, msgType});
param.push_back({hff::tag::EncryptMethod, "0"});
param.push_back({hff::tag::HeartBtInt, std::to_string(this->sessionOptions.heartbeatFixIntervalMilliSeconds / 1000)});
param.push_back({hff::tag::HeartBtInt, std::to_string(this->sessionOptions.heartbeatFixIntervalMilliseconds / 1000)});
auto credential = this->credentialByConnectionIdMap[connectionId];
auto apiPassphrase = mapGetWithDefault(credential, this->apiPassphraseName);
param.push_back({hff::tag::Password, apiPassphrase});
@@ -41,7 +41,7 @@ class FixServiceGemini : public FixService<beast::tcp_stream> {
param.push_back({hff::tag::MsgType, msgType});
param.push_back({hff::tag::ResetSeqNumFlag, "Y"});
param.push_back({hff::tag::EncryptMethod, "0"});
param.push_back({hff::tag::HeartBtInt, std::to_string(this->sessionOptions.heartbeatFixIntervalMilliSeconds / 1000)});
param.push_back({hff::tag::HeartBtInt, std::to_string(this->sessionOptions.heartbeatFixIntervalMilliseconds / 1000)});
for (const auto& x : logonOptionMap) {
param.push_back({x.first, x.second});
}
@@ -17,12 +17,17 @@ namespace ccapi {
class MarketDataService : public Service {
public:
MarketDataService(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: Service(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
CCAPI_LOGGER_FUNCTION_ENTER;
this->requestOperationToMessageTypeMap = {
{Request::Operation::GET_RECENT_TRADES, Message::Type::GET_RECENT_TRADES},
{Request::Operation::GET_HISTORICAL_TRADES, Message::Type::GET_HISTORICAL_TRADES},
{Request::Operation::GET_RECENT_AGG_TRADES, Message::Type::GET_RECENT_AGG_TRADES},
{Request::Operation::GET_HISTORICAL_AGG_TRADES, Message::Type::GET_HISTORICAL_AGG_TRADES},
{Request::Operation::GET_RECENT_CANDLESTICKS, Message::Type::GET_RECENT_CANDLESTICKS},
{Request::Operation::GET_HISTORICAL_CANDLESTICKS, Message::Type::GET_HISTORICAL_CANDLESTICKS},
{Request::Operation::GET_MARKET_DEPTH, Message::Type::GET_MARKET_DEPTH},
{Request::Operation::GET_INSTRUMENT, Message::Type::GET_INSTRUMENT},
{Request::Operation::GET_INSTRUMENTS, Message::Type::GET_INSTRUMENTS},
};
@@ -42,7 +47,7 @@ class MarketDataService : public Service {
}
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// subscriptions are grouped and each group creates a unique websocket connection
void subscribe(std::vector<Subscription>& subscriptionList) override {
CCAPI_LOGGER_FUNCTION_ENTER;
@@ -131,13 +136,12 @@ class MarketDataService : public Service {
}
std::shared_ptr<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>> streamPtr(nullptr);
try {
streamPtr = that->createStream<beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>>(
that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr, that->hostWs);
streamPtr = that->createWsStream(that->serviceContextPtr->ioContextPtr, that->serviceContextPtr->sslContextPtr);
} catch (const beast::error_code& ec) {
CCAPI_LOGGER_TRACE("fail");
std::vector<std::string> correlationIdList;
correlationIdList.reserve(subscriptionListGivenInstrumentGroup.size());
std::transform(subscriptionListGivenInstrumentGroup.cbegin(), subscriptionListGivenInstrumentGroup.cend(), correlationIdList.begin(),
std::transform(subscriptionListGivenInstrumentGroup.cbegin(), subscriptionListGivenInstrumentGroup.cend(), std::back_inserter(correlationIdList),
[](Subscription subscription) { return subscription.getCorrelationId(); });
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "create stream", correlationIdList);
return;
@@ -156,7 +160,7 @@ class MarketDataService : public Service {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
typedef wspp::lib::error_code ErrorCode;
typedef wspp::lib::function<void(ErrorCode const&)> TimerHandler;
#else
@@ -171,7 +175,12 @@ class MarketDataService : public Service {
return groups;
}
virtual std::string getInstrumentGroup(const Subscription& subscription) {
return this->baseUrlWs + "|" + subscription.getField() + "|" + subscription.getSerializedOptions() + "|" + subscription.getSerializedCredential();
const auto& field = subscription.getField();
if (field == CCAPI_GENERIC_PUBLIC_SUBSCRIPTION) {
return this->baseUrlWs + "|" + subscription.getField() + "|" + subscription.getCorrelationId() + "|" + subscription.getSerializedCredential();
} else {
return this->baseUrlWs + "|" + subscription.getField() + "|" + subscription.getSerializedOptions() + "|" + subscription.getSerializedCredential();
}
}
void prepareSubscription(const WsConnection& wsConnection, const Subscription& subscription) {
auto instrument = subscription.getInstrument();
@@ -196,7 +205,7 @@ class MarketDataService : public Service {
CCAPI_LOGGER_TRACE("this->correlationIdListByConnectionIdChannelSymbolIdMap = " + toString(this->correlationIdListByConnectionIdChannelIdSymbolIdMap));
CCAPI_LOGGER_FUNCTION_EXIT;
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void processMarketDataMessageList(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
Event& event, std::vector<MarketDataMessage>& marketDataMessageList) {
CCAPI_LOGGER_TRACE("marketDataMessageList = " + toString(marketDataMessageList));
@@ -205,9 +214,9 @@ class MarketDataService : public Service {
if (marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE) {
if (this->sessionOptions.warnLateEventMaxMilliSeconds > 0 &&
if (this->sessionOptions.warnLateEventMaxMilliseconds > 0 &&
std::chrono::duration_cast<std::chrono::milliseconds>(timeReceived - marketDataMessage.tp).count() >
this->sessionOptions.warnLateEventMaxMilliSeconds &&
this->sessionOptions.warnLateEventMaxMilliseconds &&
marketDataMessage.recapType == MarketDataMessage::RecapType::NONE) {
CCAPI_LOGGER_WARN("late websocket message: timeReceived = " + toString(timeReceived) + ", marketDataMessage.tp = " + toString(marketDataMessage.tp) +
", wsConnection = " + toString(wsConnection));
@@ -308,7 +317,7 @@ class MarketDataService : public Service {
event.setMessageList({message});
this->eventHandler(event, nullptr);
}
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived);
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, hdl, textMessage, timeReceived, false);
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void onIncorrectStatesFound(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
@@ -391,7 +400,7 @@ class MarketDataService : public Service {
void onClose(wspp::connection_hdl hdl) override {
CCAPI_LOGGER_FUNCTION_ENTER;
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.erase(wsConnection.id);
this->exchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
this->instrumentGroupByWsConnectionIdMap.erase(wsConnection.id);
this->correlationIdByConnectionIdMap.erase(wsConnection.id);
@@ -409,7 +418,7 @@ class MarketDataService : public Service {
for (const auto& sendString : sendStringList) {
CCAPI_LOGGER_INFO("sendString = " + sendString);
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -441,7 +450,7 @@ class MarketDataService : public Service {
for (const auto& sendString : sendStringList) {
CCAPI_LOGGER_INFO("sendString = " + sendString);
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -460,27 +469,35 @@ class MarketDataService : public Service {
for (auto& marketDataMessage : marketDataMessageList) {
if (marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE) {
if (this->sessionOptions.warnLateEventMaxMilliSeconds > 0 &&
std::chrono::duration_cast<std::chrono::milliseconds>(timeReceived - marketDataMessage.tp).count() >
this->sessionOptions.warnLateEventMaxMilliSeconds &&
marketDataMessage.recapType == MarketDataMessage::RecapType::NONE) {
CCAPI_LOGGER_WARN("late websocket message: timeReceived = " + toString(timeReceived) + ", marketDataMessage.tp = " + toString(marketDataMessage.tp) +
", wsConnection = " + toString(wsConnection));
}
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK) {
// if (this->sessionOptions.warnLateEventMaxMilliseconds > 0 &&
// std::chrono::duration_cast<std::chrono::milliseconds>(timeReceived - marketDataMessage.tp).count() >
// this->sessionOptions.warnLateEventMaxMilliseconds &&
// marketDataMessage.recapType == MarketDataMessage::RecapType::NONE) {
// CCAPI_LOGGER_WARN("late websocket message: timeReceived = " + toString(timeReceived) + ", marketDataMessage.tp = " + toString(marketDataMessage.tp)
// +
// ", wsConnection = " + toString(wsConnection));
// }
std::string& exchangeSubscriptionId = marketDataMessage.exchangeSubscriptionId;
CCAPI_LOGGER_TRACE("this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap = " +
toString(this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap));
CCAPI_LOGGER_TRACE("this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id) = " +
toString(this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id)));
CCAPI_LOGGER_TRACE("exchangeSubscriptionId = " + exchangeSubscriptionId);
std::string& channelId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
CCAPI_LOGGER_TRACE("channelId = " + toString(channelId));
std::string& symbolId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID);
CCAPI_LOGGER_TRACE("symbolId = " + toString(symbolId));
CCAPI_LOGGER_TRACE("this->fieldByConnectionIdChannelIdSymbolIdMap = " + toString(this->fieldByConnectionIdChannelIdSymbolIdMap));
CCAPI_LOGGER_TRACE("this->fieldByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id) = " +
toString(this->fieldByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)));
auto& field = this->fieldByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
CCAPI_LOGGER_TRACE("this->optionMapByConnectionIdChannelIdSymbolIdMap = " + toString(this->optionMapByConnectionIdChannelIdSymbolIdMap));
CCAPI_LOGGER_TRACE("wsConnection = " + toString(wsConnection));
CCAPI_LOGGER_TRACE("channelId = " + toString(channelId));
CCAPI_LOGGER_TRACE("symbolId = " + toString(symbolId));
auto& optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
CCAPI_LOGGER_TRACE("optionMap = " + toString(optionMap));
auto& correlationIdList = this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
@@ -532,6 +549,11 @@ class MarketDataService : public Service {
this->processTrade(wsConnection, channelId, symbolId, event, marketDataMessage.tp, timeReceived, marketDataMessage.data, field, optionMap,
correlationIdList, isSolicited);
}
if (marketDataMessage.data.find(MarketDataMessage::DataType::CANDLESTICK) != marketDataMessage.data.end()) {
bool isSolicited = marketDataMessage.recapType == MarketDataMessage::RecapType::SOLICITED;
this->processExchangeProvidedCandlestick(wsConnection, channelId, symbolId, event, marketDataMessage.tp, timeReceived, marketDataMessage.data, field,
optionMap, correlationIdList, isSolicited);
}
} else {
CCAPI_LOGGER_WARN("websocket event type is unknown for " + toString(marketDataMessage));
CCAPI_LOGGER_WARN("textMessage is " + std::string(textMessage));
@@ -563,13 +585,12 @@ class MarketDataService : public Service {
event.setMessageList({message});
this->eventHandler(event, nullptr);
}
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, wsConnectionPtr, timeReceived);
this->onPongByMethod(PingPongMethod::WEBSOCKET_APPLICATION_LEVEL, wsConnectionPtr, timeReceived, false);
CCAPI_LOGGER_FUNCTION_EXIT;
}
virtual void onIncorrectStatesFound(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived,
const std::string& exchangeSubscriptionId, std::string const& reason) {
WsConnection& wsConnection = *wsConnectionPtr;
std::string errorMessage = "incorrect states found: connection = " + toString(wsConnection) + ", textMessage = " + std::string(textMessageView) +
std::string errorMessage = "incorrect states found: connection = " + toString(*wsConnectionPtr) + ", textMessage = " + std::string(textMessageView) +
", timeReceived = " + UtilTime::getISOTimestamp(timeReceived) + ", exchangeSubscriptionId = " + exchangeSubscriptionId +
", reason = " + reason;
CCAPI_LOGGER_ERROR(errorMessage);
@@ -577,9 +598,17 @@ class MarketDataService : public Service {
this->close(wsConnectionPtr, beast::websocket::close_code::normal,
beast::websocket::close_reason(beast::websocket::close_code::normal, "incorrect states found: " + reason), ec);
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, "shutdown");
std::string& channelId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnectionPtr->id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
std::string& symbolId =
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnectionPtr->id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID);
CCAPI_LOGGER_TRACE("channelId = " + toString(channelId));
CCAPI_LOGGER_TRACE("symbolId = " + toString(symbolId));
auto& correlationIdList = this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnectionPtr->id).at(channelId).at(symbolId);
CCAPI_LOGGER_TRACE("correlationIdList = " + toString(correlationIdList));
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, "shutdown", correlationIdList);
}
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false;
this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnectionPtr->id] = false;
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::INCORRECT_STATE_FOUND, errorMessage);
}
void connect(std::shared_ptr<WsConnection> wsConnectionPtr) override {
@@ -651,7 +680,7 @@ class MarketDataService : public Service {
virtual void onClose(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode ec) override {
CCAPI_LOGGER_FUNCTION_ENTER;
WsConnection& wsConnection = *wsConnectionPtr;
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.erase(wsConnection.id);
this->exchangeJsonPayloadIdByConnectionIdMap.erase(wsConnection.id);
this->instrumentGroupByWsConnectionIdMap.erase(wsConnection.id);
this->correlationIdByConnectionIdMap.erase(wsConnection.id);
@@ -682,10 +711,10 @@ class MarketDataService : public Service {
for (const auto& subscription : wsConnection.subscriptionList) {
auto instrument = subscription.getInstrument();
this->subscriptionStatusByInstrumentGroupInstrumentMap[instrumentGroup][instrument] = Subscription::Status::SUBSCRIBING;
if (subscription.getRawOptions().empty()) {
this->prepareSubscription(wsConnection, subscription);
} else {
if (subscription.getField() == CCAPI_GENERIC_PUBLIC_SUBSCRIPTION) {
this->correlationIdByConnectionIdMap.insert({wsConnection.id, subscription.getCorrelationId()});
} else {
this->prepareSubscription(wsConnection, subscription);
}
}
CCAPI_LOGGER_INFO("about to subscribe to exchange");
@@ -766,6 +795,45 @@ class MarketDataService : public Service {
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
void updateElementListWithOrderBookSnapshot(const std::string& field, int maxMarketDepth, const std::map<Decimal, std::string>& snapshotBid,
const std::map<Decimal, std::string>& snapshotAsk, std::vector<Element>& elementList) {
CCAPI_LOGGER_FUNCTION_ENTER;
if (field == CCAPI_MARKET_DEPTH) {
int bidIndex = 0;
for (auto iter = snapshotBid.rbegin(); iter != snapshotBid.rend(); iter++) {
if (bidIndex < maxMarketDepth) {
Element element;
element.insert(CCAPI_BEST_BID_N_PRICE, iter->first.toString());
element.insert(CCAPI_BEST_BID_N_SIZE, iter->second);
elementList.emplace_back(std::move(element));
}
++bidIndex;
}
if (snapshotBid.empty()) {
Element element;
element.insert(CCAPI_BEST_BID_N_PRICE, CCAPI_BEST_BID_N_PRICE_EMPTY);
element.insert(CCAPI_BEST_BID_N_SIZE, CCAPI_BEST_BID_N_SIZE_EMPTY);
elementList.emplace_back(std::move(element));
}
int askIndex = 0;
for (auto iter = snapshotAsk.begin(); iter != snapshotAsk.end(); iter++) {
if (askIndex < maxMarketDepth) {
Element element;
element.insert(CCAPI_BEST_ASK_N_PRICE, iter->first.toString());
element.insert(CCAPI_BEST_ASK_N_SIZE, iter->second);
elementList.emplace_back(std::move(element));
}
++askIndex;
}
if (snapshotAsk.empty()) {
Element element;
element.insert(CCAPI_BEST_ASK_N_PRICE, CCAPI_BEST_ASK_N_PRICE_EMPTY);
element.insert(CCAPI_BEST_ASK_N_SIZE, CCAPI_BEST_ASK_N_SIZE_EMPTY);
elementList.emplace_back(std::move(element));
}
}
CCAPI_LOGGER_FUNCTION_EXIT;
}
std::map<Decimal, std::string> calculateMarketDepthUpdate(bool isBid, const std::map<Decimal, std::string>& c1, const std::map<Decimal, std::string>& c2,
int maxMarketDepth) {
if (c1.empty()) {
@@ -936,8 +1004,8 @@ class MarketDataService : public Service {
Element element;
std::string k1(CCAPI_LAST_PRICE);
std::string k2(CCAPI_LAST_SIZE);
element.emplace(k1, y.at(MarketDataMessage::DataFieldType::PRICE));
element.emplace(k2, y.at(MarketDataMessage::DataFieldType::SIZE));
element.emplace(k1, price);
element.emplace(k2, size);
{
auto it = y.find(MarketDataMessage::DataFieldType::TRADE_ID);
if (it != y.end()) {
@@ -969,20 +1037,62 @@ class MarketDataService : public Service {
}
}
}
void updateElementListWithOhlc(const WsConnection& wsConnection, const std::string& channelId, const std::string& symbolId, const std::string& field,
std::vector<Element>& elementList) {
void updateElementListWithExchangeProvidedCandlestick(const std::string& field, MarketDataMessage::TypeForData& input, std::vector<Element>& elementList) {
if (field == CCAPI_CANDLESTICK) {
for (auto& x : input) {
auto& type = x.first;
auto& detail = x.second;
if (type == MarketDataMessage::DataType::CANDLESTICK) {
for (auto& y : detail) {
auto& openPrice = y.at(MarketDataMessage::DataFieldType::OPEN_PRICE);
auto& highPrice = y.at(MarketDataMessage::DataFieldType::HIGH_PRICE);
auto& lowPrice = y.at(MarketDataMessage::DataFieldType::LOW_PRICE);
auto& closePrice = y.at(MarketDataMessage::DataFieldType::CLOSE_PRICE);
Element element;
std::string k1(CCAPI_OPEN_PRICE);
std::string k2(CCAPI_HIGH_PRICE);
std::string k3(CCAPI_LOW_PRICE);
std::string k4(CCAPI_CLOSE_PRICE);
element.emplace(k1, y.at(MarketDataMessage::DataFieldType::OPEN_PRICE));
element.emplace(k2, y.at(MarketDataMessage::DataFieldType::HIGH_PRICE));
element.emplace(k3, y.at(MarketDataMessage::DataFieldType::LOW_PRICE));
element.emplace(k4, y.at(MarketDataMessage::DataFieldType::CLOSE_PRICE));
{
auto it = y.find(MarketDataMessage::DataFieldType::VOLUME);
if (it != y.end()) {
std::string k(CCAPI_VOLUME);
element.emplace(k, it->second);
}
}
{
auto it = y.find(MarketDataMessage::DataFieldType::QUOTE_VOLUME);
if (it != y.end()) {
std::string k(CCAPI_QUOTE_VOLUME);
element.emplace(k, it->second);
}
}
elementList.emplace_back(std::move(element));
}
} else {
CCAPI_LOGGER_WARN("extra type " + MarketDataMessage::dataTypeToString(type));
}
}
}
}
void updateElementListWithCalculatedCandlestick(const WsConnection& wsConnection, const std::string& channelId, const std::string& symbolId,
const std::string& field, std::vector<Element>& elementList) {
if (field == CCAPI_TRADE || field == CCAPI_AGG_TRADE) {
Element element;
if (this->openByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].empty()) {
element.insert(CCAPI_OPEN, CCAPI_OHLC_EMPTY);
element.insert(CCAPI_HIGH, CCAPI_OHLC_EMPTY);
element.insert(CCAPI_LOW, CCAPI_OHLC_EMPTY);
element.insert(CCAPI_CLOSE, CCAPI_OHLC_EMPTY);
element.insert(CCAPI_OPEN_PRICE, CCAPI_CANDLESTICK_EMPTY);
element.insert(CCAPI_HIGH_PRICE, CCAPI_CANDLESTICK_EMPTY);
element.insert(CCAPI_LOW_PRICE, CCAPI_CANDLESTICK_EMPTY);
element.insert(CCAPI_CLOSE_PRICE, CCAPI_CANDLESTICK_EMPTY);
} else {
element.insert(CCAPI_OPEN, this->openByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]);
element.insert(CCAPI_HIGH, this->highByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].toString());
element.insert(CCAPI_LOW, this->lowByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].toString());
element.insert(CCAPI_CLOSE, this->closeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]);
element.insert(CCAPI_OPEN_PRICE, this->openByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]);
element.insert(CCAPI_HIGH_PRICE, this->highByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].toString());
element.insert(CCAPI_LOW_PRICE, this->lowByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId].toString());
element.insert(CCAPI_CLOSE_PRICE, this->closeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]);
}
elementList.emplace_back(std::move(element));
this->openByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = "";
@@ -1221,7 +1331,7 @@ class MarketDataService : public Service {
std::vector<Message> messageList;
std::vector<Element> elementList;
if (shouldConflate && intervalChanged) {
this->updateElementListWithOhlc(wsConnection, channelId, symbolId, field, elementList);
this->updateElementListWithCalculatedCandlestick(wsConnection, channelId, symbolId, field, elementList);
} else {
this->updateElementListWithTrade(field, input, elementList);
}
@@ -1243,14 +1353,53 @@ class MarketDataService : public Service {
}
if (shouldConflate) {
this->previousConflateTimeMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId) = conflateTp;
this->updateOhlc(wsConnection, channelId, symbolId, field, input);
this->updateCalculatedCandlestick(wsConnection, channelId, symbolId, field, input);
}
} else {
this->updateOhlc(wsConnection, channelId, symbolId, field, input);
this->updateCalculatedCandlestick(wsConnection, channelId, symbolId, field, input);
}
}
void updateOhlc(const WsConnection& wsConnection, const std::string& channelId, const std::string& symbolId, const std::string& field,
const MarketDataMessage::TypeForData& input) {
void processExchangeProvidedCandlestick(const WsConnection& wsConnection, const std::string& channelId, const std::string& symbolId, Event& event,
const TimePoint& tp, const TimePoint& timeReceived, MarketDataMessage::TypeForData& input, const std::string& field,
const std::map<std::string, std::string>& optionMap, const std::vector<std::string>& correlationIdList,
bool isSolicited) {
std::vector<Message> messageList;
std::vector<Element> elementList;
this->updateElementListWithExchangeProvidedCandlestick(field, input, elementList);
if (!elementList.empty()) {
Message message;
message.setTimeReceived(timeReceived);
message.setType(Message::Type::MARKET_DATA_EVENTS_CANDLESTICK);
message.setRecapType(isSolicited ? Message::RecapType::SOLICITED : Message::RecapType::NONE);
message.setTime(tp);
message.setElementList(elementList);
message.setCorrelationIdList(correlationIdList);
messageList.emplace_back(std::move(message));
}
if (!messageList.empty()) {
event.addMessages(messageList);
}
}
void processExchangeProvidedCandlestick(Event& event, const TimePoint& tp, const TimePoint& timeReceived, MarketDataMessage::TypeForData& input,
const std::vector<std::string>& correlationIdList, Message::Type messageType) {
std::vector<Message> messageList;
std::vector<Element> elementList;
this->updateElementListWithExchangeProvidedCandlestick(CCAPI_CANDLESTICK, input, elementList);
if (!elementList.empty()) {
Message message;
message.setTimeReceived(timeReceived);
message.setType(Message::Type::MARKET_DATA_EVENTS_CANDLESTICK);
message.setTime(tp);
message.setElementList(elementList);
message.setCorrelationIdList(correlationIdList);
messageList.emplace_back(std::move(message));
}
if (!messageList.empty()) {
event.addMessages(messageList);
}
}
void updateCalculatedCandlestick(const WsConnection& wsConnection, const std::string& channelId, const std::string& symbolId, const std::string& field,
const MarketDataMessage::TypeForData& input) {
if (field == CCAPI_TRADE || field == CCAPI_AGG_TRADE) {
for (const auto& x : input) {
auto type = x.first;
@@ -1327,7 +1476,7 @@ class MarketDataService : public Service {
}
return true;
}
int calculateMarketDepthSubscribedToExchange(int depthWanted, std::vector<int> availableMarketDepth) {
int calculateMarketDepthAllowedByExchange(int depthWanted, std::vector<int> availableMarketDepth) {
int i = ceilSearch(availableMarketDepth, 0, availableMarketDepth.size(), depthWanted);
if (i < 0) {
i = availableMarketDepth.size() - 1;
@@ -1374,7 +1523,7 @@ class MarketDataService : public Service {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
} else {
if (
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->wsConnectionByIdMap.at(wsConnection.id).status == WsConnection::Status::OPEN
#else
this->wsConnectionByIdMap.at(wsConnection.id)->status == WsConnection::Status::OPEN
@@ -1391,7 +1540,7 @@ class MarketDataService : public Service {
this->updateElementListWithUpdateMarketDepth(field, optionMap, snapshotBid, std::map<Decimal, std::string>(), snapshotAsk,
std::map<Decimal, std::string>(), elementList, true);
} else if (field == CCAPI_TRADE || field == CCAPI_AGG_TRADE) {
this->updateElementListWithOhlc(wsConnection, channelId, symbolId, field, elementList);
this->updateElementListWithCalculatedCandlestick(wsConnection, channelId, symbolId, field, elementList);
}
CCAPI_LOGGER_TRACE("elementList = " + toString(elementList));
this->previousConflateTimeMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId) = conflateTp;
@@ -1474,13 +1623,24 @@ class MarketDataService : public Service {
for (auto& marketDataMessage : marketDataMessageList) {
if (marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE) {
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE ||
marketDataMessage.type == MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK) {
const std::vector<std::string>& correlationIdList = {request.getCorrelationId()};
CCAPI_LOGGER_TRACE("correlationIdList = " + toString(correlationIdList));
if (marketDataMessage.data.find(MarketDataMessage::DataType::TRADE) != marketDataMessage.data.end() ||
marketDataMessage.data.find(MarketDataMessage::DataType::AGG_TRADE) != marketDataMessage.data.end()) {
if (marketDataMessage.data.find(MarketDataMessage::DataType::BID) != marketDataMessage.data.end() ||
marketDataMessage.data.find(MarketDataMessage::DataType::ASK) != marketDataMessage.data.end()) {
auto messageType = this->requestOperationToMessageTypeMap.at(request.getOperation());
const auto& param = request.getFirstParamWithDefault();
const auto& maxMarketDepthStr = mapGetWithDefault(param, std::string(CCAPI_MARKET_DEPTH_MAX));
int maxMarketDepth = maxMarketDepthStr.empty() ? INT_MAX : std::stoi(maxMarketDepthStr);
this->processOrderBookSnapshot(event, marketDataMessage.tp, timeReceived, marketDataMessage.data, correlationIdList, messageType, maxMarketDepth);
} else if (marketDataMessage.data.find(MarketDataMessage::DataType::TRADE) != marketDataMessage.data.end() ||
marketDataMessage.data.find(MarketDataMessage::DataType::AGG_TRADE) != marketDataMessage.data.end()) {
auto messageType = this->requestOperationToMessageTypeMap.at(request.getOperation());
this->processTrade(event, marketDataMessage.tp, timeReceived, marketDataMessage.data, correlationIdList, messageType);
} else if (marketDataMessage.data.find(MarketDataMessage::DataType::CANDLESTICK) != marketDataMessage.data.end()) {
auto messageType = this->requestOperationToMessageTypeMap.at(request.getOperation());
this->processExchangeProvidedCandlestick(event, marketDataMessage.tp, timeReceived, marketDataMessage.data, correlationIdList, messageType);
}
} else {
CCAPI_LOGGER_WARN("market data event type is unknown!");
@@ -1503,6 +1663,45 @@ class MarketDataService : public Service {
messageList.emplace_back(std::move(message));
event.addMessages(messageList);
}
void processOrderBookSnapshot(Event& event, const TimePoint& tp, const TimePoint& timeReceived, MarketDataMessage::TypeForData& input,
const std::vector<std::string>& correlationIdList, Message::Type messageType, int maxMarketDepth) {
std::vector<Message> messageList;
std::vector<Element> elementList;
std::map<Decimal, std::string> snapshotBid, snapshotAsk;
for (auto& x : input) {
auto& type = x.first;
auto& detail = x.second;
if (type == MarketDataMessage::DataType::BID) {
for (auto& y : detail) {
auto& price = y.at(MarketDataMessage::DataFieldType::PRICE);
auto& size = y.at(MarketDataMessage::DataFieldType::SIZE);
Decimal decimalPrice(price, this->sessionOptions.enableCheckOrderBookChecksum);
snapshotBid.emplace(std::move(decimalPrice), std::move(size));
}
CCAPI_LOGGER_TRACE("lastNToString(snapshotBid, " + toString(maxMarketDepth) + ") = " + lastNToString(snapshotBid, maxMarketDepth));
} else if (type == MarketDataMessage::DataType::ASK) {
for (auto& y : detail) {
auto& price = y.at(MarketDataMessage::DataFieldType::PRICE);
auto& size = y.at(MarketDataMessage::DataFieldType::SIZE);
Decimal decimalPrice(price, this->sessionOptions.enableCheckOrderBookChecksum);
snapshotAsk.emplace(std::move(decimalPrice), std::move(size));
}
CCAPI_LOGGER_TRACE("firstNToString(snapshotAsk, " + toString(maxMarketDepth) + ") = " + firstNToString(snapshotAsk, maxMarketDepth));
} else {
CCAPI_LOGGER_WARN("extra type " + MarketDataMessage::dataTypeToString(type));
}
}
this->updateElementListWithOrderBookSnapshot(CCAPI_MARKET_DEPTH, maxMarketDepth, snapshotBid, snapshotAsk, elementList);
CCAPI_LOGGER_TRACE("elementList = " + toString(elementList));
Message message;
message.setTimeReceived(timeReceived);
message.setType(messageType);
message.setTime(tp);
message.setElementList(elementList);
message.setCorrelationIdList(correlationIdList);
messageList.emplace_back(std::move(message));
event.addMessages(messageList);
}
void convertRequestForRestGenericPublicRequest(http::request<http::string_body>& req, const Request& request, const TimePoint& now,
const std::string& symbolId, const std::map<std::string, std::string>& credential) {
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
@@ -1535,43 +1734,43 @@ class MarketDataService : public Service {
}
} else {
if (this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap[wsConnection.id][exchangeSubscriptionId].empty()) {
int delayMilliSeconds = std::stoi(optionMap.at(CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS));
if (delayMilliSeconds > 0) {
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliSeconds)));
timerPtr->async_wait([wsConnection, exchangeSubscriptionId, delayMilliSeconds, that = this](ErrorCode const& ec) {
int delayMilliseconds = std::stoi(optionMap.at(CCAPI_FETCH_MARKET_DEPTH_INITIAL_SNAPSHOT_DELAY_MILLISECONDS));
if (delayMilliseconds > 0) {
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliseconds)));
timerPtr->async_wait([wsConnection, exchangeSubscriptionId, delayMilliseconds, that = this](ErrorCode const& ec) {
auto now = UtilTime::now();
if (ec) {
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
} else {
that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliseconds);
}
});
this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = timerPtr;
} else {
this->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
this->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliseconds);
}
}
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdVersionIdMap[wsConnection.id][exchangeSubscriptionId][versionId] =
marketDataMessage.data;
}
}
void buildOrderBookInitialOnFail(const WsConnection& wsConnection, const std::string& exchangeSubscriptionId, long delayMilliSeconds) {
auto thisDelayMilliSeconds = delayMilliSeconds * 2;
if (thisDelayMilliSeconds > 0) {
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(thisDelayMilliSeconds)));
timerPtr->async_wait([wsConnection, exchangeSubscriptionId, thisDelayMilliSeconds, that = this](ErrorCode const& ec) {
void buildOrderBookInitialOnFail(const WsConnection& wsConnection, const std::string& exchangeSubscriptionId, long delayMilliseconds) {
auto thisDelayMilliseconds = delayMilliseconds * 2;
if (thisDelayMilliseconds > 0) {
TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(thisDelayMilliseconds)));
timerPtr->async_wait([wsConnection, exchangeSubscriptionId, thisDelayMilliseconds, that = this](ErrorCode const& ec) {
if (ec) {
that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
} else {
that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, thisDelayMilliSeconds);
that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, thisDelayMilliseconds);
}
});
this->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] = timerPtr;
} else {
this->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, thisDelayMilliSeconds);
this->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, thisDelayMilliseconds);
}
}
void buildOrderBookInitial(const WsConnection& wsConnection, const std::string& exchangeSubscriptionId, long delayMilliSeconds) {
void buildOrderBookInitial(const WsConnection& wsConnection, const std::string& exchangeSubscriptionId, long delayMilliseconds) {
auto now = UtilTime::now();
http::request<http::string_body> req;
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
@@ -1582,10 +1781,10 @@ class MarketDataService : public Service {
this->createFetchOrderBookInitialReq(req, symbolId, now, credential);
this->sendRequest(
req,
[wsConnection, exchangeSubscriptionId, delayMilliSeconds, that = shared_from_base<MarketDataService>()](const beast::error_code& ec) {
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
[wsConnection, exchangeSubscriptionId, delayMilliseconds, that = shared_from_base<MarketDataService>()](const beast::error_code& ec) {
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliseconds);
},
[wsConnection, exchangeSubscriptionId, delayMilliSeconds, that = shared_from_base<MarketDataService>()](const http::response<http::string_body>& res) {
[wsConnection, exchangeSubscriptionId, delayMilliseconds, that = shared_from_base<MarketDataService>()](const http::response<http::string_body>& res) {
auto timeReceived = UtilTime::now();
int statusCode = res.result_int();
std::string body = res.body();
@@ -1710,19 +1909,19 @@ class MarketDataService : public Service {
that->eventHandler(event, nullptr);
that->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
} else {
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
// if (delayMilliSeconds > 0) {
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliseconds);
// if (delayMilliseconds > 0) {
// that->fetchMarketDepthInitialSnapshotTimerByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId] =
// that->serviceContextPtr->tlsClientPtr->set_timer(
// delayMilliSeconds, [wsConnection, exchangeSubscriptionId, delayMilliSeconds, that](ErrorCode const& ec) {
// delayMilliseconds, [wsConnection, exchangeSubscriptionId, delayMilliseconds, that](ErrorCode const& ec) {
// if (ec) {
// that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer");
// } else {
// that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
// that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliseconds);
// }
// });
// } else {
// that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
// that->buildOrderBookInitial(wsConnection, exchangeSubscriptionId, delayMilliseconds);
// }
}
return;
@@ -1730,11 +1929,27 @@ class MarketDataService : public Service {
CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what());
}
}
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliSeconds);
that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliseconds);
// WsConnection thisWsConnection = wsConnection;
// that->onFail_(thisWsConnection);
},
this->sessionOptions.httpRequestTimeoutMilliSeconds);
this->sessionOptions.httpRequestTimeoutMilliseconds);
}
std::string convertCandlestickIntervalSecondsToInterval(int intervalSeconds, const std::string& secondStr, const std::string& minuteStr,
const std::string& hourStr, const std::string& dayStr, const std::string& weekStr) {
std::string interval;
if (intervalSeconds < 60) {
interval = std::to_string(intervalSeconds) + secondStr;
} else if (intervalSeconds < 3600) {
interval = std::to_string(intervalSeconds / 60) + minuteStr;
} else if (intervalSeconds < 86400) {
interval = std::to_string(intervalSeconds / 3600) + hourStr;
} else if (intervalSeconds < 604800) {
interval = std::to_string(intervalSeconds / 86400) + dayStr;
} else {
interval = std::to_string(intervalSeconds / 604800) + weekStr;
}
return interval;
}
virtual std::vector<std::string> createSendStringListFromSubscriptionList(const WsConnection& wsConnection, const std::vector<Subscription>& subscriptionList,
const TimePoint& now, const std::map<std::string, std::string>& credential) {
@@ -1742,7 +1957,7 @@ class MarketDataService : public Service {
}
virtual void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) {}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
virtual void processTextMessage(WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived,
Event& event, std::vector<MarketDataMessage>& marketDataMessageList) {}
#else
@@ -1785,10 +2000,14 @@ class MarketDataService : public Service {
std::map<std::string, std::map<std::string, std::map<std::string, Decimal>>> lowByConnectionIdChannelIdSymbolIdMap;
std::map<std::string, std::map<std::string, std::map<std::string, std::string>>> closeByConnectionIdChannelIdSymbolIdMap;
std::string getRecentTradesTarget;
std::string getHistoricalTradesTarget;
std::string getRecentCandlesticksTarget;
std::string getHistoricalCandlesticksTarget;
std::string getMarketDepthTarget;
std::string getInstrumentTarget;
std::string getInstrumentsTarget;
std::map<std::string, int> exchangeJsonPayloadIdByConnectionIdMap;
std::map<std::string, std::map<int, std::vector<std::string>>> exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap;
std::map<std::string, std::map<int, std::vector<std::string>>> exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap;
// only needed for generic public subscription
std::map<std::string, std::string> correlationIdByConnectionIdMap;
std::map<std::string, std::map<std::string, std::map<int64_t, MarketDataMessage::TypeForData>>>
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceAscendex : public MarketDataService {
public:
MarketDataServiceAscendex(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_ASCENDEX;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/api/pro/v1/stream";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/pro/v1/trades";
this->getInstrumentTarget = "/api/pro/v1/products";
this->getInstrumentsTarget = "/api/pro/v1/products";
@@ -44,9 +44,12 @@ class MarketDataServiceAscendex : public MarketDataService {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_ASCENDEX_CHANNEL_BBO;
}
} else if (field == CCAPI_CANDLESTICK) {
std::string interval = std::to_string(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)) / 60);
channelId += ":" + interval;
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); }
@@ -78,14 +81,14 @@ class MarketDataServiceAscendex : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -160,9 +163,27 @@ class MarketDataServiceAscendex : public MarketDataService {
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (m == "bar") {
std::string channelId = m;
const rj::Value& data = document["data"];
std::string symbolId = document["s"].GetString();
std::string exchangeSubscriptionId = channelId + ":" + std::string(data["i"].GetString()) + ":" + symbolId;
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(data["ts"].GetString())));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, data["o"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, data["h"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, data["l"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, data["c"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, data["v"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (m == "ping") {
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(hdl, R"({ "op": "pong" })", wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, R"({ "op": "pong" })", ec);
@@ -215,7 +236,7 @@ class MarketDataServiceAscendex : public MarketDataService {
std::string sendString = stringBuffer.GetString();
ErrorCode ec;
CCAPI_LOGGER_TRACE(sendString);
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
@@ -7,30 +7,35 @@ namespace ccapi {
class MarketDataServiceBinance : public MarketDataServiceBinanceBase {
public:
MarketDataServiceBinance(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_API_KEY;
this->setupCredential({this->apiKeyName});
this->getRecentTradesTarget = "/api/v3/trades";
this->getHistoricalTradesTarget = "/api/v3/historicalTrades";
this->getRecentAggTradesTarget = "/api/v3/aggTrades";
this->getHistoricalAggTradesTarget = "/api/v3/aggTrades";
this->getRecentCandlesticksTarget = "/api/v3/klines";
this->getHistoricalCandlesticksTarget = "/api/v3/klines";
this->getMarketDepthTarget = "/api/v3/depth";
this->getInstrumentTarget = "/api/v3/exchangeInfo";
this->getInstrumentsTarget = "/api/v3/exchangeInfo";
}
@@ -8,7 +8,7 @@ namespace ccapi {
class MarketDataServiceBinanceBase : public MarketDataService {
public:
MarketDataServiceBinanceBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->enableCheckPingPongWebsocketApplicationLevel = false;
}
@@ -17,7 +17,7 @@ class MarketDataServiceBinanceBase : public MarketDataService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onOpen(wspp::connection_hdl hdl) override {
CCAPI_LOGGER_FUNCTION_ENTER;
auto now = UtilTime::now();
@@ -36,15 +36,15 @@ class MarketDataServiceBinanceBase : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_BOOK_TICKER;
} else {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
std::string updateSpeed;
if (conflateIntervalMilliSeconds < 1000) {
if (conflateIntervalMilliseconds < 1000) {
updateSpeed = "100ms";
}
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
@@ -53,6 +53,10 @@ class MarketDataServiceBinanceBase : public MarketDataService {
}
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
} else if (field == CCAPI_CANDLESTICK) {
std::string interval =
this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), "s", "m", "h", "d", "w");
channelId = channelId + "_" + interval;
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
@@ -94,7 +98,7 @@ class MarketDataServiceBinanceBase : public MarketDataService {
}
document.AddMember("params", params, allocator);
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
rj::StringBuffer stringBuffer;
@@ -105,14 +109,14 @@ class MarketDataServiceBinanceBase : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -127,11 +131,11 @@ class MarketDataServiceBinanceBase : public MarketDataService {
std::vector<std::string> correlationIdList;
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
int id = std::stoi(document["id"].GetString());
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
if (this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.end() &&
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).at(id)) {
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
@@ -240,6 +244,22 @@ class MarketDataServiceBinanceBase : public MarketDataService {
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, data["m"].GetBool() ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::AGG_TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId.find(CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_KLINE) != std::string::npos) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
const rj::Value& k = data["k"];
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(k["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, k["o"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, k["h"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, k["l"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, k["c"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, k["v"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, k["q"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
@@ -268,7 +288,21 @@ class MarketDataServiceBinanceBase : public MarketDataService {
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_RECENT_AGG_TRADES: {
case Request::Operation::GET_HISTORICAL_TRADES: {
req.method(http::verb::get);
auto target = this->getHistoricalTradesTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
{CCAPI_START_TRADE_ID, "fromId"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_RECENT_AGG_TRADES:
case Request::Operation::GET_HISTORICAL_AGG_TRADES: {
req.method(http::verb::get);
auto target = this->getRecentAggTradesTarget;
std::string queryString;
@@ -276,6 +310,53 @@ class MarketDataServiceBinanceBase : public MarketDataService {
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
{CCAPI_START_TIME_SECONDS, "startTime"},
{CCAPI_END_TIME_SECONDS, "endTime"},
{CCAPI_START_AGG_TRADE_ID, "fromId"},
},
{
{CCAPI_START_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBinanceBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
{CCAPI_END_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBinanceBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
req.method(http::verb::get);
auto target = this->getRecentCandlesticksTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS, "interval"},
{CCAPI_LIMIT, "limit"},
{CCAPI_START_TIME_SECONDS, "startTime"},
{CCAPI_END_TIME_SECONDS, "endTime"},
},
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS,
[that = shared_from_base<MarketDataServiceBinanceBase>()](const std::string& input) {
return that->convertCandlestickIntervalSecondsToInterval(std::stoi(input), "s", "m", "h", "d", "w");
}},
{CCAPI_START_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBinanceBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
{CCAPI_END_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBinanceBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_MARKET_DEPTH: {
req.method(http::verb::get);
auto target = this->getMarketDepthTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_MARKET_DEPTH_MAX, "limit"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
@@ -317,7 +398,8 @@ class MarketDataServiceBinanceBase : public MarketDataService {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
switch (request.getOperation()) {
case Request::Operation::GET_RECENT_TRADES: {
case Request::Operation::GET_RECENT_TRADES:
case Request::Operation::GET_HISTORICAL_TRADES: {
for (const auto& x : document.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
@@ -331,7 +413,8 @@ class MarketDataServiceBinanceBase : public MarketDataService {
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_RECENT_AGG_TRADES: {
case Request::Operation::GET_RECENT_AGG_TRADES:
case Request::Operation::GET_HISTORICAL_AGG_TRADES: {
for (const auto& x : document.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_AGG_TRADE;
@@ -345,6 +428,41 @@ class MarketDataServiceBinanceBase : public MarketDataService {
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
for (const auto& x : document.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x[0].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, x[7].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_MARKET_DEPTH: {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(document["T"].GetString()));
for (const auto& x : document["bids"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
for (const auto& x : document["asks"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
@@ -380,6 +498,7 @@ class MarketDataServiceBinanceBase : public MarketDataService {
}
bool isDerivatives{};
std::string getRecentAggTradesTarget;
std::string getHistoricalAggTradesTarget;
};
} /* namespace ccapi */
#endif
@@ -7,30 +7,35 @@ namespace ccapi {
class MarketDataServiceBinanceCoinFutures : public MarketDataServiceBinanceDerivativesBase {
public:
MarketDataServiceBinanceCoinFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBinanceDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_COIN_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_COIN_FUTURES_API_KEY;
this->setupCredential({this->apiKeyName});
this->getRecentTradesTarget = "/dapi/v1/trades";
this->getHistoricalTradesTarget = "/dapi/v1/historicalTrades";
this->getRecentAggTradesTarget = "/dapi/v1/aggTrades";
this->getHistoricalAggTradesTarget = "/dapi/v1/aggTrades";
this->getRecentCandlesticksTarget = "/dapi/v1/klines";
this->getHistoricalCandlesticksTarget = "/dapi/v1/klines";
this->getMarketDepthTarget = "/dapi/v1/depth";
this->getInstrumentTarget = "/dapi/v1/exchangeInfo";
this->getInstrumentsTarget = "/dapi/v1/exchangeInfo";
}
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceBase {
public:
MarketDataServiceBinanceDerivativesBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->isDerivatives = true;
}
@@ -19,17 +19,17 @@ class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceB
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({1, 5, 10, 20}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({1, 5, 10, 20}));
if (marketDepthSubscribedToExchange == 1) {
channelId = CCAPI_WEBSOCKET_BINANCE_BASE_CHANNEL_BOOK_TICKER;
} else {
std::string updateSpeed;
if (conflateIntervalMilliSeconds < 250) {
if (conflateIntervalMilliseconds < 250) {
updateSpeed = "100ms";
} else if (conflateIntervalMilliSeconds >= 500) {
} else if (conflateIntervalMilliseconds >= 500) {
updateSpeed = "500ms";
}
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
@@ -38,9 +38,17 @@ class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceB
}
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
} else if (field == CCAPI_CANDLESTICK) {
std::string interval =
this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), "s", "m", "h", "d", "w");
channelId = channelId + "_" + interval;
}
}
void extractInstrumentInfo(Element& element, const rj::Value& x) {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_INSTRUMENT_STATUS, x["status"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseAsset"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteAsset"].GetString());
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_MARGIN_ASSET, x["marginAsset"].GetString());
element.insert(CCAPI_UNDERLYING_SYMBOL, x["pair"].GetString());
@@ -51,11 +59,38 @@ class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceB
} else if (filterType == "LOT_SIZE") {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, y["stepSize"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, y["minQty"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MAX, y["maxQty"].GetString());
} else if (filterType == "MIN_NOTIONAL") {
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, y["notional"].GetString());
}
}
}
void convertRequestForRest(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
this->prepareReq(req, credential);
switch (request.getOperation()) {
case Request::Operation::GET_MARKET_DEPTH: {
req.method(http::verb::get);
auto target = this->getMarketDepthTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_MARKET_DEPTH_MAX, "limit"},
},
{
{CCAPI_MARKET_DEPTH_MAX,
[that = shared_from_base<MarketDataServiceBinanceDerivativesBase>()](const std::string& input) {
return std::to_string(that->calculateMarketDepthAllowedByExchange(std::stoi(input), {5, 10, 20, 50, 100, 500, 1000}));
}},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
default:
MarketDataServiceBinanceBase::convertRequestForRest(req, request, now, symbolId, credential);
}
}
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
switch (request.getOperation()) {
@@ -7,30 +7,35 @@ namespace ccapi {
class MarketDataServiceBinanceUs : public MarketDataServiceBinanceBase {
public:
MarketDataServiceBinanceUs(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBinanceBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_US;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_US_API_KEY;
this->setupCredential({this->apiKeyName});
this->getRecentTradesTarget = "/api/v3/trades";
this->getHistoricalTradesTarget = "/api/v3/historicalTrades";
this->getRecentAggTradesTarget = "/api/v3/aggTrades";
this->getHistoricalAggTradesTarget = "/api/v3/aggTrades";
this->getRecentCandlesticksTarget = "/api/v3/klines";
this->getHistoricalCandlesticksTarget = "/api/v3/klines";
this->getMarketDepthTarget = "/api/v3/depth";
this->getInstrumentTarget = "/api/v3/exchangeInfo";
this->getInstrumentsTarget = "/api/v3/exchangeInfo";
}
@@ -7,30 +7,35 @@ namespace ccapi {
class MarketDataServiceBinanceUsdsFutures : public MarketDataServiceBinanceDerivativesBase {
public:
MarketDataServiceBinanceUsdsFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBinanceDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BINANCE_USDS_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/stream";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BINANCE_USDS_FUTURES_API_KEY;
this->setupCredential({this->apiKeyName});
this->getRecentTradesTarget = "/fapi/v1/trades";
this->getHistoricalTradesTarget = "/fapi/v1/historicalTrades";
this->getRecentAggTradesTarget = "/fapi/v1/aggTrades";
this->getHistoricalAggTradesTarget = "/fapi/v1/aggTrades";
this->getRecentCandlesticksTarget = "/fapi/v1/klines";
this->getHistoricalCandlesticksTarget = "/fapi/v1/klines";
this->getMarketDepthTarget = "/fapi/v1/depth";
this->getInstrumentTarget = "/fapi/v1/exchangeInfo";
this->getInstrumentsTarget = "/fapi/v1/exchangeInfo";
}
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceBitfinex : public MarketDataService {
public:
MarketDataServiceBitfinex(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITFINEX;
this->baseUrlWs = std::string(CCAPI_BITFINEX_PUBLIC_URL_WS_BASE) + "/ws/2";
this->baseUrlRest = CCAPI_BITFINEX_PUBLIC_URL_REST_BASE;
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/v2/trades/{Symbol}/hist";
this->getInstrumentsTarget = CCAPI_BITFINEX_GET_INSTRUMENTS_PATH;
this->getInstrumentTarget = CCAPI_BITFINEX_GET_INSTRUMENTS_PATH;
@@ -36,8 +36,8 @@ class MarketDataServiceBitfinex : public MarketDataService {
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); }
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"event":"ping"})", wspp::frame::opcode::text, ec); }
void onOpen(wspp::connection_hdl hdl) override {
MarketDataService::onOpen(hdl);
rj::Document document;
@@ -103,7 +103,7 @@ class MarketDataServiceBitfinex : public MarketDataService {
MarketDataService::onIncorrectStatesFound(wsConnection, hdl, textMessage, timeReceived, exchangeSubscriptionId, reason);
}
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); }
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"event":"ping"})", ec); }
void onOpen(std::shared_ptr<WsConnection> wsConnectionPtr) override {
MarketDataService::onOpen(wsConnectionPtr);
rj::Document document;
@@ -172,28 +172,23 @@ class MarketDataServiceBitfinex : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({1, 25, 100, 250}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({1, 25, 100, 250}));
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
} else if (field == CCAPI_CANDLESTICK) {
std::string interval =
this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), "", "m", "h", "D", "W");
channelId = std::string(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES) + ":" + interval;
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override { return std::vector<std::string>(); }
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
void processTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
#endif
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
if (document.IsArray() && document.Size() >= 1) {
@@ -201,46 +196,39 @@ class MarketDataServiceBitfinex : public MarketDataService {
if (document.Size() >= 2 && document[1].IsString() && std::string(document[1].GetString()) == "hb") {
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document[2].GetString());
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
if (!this->checkSequence(wsConnection, sequence)) {
this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, exchangeSubscriptionId);
return;
}
#else
if (!this->checkSequence(wsConnectionPtr, sequence)) {
this->onOutOfSequence(wsConnectionPtr, sequence, textMessageView, timeReceived, exchangeSubscriptionId);
return;
}
#endif
}
} else {
auto channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_CHANNEL_ID);
auto symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap.at(wsConnection.id).at(exchangeSubscriptionId).at(CCAPI_SYMBOL_ID);
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0 || channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES) {
std::string channel =
channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0 ? CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK : CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES;
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS, 0) == 0 || channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES ||
channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES, 0) == 0) {
std::string channel;
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS, 0) == 0) {
channel = CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS;
} else if (channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES) {
channel = CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES;
} else if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES, 0) == 0) {
channel = CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES;
}
rj::Value data(rj::kArrayType);
if (document[1].IsArray()) {
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document[2].GetString());
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
if (!this->checkSequence(wsConnection, sequence)) {
this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, exchangeSubscriptionId);
return;
}
#else
if (!this->checkSequence(wsConnectionPtr, sequence)) {
this->onOutOfSequence(wsConnectionPtr, sequence, textMessageView, timeReceived, exchangeSubscriptionId);
return;
}
#endif
}
const rj::Value& content = document[1].GetArray();
if (content[0].IsArray()) {
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document[2].GetString());
}
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0) {
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS, 0) == 0) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
@@ -270,7 +258,7 @@ class MarketDataServiceBitfinex : public MarketDataService {
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else {
} else if (channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES) {
for (const auto& x : content.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
@@ -288,36 +276,72 @@ class MarketDataServiceBitfinex : public MarketDataService {
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES, 0) == 0) {
for (const auto& x : content.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.recapType = MarketDataMessage::RecapType::SOLICITED;
std::string timestampInMilliseconds = x[0].GetString();
timestampInMilliseconds.insert(timestampInMilliseconds.size() - 3, ".");
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(timestampInMilliseconds));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[5].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
} else {
const rj::Value& x = content;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
auto count = std::string(x[1].GetString());
auto amount = UtilString::normalizeDecimalString(x[2].GetString());
if (count != "0") {
if (amount.at(0) == '-') {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount.substr(1)});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::ASK]
.emplace_back(std::move(dataPoint));
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::BID]
.emplace_back(std::move(dataPoint));
}
if (channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
std::string timestampInMilliseconds = x[0].GetString();
timestampInMilliseconds.insert(timestampInMilliseconds.size() - 3, ".");
marketDataMessage.tp = UtilTime::makeTimePoint(UtilTime::divide(timestampInMilliseconds));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[5].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else {
if (amount.at(0) == '-') {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, "0"});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::ASK]
.emplace_back(std::move(dataPoint));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
auto count = std::string(x[1].GetString());
auto amount = UtilString::normalizeDecimalString(x[2].GetString());
if (count != "0") {
if (amount.at(0) == '-') {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount.substr(1)});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::ASK]
.emplace_back(std::move(dataPoint));
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, amount});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::BID]
.emplace_back(std::move(dataPoint));
}
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, "0"});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::BID]
.emplace_back(std::move(dataPoint));
if (amount.at(0) == '-') {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, "0"});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::ASK]
.emplace_back(std::move(dataPoint));
} else {
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, "0"});
this->marketDataMessageDataBufferByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId]
[MarketDataMessage::DataType::BID]
.emplace_back(std::move(dataPoint));
}
}
}
}
@@ -326,17 +350,10 @@ class MarketDataServiceBitfinex : public MarketDataService {
if (str == "tu" || str == "te") {
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document[3].GetString());
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
if (!this->checkSequence(wsConnection, sequence)) {
this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, exchangeSubscriptionId);
return;
}
#else
if (!this->checkSequence(wsConnectionPtr, sequence)) {
this->onOutOfSequence(wsConnectionPtr, sequence, textMessageView, timeReceived, exchangeSubscriptionId);
return;
}
#endif
}
if (str == CCAPI_BITFINEX_STREAM_TRADE_RAW_MESSAGE_TYPE) {
const rj::Value& x = document[2].GetArray();
@@ -361,17 +378,10 @@ class MarketDataServiceBitfinex : public MarketDataService {
} else if (str == "cs") {
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document[3].GetString());
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
if (!this->checkSequence(wsConnection, sequence)) {
this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, exchangeSubscriptionId);
return;
}
#else
if (!this->checkSequence(wsConnectionPtr, sequence)) {
this->onOutOfSequence(wsConnectionPtr, sequence, textMessageView, timeReceived, exchangeSubscriptionId);
return;
}
#endif
}
if (this->sessionOptions.enableCheckOrderBookChecksum) {
this->orderBookChecksumByConnectionIdSymbolIdMap[wsConnection.id][symbolId] =
@@ -397,9 +407,16 @@ class MarketDataServiceBitfinex : public MarketDataService {
std::vector<std::string> sendStringList;
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0 || channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES) {
std::string channel = channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK, 0) == 0 ? CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK
: CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES;
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS, 0) == 0 || channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES ||
channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES, 0) == 0) {
std::string channel;
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS, 0) == 0) {
channel = CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS;
} else if (channelId == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES) {
channel = CCAPI_WEBSOCKET_BITFINEX_CHANNEL_TRADES;
} else if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES, 0) == 0) {
channel = CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES;
}
for (auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
rj::Document document;
document.SetObject();
@@ -407,8 +424,13 @@ class MarketDataServiceBitfinex : public MarketDataService {
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
document.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator);
auto symbolId = subscriptionListBySymbolId.first;
document.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
if (channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK) {
if (channelId.rfind(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES, 0) == 0) {
auto splitted = UtilString::split(channelId, ':');
document.AddMember("key", rj::Value(("trade:" + splitted.at(1) + ":" + symbolId).c_str(), allocator).Move(), allocator);
} else {
document.AddMember("symbol", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
if (channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS) {
document.AddMember("prec", rj::Value("P0").Move(), allocator);
document.AddMember("freq", rj::Value("F0").Move(), allocator);
document.AddMember(
@@ -430,21 +452,28 @@ class MarketDataServiceBitfinex : public MarketDataService {
}
for (const auto& sendString : sendStringList) {
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
this->send(hdl, sendString, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, sendString, ec);
#endif
if (ec) {
this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "subscribe");
}
}
} else if (eventStr == "subscribed" || eventStr == "error") {
std::string channel = document["channel"].GetString();
auto channelId = channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOK
? channel + "?" + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::string(document["len"].GetString())
: channel;
auto symbolId = std::string(document["symbol"].GetString());
std::string channelId;
if (channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_BOOKS) {
channelId = channel + "?" + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::string(document["len"].GetString());
} else if (channel == CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES) {
auto splitted = UtilString::split(document["key"].GetString(), ':');
channelId = std::string(CCAPI_WEBSOCKET_BITFINEX_CHANNEL_CANDLES) + ":" + splitted.at(1);
} else {
channelId = channel;
}
std::string symbolId;
if (document.FindMember("symbol") != document.MemberEnd()) {
symbolId = std::string(document["symbol"].GetString());
} else if (document.FindMember("key") != document.MemberEnd()) {
symbolId = UtilString::split(std::string(document["key"].GetString()), ':').at(2);
}
if (eventStr == "subscribed") {
auto exchangeSubscriptionId = std::string(document["chanId"].GetString());
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
@@ -7,29 +7,32 @@ namespace ccapi {
class MarketDataServiceBitget : public MarketDataServiceBitgetBase {
public:
MarketDataServiceBitget(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/v1/stream";
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/ws/public";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
this->getRecentTradesTarget = "/api/spot/v1/market/fills";
this->getInstrumentTarget = "/api/spot/v1/public/product";
this->getInstrumentsTarget = "/api/spot/v1/public/products";
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/v2/spot/market/fills";
this->getHistoricalTradesTarget = "/api/v2/spot/market/fills-history";
this->getInstrumentTarget = "/api/v2/spot/public/symbols";
this->getInstrumentsTarget = "/api/v2/spot/public/symbols";
this->getRecentCandlesticksTarget = "/api/v2/spot/market/candles";
this->getHistoricalCandlesticksTarget = "/api/v2/spot/market/candles";
}
virtual ~MarketDataServiceBitget() {}
};
@@ -7,8 +7,10 @@ namespace ccapi {
class MarketDataServiceBitgetBase : public MarketDataService {
public:
MarketDataServiceBitgetBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->hostHttpHeaderValueIgnorePort = true;
}
virtual ~MarketDataServiceBitgetBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
@@ -18,24 +20,15 @@ class MarketDataServiceBitgetBase : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (this->isDerivatives) this->instrumentType = subscription.getInstrumentType();
if (field == CCAPI_MARKET_DEPTH) {
if (this->isDerivatives) {
if (conflateIntervalMilliSeconds < 200) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS;
} else {
if (marketDepthRequested <= 1) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1;
} else if (marketDepthRequested <= 5) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5;
} else if (marketDepthRequested <= 15) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15;
} else {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS;
}
}
if (conflateIntervalMilliseconds < 200 && this->isDerivatives) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS;
} else {
if (marketDepthRequested <= 5) {
if (marketDepthRequested <= 1) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS1;
} else if (marketDepthRequested <= 5) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS5;
} else if (marketDepthRequested <= 15) {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS15;
@@ -43,9 +36,13 @@ class MarketDataServiceBitgetBase : public MarketDataService {
channelId = CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_BOOKS;
}
}
} else if (field == CCAPI_CANDLESTICK) {
std::string interval =
this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), " ", "m", "H", "D", "W");
channelId = channelId + interval;
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); }
@@ -67,7 +64,7 @@ class MarketDataServiceBitgetBase : public MarketDataService {
}
std::string exchangeSubscriptionId = UtilString::split(channelId, "?").at(0) + ":" + symbolId;
rj::Value arg(rj::kObjectType);
std::string instType = this->isDerivatives ? "mc" : "sp";
std::string instType = this->instrumentType;
arg.AddMember("instType", rj::Value(instType.c_str(), allocator).Move(), allocator);
arg.AddMember("channel", rj::Value(channelId.c_str(), allocator).Move(), allocator);
arg.AddMember("instId", rj::Value(symbolId.c_str(), allocator).Move(), allocator);
@@ -107,14 +104,14 @@ class MarketDataServiceBitgetBase : public MarketDataService {
return intToHex(csCalc);
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -229,13 +226,31 @@ class MarketDataServiceBitgetBase : public MarketDataService {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.recapType = recapType;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum["price"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum["size"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "Buy" ? "1" : "0"});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(datum["tradeId"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (channelId.find(CCAPI_WEBSOCKET_BITGET_BASE_CHANNEL_KLINE) != std::string::npos) {
for (const auto& datum : document["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum[0].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum[1].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum[2].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum[3].GetString()) == "sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, datum[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, datum[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, datum[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, datum[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, datum[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, datum[6].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
@@ -257,26 +272,56 @@ class MarketDataServiceBitgetBase : public MarketDataService {
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
{CCAPI_INSTRUMENT_TYPE, "productType"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
case Request::Operation::GET_HISTORICAL_TRADES: {
req.method(http::verb::get);
std::string target;
auto target = this->getHistoricalTradesTarget;
std::string queryString;
if (this->isDerivatives) {
target = this->getInstrumentsTarget;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "productType"},
});
} else {
target = this->getInstrumentTarget;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendSymbolId(queryString, symbolId, "symbol");
}
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
{CCAPI_INSTRUMENT_TYPE, "productType"},
{CCAPI_START_TIME_SECONDS, "startTime"},
{CCAPI_END_TIME_SECONDS, "endTime"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
req.method(http::verb::get);
auto target = this->getRecentCandlesticksTarget;
std::string minuteSuffix = this->isDerivatives ? "m" : "min";
std::string hourSuffix = this->isDerivatives ? "H" : "h";
std::string daySuffix = this->isDerivatives ? "D" : "day";
std::string weekSuffix = this->isDerivatives ? "W" : "week";
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(
queryString, param,
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS, "granularity"},
{CCAPI_LIMIT, "limit"},
{CCAPI_START_TIME_SECONDS, "startTime"},
{CCAPI_END_TIME_SECONDS, "endTime"},
{CCAPI_INSTRUMENT_TYPE, "productType"},
},
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS,
[that = shared_from_base<MarketDataServiceBitgetBase>(), minuteSuffix, hourSuffix, daySuffix, weekSuffix](const std::string& input) {
return that->convertCandlestickIntervalSecondsToInterval(std::stoi(input), " ", minuteSuffix, hourSuffix, daySuffix, weekSuffix);
}},
{CCAPI_START_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBitgetBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
{CCAPI_END_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBitgetBase>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENTS: {
@@ -284,25 +329,34 @@ class MarketDataServiceBitgetBase : public MarketDataService {
auto target = this->getInstrumentsTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
if (this->isDerivatives) {
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "productType"},
});
req.target(target + "?" + queryString);
} else {
req.target(target);
}
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "productType"},
});
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
std::string target;
std::string queryString;
target = this->getInstrumentsTarget;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "productType"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractInstrumentInfo(Element& element, const rj::Value& x) {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
if (this->isDerivatives) {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
int pricePlace = std::stoi(x["pricePlace"].GetString());
if (pricePlace > 0) {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(pricePlace - 1, '0') + x["priceEndStep"].GetString());
@@ -312,16 +366,13 @@ class MarketDataServiceBitgetBase : public MarketDataService {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["sizeMultiplier"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minTradeNum"].GetString());
} else {
element.insert(CCAPI_INSTRUMENT, x["symbolName"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
int priceScale = std::stoi(x["priceScale"].GetString());
int priceScale = std::stoi(x["pricePrecision"].GetString());
if (priceScale > 0) {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "0." + std::string(priceScale - 1, '0') + "1");
} else {
element.insert(CCAPI_ORDER_PRICE_INCREMENT, "1");
}
int quantityScale = std::stoi(x["quantityScale"].GetString());
int quantityScale = std::stoi(x["quantityPrecision"].GetString());
if (quantityScale > 0) {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, "0." + std::string(quantityScale - 1, '0') + "1");
} else {
@@ -335,22 +386,38 @@ class MarketDataServiceBitgetBase : public MarketDataService {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
switch (request.getOperation()) {
case Request::Operation::GET_RECENT_TRADES: {
case Request::Operation::GET_RECENT_TRADES:
case Request::Operation::GET_HISTORICAL_TRADES: {
for (const auto& datum : document["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum[this->isDerivatives ? "timestamp" : "fillTime"].GetString())));
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum["ts"].GetString())));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert(
{MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum[this->isDerivatives ? "price" : "fillPrice"].GetString())});
dataPoint.insert(
{MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum[this->isDerivatives ? "size" : "fillQuantity"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(datum["price"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(datum["size"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, datum["tradeId"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "sell" ? "1" : "0"});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(datum["side"].GetString()) == "Buy" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
for (const auto& datum : document["data"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(datum[0].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, datum[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, datum[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, datum[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, datum[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, datum[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, datum[6].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
@@ -385,6 +452,7 @@ class MarketDataServiceBitgetBase : public MarketDataService {
}
}
bool isDerivatives{};
std::string instrumentType{"SPOT"};
};
} /* namespace ccapi */
#endif
@@ -7,29 +7,32 @@ namespace ccapi {
class MarketDataServiceBitgetFutures : public MarketDataServiceBitgetBase {
public:
MarketDataServiceBitgetFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceBitgetBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITGET_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/mix/v1/stream";
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/ws/public";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
this->getRecentTradesTarget = "/api/mix/v1/market/fills";
this->getInstrumentTarget = "/api/mix/v1/market/contracts";
this->getInstrumentsTarget = "/api/mix/v1/market/contracts";
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/v2/mix/market/fills";
this->getHistoricalTradesTarget = "/api/v2/mix/market/fills-history";
this->getInstrumentTarget = "/api/v2/mix/market/contracts";
this->getInstrumentsTarget = "/api/v2/mix/market/contracts";
this->getRecentCandlesticksTarget = "/api/v2/mix/market/candles";
this->getHistoricalCandlesticksTarget = "/api/v2/mix/market/candles";
this->isDerivatives = true;
}
virtual ~MarketDataServiceBitgetFutures() {}
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceBitmart : public MarketDataService {
public:
MarketDataServiceBitmart(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITMART;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/api?protocol=1.1";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_BITMART_API_KEY;
this->apiSecretName = CCAPI_BITMART_API_SECRET;
this->apiMemo = CCAPI_BITMART_API_MEMO;
@@ -52,7 +52,7 @@ class MarketDataServiceBitmart : public MarketDataService {
}
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
void onClose(wspp::connection_hdl hdl) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
@@ -97,14 +97,14 @@ class MarketDataServiceBitmart : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceBitmex : public MarketDataService {
public:
MarketDataServiceBitmex(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITMEX;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/realtime";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/v1/trade";
this->getInstrumentTarget = "/api/v1/instrument";
this->getInstrumentsTarget = "/api/v1/instrument";
@@ -54,7 +54,7 @@ class MarketDataServiceBitmex : public MarketDataService {
}
}
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); }
void onClose(wspp::connection_hdl hdl) override {
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
@@ -97,14 +97,14 @@ class MarketDataServiceBitmex : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -187,7 +187,7 @@ class MarketDataServiceBitmex : public MarketDataService {
} else {
price = this->priceByConnectionIdChannelIdSymbolIdPriceIdMap[wsConnection.id][channelId][symbolId][priceId];
if (price.empty()) {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->onIncorrectStatesFound(wsConnection, hdl, textMessage, timeReceived, exchangeSubscriptionId,
"bitmex update for missing item came through on wsConnection = " + toString(wsConnection) +
", channelId = " + channelId + ", symbolId = " + symbolId + ", priceId = " + priceId + ". Data: " +
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceBitstamp : public MarketDataService {
public:
MarketDataServiceBitstamp(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BITSTAMP;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
@@ -15,19 +15,19 @@ class MarketDataServiceBitstamp : public MarketDataService {
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/api/v2/transactions/{currency_pair}/"; // must have trailing slash
this->getInstrumentTarget = "/api/v2/trading-pairs-info/";
this->getInstrumentsTarget = "/api/v2/trading-pairs-info/";
@@ -37,7 +37,7 @@ class MarketDataServiceBitstamp : public MarketDataService {
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
this->send(hdl, R"({"event": "bts:heartbeat"})", wspp::frame::opcode::text, ec);
}
@@ -78,14 +78,14 @@ class MarketDataServiceBitstamp : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -2,48 +2,71 @@
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT
#include "ccapi_cpp/service/ccapi_market_data_service_bybit_base.h"
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceBybit : public MarketDataServiceBybitBase {
class MarketDataServiceBybit : public MarketDataService {
public:
MarketDataServiceBybit(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/spot/public/v3";
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v5/public/{instrumentTypeSubstitute}";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
this->getRecentTradesTarget = "/spot/v3/public/quote/trades";
this->getInstrumentsTarget = "/spot/v3/public/symbols";
this->getRecentTradesTarget = "/v5/market/recent-trade";
this->getHistoricalTradesTarget = "/v5/market/recent-trade";
this->getRecentCandlesticksTarget = "/v5/market/kline";
this->getHistoricalCandlesticksTarget = "/v5/market/kline";
this->getMarketDepthTarget = "/v5/market/orderbook";
this->getInstrumentTarget = "/v5/market/instruments-info";
this->getInstrumentsTarget = "/v5/market/instruments-info";
}
virtual ~MarketDataServiceBybit() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
std::string getInstrumentGroup(const Subscription& subscription) override {
const auto& instrumentTypeSubstitute = subscription.getInstrumentType();
std::string url = MarketDataService::getInstrumentGroup(subscription);
std::string toReplace("{instrumentTypeSubstitute}");
url.replace(url.find(toReplace), toReplace.length(), instrumentTypeSubstitute);
return url;
}
std::string convertCandlestickIntervalSecondsToInterval(int intervalSeconds) {
std::string interval;
if (intervalSeconds < 86400) {
interval = std::to_string(intervalSeconds / 60);
} else if (intervalSeconds == 86400) {
interval = "D";
} else {
interval = "W";
}
return interval;
}
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
const auto& marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
const auto& instrumentType = subscription.getInstrumentType();
if (field == CCAPI_MARKET_DEPTH) {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER;
} else {
channelId = CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH;
std::vector<int> depths;
if (instrumentType == "spot") {
depths = {1, 50, 200};
} else if (instrumentType == "linear" || instrumentType == "inverse") {
depths = {1, 50, 200, 500};
} else if (instrumentType == "option") {
depths = {25, 100};
}
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, depths);
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
} else if (field == CCAPI_CANDLESTICK) {
int intervalSeconds = std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS));
std::string interval = this->convertCandlestickIntervalSecondsToInterval(intervalSeconds);
std::string toReplace = "{interval}";
channelId.replace(channelId.find(toReplace), toReplace.length(), interval);
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
@@ -58,9 +81,13 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
auto channelId = subscriptionListByChannelIdSymbolId.first;
for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListByInstrument.first;
auto exchangeSubscriptionId = channelId;
if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER || channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
std::string exchangeSubscriptionId = channelId;
if (channelId.rfind(CCAPI_WEBSOCKET_BYBIT_CHANNEL_ORDERBOOK, 0) == 0) {
int marketDepthSubscribedToExchange =
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
exchangeSubscriptionId = CCAPI_WEBSOCKET_BYBIT_CHANNEL_ORDERBOOK;
std::string toReplace = "{depth}";
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), std::to_string(marketDepthSubscribedToExchange));
}
std::string toReplace = "{symbol}";
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), symbolId);
@@ -72,7 +99,7 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
}
document.AddMember("args", args, allocator);
document.AddMember("req_id", rj::Value(std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).c_str(), allocator).Move(), allocator);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
rj::StringBuffer stringBuffer;
@@ -82,19 +109,10 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
sendStringList.push_back(sendString);
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
void processTextMessage(std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
#endif
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
if (document.IsObject() && document.HasMember("op")) {
@@ -109,11 +127,11 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
int id = std::stoi(document["req_id"].GetString());
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
if (this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.end() &&
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).at(id)) {
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
@@ -137,73 +155,63 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
event.setMessageList(messageList);
}
} else if (document.IsObject() && document.HasMember("data")) {
MarketDataMessage marketDataMessage;
std::string exchangeSubscriptionId = document["topic"].GetString();
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
auto optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
const rj::Value& data = document["data"];
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(data["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_BOOK_TICKER) {
if (channelId.rfind(CCAPI_WEBSOCKET_BYBIT_CHANNEL_ORDERBOOK, 0) == 0) {
MarketDataMessage marketDataMessage;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(document["ts"].GetString())));
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["bp"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["bq"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
{
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(data["ap"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(data["aq"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
const char* bidsName = "b";
int bidIndex = 0;
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
for (const auto& x : data[bidsName].GetArray()) {
if (bidIndex >= maxMarketDepth) {
break;
}
std::string type = document["type"].GetString();
marketDataMessage.recapType = type == "snapshot" ? MarketDataMessage::RecapType::SOLICITED : MarketDataMessage::RecapType::NONE;
for (const auto& x : data["b"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
++bidIndex;
}
const char* asksName = "a";
int askIndex = 0;
for (const auto& x : data[asksName].GetArray()) {
if (askIndex >= maxMarketDepth) {
break;
}
for (const auto& x : data["a"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
++askIndex;
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId == CCAPI_WEBSOCKET_BYBIT_CHANNEL_TRADE) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(data["p"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(data["q"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(data["v"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, data["m"].GetBool() ? "0" : "1"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
for (const auto& x : data.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(x["T"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["p"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["v"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["i"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["S"].GetString()) == "Buy" ? "0" : "1"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (channelId.rfind(CCAPI_WEBSOCKET_BYBIT_CHANNEL_KLINE_2, 0) == 0) {
for (const auto& x : data.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(x["start"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x["open"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x["high"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x["low"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x["close"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x["volume"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, x["turnover"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
}
@@ -213,7 +221,8 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
case Request::Operation::GENERIC_PUBLIC_REQUEST: {
MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential);
} break;
case Request::Operation::GET_RECENT_TRADES: {
case Request::Operation::GET_RECENT_TRADES:
case Request::Operation::GET_HISTORICAL_TRADES: {
req.method(http::verb::get);
auto target = this->getRecentTradesTarget;
std::string queryString;
@@ -225,55 +234,160 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
req.method(http::verb::get);
auto target = this->getRecentCandlesticksTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS, "interval"},
{CCAPI_LIMIT, "limit"},
{CCAPI_START_TIME_SECONDS, "start"},
{CCAPI_END_TIME_SECONDS, "end"},
},
{
{CCAPI_CANDLESTICK_INTERVAL_SECONDS,
[that = shared_from_base<MarketDataServiceBybit>()](const std::string& input) {
return that->convertCandlestickIntervalSecondsToInterval(std::stoi(input));
}},
{CCAPI_START_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBybit>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
{CCAPI_END_TIME_SECONDS, [that = shared_from_base<MarketDataServiceBybit>()](
const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_MARKET_DEPTH: {
req.method(http::verb::get);
auto target = this->getMarketDepthTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentsTarget;
req.target(target);
auto target = this->getInstrumentTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "category"},
});
if (!symbolId.empty()) {
this->appendSymbolId(queryString, symbolId, "symbol");
}
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENTS: {
req.method(http::verb::get);
auto target = this->getInstrumentsTarget;
req.target(target);
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "category"},
});
req.target(target + "?" + queryString);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractInstrumentInfo(Element& element, const rj::Value& x) {
element.insert(CCAPI_INSTRUMENT, x["name"].GetString());
void extractInstrumentInfo(Element& element, const rj::Value& x, const std::string& category) {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["minPricePrecision"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["basePrecision"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["minTradeQty"].GetString());
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["minTradeAmt"].GetString());
auto it = x.FindMember("settleCoin");
if (it != x.MemberEnd()) {
element.insert(CCAPI_MARGIN_ASSET, it->value.GetString());
}
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["priceFilter"]["tickSize"].GetString());
if (category == "spot") {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSizeFilter"]["basePrecision"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["lotSizeFilter"]["minOrderQty"].GetString());
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["lotSizeFilter"]["minOrderAmt"].GetString());
} else if (category == "linear" || category == "inverse") {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSizeFilter"]["qtyStep"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["lotSizeFilter"]["minOrderQty"].GetString());
element.insert(CCAPI_ORDER_PRICE_TIMES_QUANTITY_MIN, x["lotSizeFilter"]["minNotionalValue"].GetString());
} else if (category == "option") {
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSizeFilter"]["qtyStep"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["lotSizeFilter"]["minOrderQty"].GetString());
}
}
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
switch (request.getOperation()) {
case Request::Operation::GET_RECENT_TRADES: {
case Request::Operation::GET_RECENT_TRADES:
case Request::Operation::GET_HISTORICAL_TRADES: {
for (const auto& x : document["result"]["list"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["qty"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, x["isBuyerMaker"].GetString() ? "0" : "1"});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["size"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["side"].GetString()) == "sell" ? "0" : "1"});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, x["execId"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_RECENT_CANDLESTICKS:
case Request::Operation::GET_HISTORICAL_CANDLESTICKS: {
for (const auto& x : document["result"]["list"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x[0].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[1].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, x[6].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_MARKET_DEPTH: {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
const rj::Value& result = document["result"];
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(result["ts"].GetString()));
for (const auto& x : result["b"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
for (const auto& x : result["a"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
std::string category = document["result"]["category"].GetString();
for (const auto& x : document["result"]["list"].GetArray()) {
if (std::string(x["name"].GetString()) == request.getInstrument()) {
if (std::string(x["symbol"].GetString()) == request.getInstrument()) {
Element element;
this->extractInstrumentInfo(element, x);
this->extractInstrumentInfo(element, x, category);
message.setElementList({element});
break;
}
@@ -285,10 +399,11 @@ class MarketDataServiceBybit : public MarketDataServiceBybitBase {
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
std::string category = document["result"]["category"].GetString();
std::vector<Element> elementList;
for (const auto& x : document["result"]["list"].GetArray()) {
Element element;
this->extractInstrumentInfo(element, x);
this->extractInstrumentInfo(element, x, category);
elementList.push_back(element);
}
message.setElementList(elementList);
@@ -1,27 +0,0 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_BASE_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_BASE_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#if defined(CCAPI_ENABLE_EXCHANGE_BYBIT) || defined(CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES)
#include "ccapi_cpp/service/ccapi_market_data_service.h"
namespace ccapi {
class MarketDataServiceBybitBase : public MarketDataService {
public:
MarketDataServiceBybitBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~MarketDataServiceBybitBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("retCode":0)") == std::string::npos; }
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"op":"ping"})", wspp::frame::opcode::text, ec); }
#else
void pingOnApplicationLevel(std::shared_ptr<WsConnection> wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); }
#endif
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_BASE_H_
@@ -1,326 +0,0 @@
#ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_DERIVATIVES_H_
#define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_DERIVATIVES_H_
#ifdef CCAPI_ENABLE_SERVICE_MARKET_DATA
#ifdef CCAPI_ENABLE_EXCHANGE_BYBIT_DERIVATIVES
#include "ccapi_cpp/service/ccapi_market_data_service_bybit_base.h"
namespace ccapi {
class MarketDataServiceBybitDerivatives : public MarketDataServiceBybitBase {
public:
MarketDataServiceBybitDerivatives(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
: MarketDataServiceBybitBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/{instrumentTypeSubstitute}/public/v3";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
this->getRecentTradesTarget = "/derivatives/v3/public/recent-trade";
this->getInstrumentTarget = "/derivatives/v3/public/instruments-info";
this->getInstrumentsTarget = "/derivatives/v3/public/instruments-info";
}
virtual ~MarketDataServiceBybitDerivatives() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
std::string getInstrumentGroup(const Subscription& subscription) override {
const auto& instrumentType = subscription.getInstrumentType();
std::string instrumentTypeSubstitute;
if (instrumentType == "usdt-contract") {
instrumentTypeSubstitute = "contract/usdt";
} else if (instrumentType == "usdc-contract") {
instrumentTypeSubstitute = "contract/usdc";
} else if (instrumentType == "usdc-options") {
instrumentTypeSubstitute = "option/usdc";
}
std::string url = MarketDataService::getInstrumentGroup(subscription);
std::string toReplace("{instrumentTypeSubstitute}");
url.replace(url.find(toReplace), toReplace.length(), instrumentTypeSubstitute);
return url;
}
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
const auto& marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
const auto& instrumentType = subscription.getInstrumentType();
if (field == CCAPI_MARKET_DEPTH) {
std::vector<int> depths;
if (instrumentType == "usdc-options") {
depths = {25, 100};
} else {
depths = {1, 50, 200};
}
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, depths);
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
std::vector<std::string> sendStringList;
std::vector<std::string> exchangeSubscriptionIdList;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("op", rj::Value("subscribe").Move(), allocator);
rj::Value args(rj::kArrayType);
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListByInstrument.first;
std::string exchangeSubscriptionId;
if (channelId.rfind(CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK, 0) == 0) {
int marketDepthSubscribedToExchange =
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
exchangeSubscriptionId = CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK;
std::string toReplace = "{depth}";
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), std::to_string(marketDepthSubscribedToExchange));
} else if (channelId == CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE) {
exchangeSubscriptionId = CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE;
}
std::string toReplace = "{symbol}";
exchangeSubscriptionId.replace(exchangeSubscriptionId.find(toReplace), toReplace.length(), symbolId);
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
args.PushBack(rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator);
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
}
}
document.AddMember("args", args, allocator);
document.AddMember("req_id", rj::Value(std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).c_str(), allocator).Move(), allocator);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
#endif
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
if (document.IsObject() && document.HasMember("op")) {
std::string op = document["op"].GetString();
if (op == "subscribe") {
bool success = document["success"].GetBool();
event.setType(Event::Type::SUBSCRIPTION_STATUS);
std::vector<Message> messageList;
Message message;
message.setTimeReceived(timeReceived);
std::vector<std::string> correlationIdList;
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
int id = std::stoi(document["req_id"].GetString());
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) {
std::vector<std::string> correlationIdList_2 =
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end());
}
}
}
}
}
message.setCorrelationIdList(correlationIdList);
message.setType(success ? Message::Type::SUBSCRIPTION_STARTED : Message::Type::SUBSCRIPTION_FAILURE);
Element element;
element.insert(success ? CCAPI_INFO_MESSAGE : CCAPI_ERROR_MESSAGE, textMessage);
message.setElementList({element});
messageList.emplace_back(std::move(message));
event.setMessageList(messageList);
}
} else if (document.IsObject() && document.HasMember("data")) {
std::string exchangeSubscriptionId = document["topic"].GetString();
std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
auto optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
const rj::Value& data = document["data"];
if (channelId.rfind(CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_ORDERBOOK, 0) == 0) {
MarketDataMessage marketDataMessage;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(document["ts"].GetString())));
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
std::string type = document["type"].GetString();
marketDataMessage.recapType = type == "snapshot" ? MarketDataMessage::RecapType::SOLICITED : MarketDataMessage::RecapType::NONE;
for (const auto& x : data["b"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
for (const auto& x : data["a"].GetArray()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(x[0].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(x[1].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId == CCAPI_WEBSOCKET_BYBIT_DERIVATIVES_CHANNEL_TRADE) {
for (const auto& x : data.GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(x["T"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["p"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["v"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["i"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["S"].GetString()) == "Buy" ? "0" : "1"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
}
void convertRequestForRest(http::request<http::string_body>& req, const Request& request, const TimePoint& now, const std::string& symbolId,
const std::map<std::string, std::string>& credential) override {
switch (request.getOperation()) {
case Request::Operation::GENERIC_PUBLIC_REQUEST: {
MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential);
} break;
case Request::Operation::GET_RECENT_TRADES: {
req.method(http::verb::get);
auto target = this->getRecentTradesTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_LIMIT, "limit"},
});
this->appendSymbolId(queryString, symbolId, "symbol");
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENT: {
req.method(http::verb::get);
auto target = this->getInstrumentTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "category"},
});
if (!symbolId.empty()) {
this->appendSymbolId(queryString, symbolId, "symbol");
}
req.target(target + "?" + queryString);
} break;
case Request::Operation::GET_INSTRUMENTS: {
req.method(http::verb::get);
auto target = this->getInstrumentsTarget;
std::string queryString;
const std::map<std::string, std::string> param = request.getFirstParamWithDefault();
this->appendParam(queryString, param,
{
{CCAPI_INSTRUMENT_TYPE, "category"},
});
req.target(target + "?" + queryString);
} break;
default:
this->convertRequestForRestCustom(req, request, now, symbolId, credential);
}
}
void extractInstrumentInfo(Element& element, const rj::Value& x) {
element.insert(CCAPI_INSTRUMENT, x["symbol"].GetString());
element.insert(CCAPI_BASE_ASSET, x["baseCoin"].GetString());
element.insert(CCAPI_QUOTE_ASSET, x["quoteCoin"].GetString());
auto it = x.FindMember("settleCoin");
if (it != x.MemberEnd()) {
element.insert(CCAPI_MARGIN_ASSET, it->value.GetString());
}
element.insert(CCAPI_ORDER_PRICE_INCREMENT, x["priceFilter"]["tickSize"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_INCREMENT, x["lotSizeFilter"]["qtyStep"].GetString());
element.insert(CCAPI_ORDER_QUANTITY_MIN, x["lotSizeFilter"]["minTradingQty"].GetString());
}
void convertTextMessageToMarketDataMessage(const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Event& event,
std::vector<MarketDataMessage>& marketDataMessageList) override {
rj::Document document;
document.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
switch (request.getOperation()) {
case Request::Operation::GET_RECENT_TRADES: {
for (const auto& x : document["result"]["list"].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x["time"].GetString()));
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(x["size"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(x["side"].GetString()) == "sell" ? "0" : "1"});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, x["execId"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} break;
case Request::Operation::GET_INSTRUMENT: {
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
for (const auto& x : document["result"]["list"].GetArray()) {
if (std::string(x["symbol"].GetString()) == request.getInstrument()) {
Element element;
this->extractInstrumentInfo(element, x);
message.setElementList({element});
break;
}
}
message.setCorrelationIdList({request.getCorrelationId()});
event.addMessages({message});
} break;
case Request::Operation::GET_INSTRUMENTS: {
Message message;
message.setTimeReceived(timeReceived);
message.setType(this->requestOperationToMessageTypeMap.at(request.getOperation()));
std::vector<Element> elementList;
for (const auto& x : document["result"]["list"].GetArray()) {
Element element;
this->extractInstrumentInfo(element, x);
elementList.push_back(element);
}
message.setElementList(elementList);
message.setCorrelationIdList({request.getCorrelationId()});
event.addMessages({message});
} break;
default:
CCAPI_LOGGER_FATAL(CCAPI_UNSUPPORTED_VALUE);
}
}
};
} /* namespace ccapi */
#endif
#endif
#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_MARKET_DATA_SERVICE_BYBIT_DERIVATIVES_H_
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceCoinbase : public MarketDataService {
public:
MarketDataServiceCoinbase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_COINBASE;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/products/<product-id>/trades";
this->getInstrumentTarget = "/products/<product-id>";
this->getInstrumentsTarget = "/products";
@@ -75,14 +75,14 @@ class MarketDataServiceCoinbase : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceCryptocom : public MarketDataService {
public:
MarketDataServiceCryptocom(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_CRYPTOCOM;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v2/market";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/v2/public/get-trades";
this->getInstrumentTarget = "/v2/public/get-instruments";
this->getInstrumentsTarget = "/v2/public/get-instruments";
@@ -41,7 +41,7 @@ class MarketDataServiceCryptocom : public MarketDataService {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
if (field == CCAPI_MARKET_DEPTH) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({10, 150}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({10, 150}));
channelId = CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_BOOK;
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
@@ -101,14 +101,14 @@ class MarketDataServiceCryptocom : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -219,7 +219,7 @@ class MarketDataServiceCryptocom : public MarketDataService {
} else if (method == "public/heartbeat") {
std::string msg = R"({"id":)" + id + R"(,"method":"public/respond-heartbeat"})";
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(wsConnection.hdl, msg, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, msg, ec);
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceDeribit : public MarketDataService {
public:
MarketDataServiceDeribit(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_DERIBIT;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/api/v2";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->restTarget = "/api/v2";
this->getRecentTradesTarget = "/public/get_last_trades_by_instrument";
this->getInstrumentTarget = "/public/get_instrument";
@@ -37,7 +37,7 @@ class MarketDataServiceDeribit : public MarketDataService {
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onOpen(wspp::connection_hdl hdl) override {
MarketDataService::onOpen(hdl);
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
@@ -45,25 +45,10 @@ class MarketDataServiceDeribit : public MarketDataService {
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
auto now = UtilTime::now();
//////////////////////////////////////////////////
// BEGIN - BTS Custom Code
//////////////////////////////////////////////////
const auto rpcId = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
const auto hbInterval = 10;
CCAPI_LOGGER_INFO(
"MarketDataServiceDeribit::onOpen. Setting heartbeat interval."
"interval = " + toString(hbInterval) + ". "
"rpcId = " + toString(rpcId));
activeReqs.insert(rpcId);
this->appendParam(document, allocator, rpcId, "public/set_heartbeat",
this->appendParam(document, allocator, std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count(), "public/set_heartbeat",
{
{"interval", toString(hbInterval)},
{"interval", "10"},
});
//////////////////////////////////////////////////
// END - BTS Custom Code
//////////////////////////////////////////////////
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
@@ -113,7 +98,7 @@ class MarketDataServiceDeribit : public MarketDataService {
channelId = CCAPI_WEBSOCKET_DERIBIT_CHANNEL_QUOTE;
} else if (marketDepthRequested <= 20) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({10, 20}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({10, 20}));
channelId = CCAPI_WEBSOCKET_DERIBIT_CHANNEL_BOOK;
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
} else {
@@ -188,83 +173,15 @@ class MarketDataServiceDeribit : public MarketDataService {
sendStringList.push_back(sendString);
return sendStringList;
}
//////////////////////////////////////////////////
// BEGIN - BTS Custom Code
//////////////////////////////////////////////////
std::unordered_set<std::int64_t> activeHeartbeatReqs;
std::unordered_set<std::int64_t> activeReqs;
template <class T>
static std::pair<T, bool> readJson(rapidjson::Document &doc, const std::string &key);
static bool isHeartbeatRequest(const std::string &textMessage) {
rj::Document doc;
doc.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
auto resultIt = doc.FindMember("result");
if (resultIt != doc.MemberEnd()) {
return false;
}
auto paramsIt = doc.FindMember("params");
if (paramsIt == doc.MemberEnd() || !paramsIt->value.IsObject()) {
return false;
}
const auto params = paramsIt->value.GetObject();
auto typeIt = params.FindMember("type");
if (typeIt == params.MemberEnd() || !typeIt->value.IsString()) {
return false;
}
const std::string type{typeIt->value.GetString()};
if (type != "test_request") {
return false;
}
return true;
}
void sendHeartbeat(wspp::connection_hdl hdl) {
CCAPI_LOGGER_TRACE("MarketDataServiceDeribit::sendHeartbeat");
rj::Document document;
document.SetObject();
rj::Document::AllocatorType &allocator = document.GetAllocator();
auto now = UtilTime::now();
const auto rpcId = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
appendParam(document, allocator, rpcId, "/public/test", {});
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string msg = stringBuffer.GetString();
ErrorCode ec;
static const std::size_t MAX_ACTIVE_HEARTBEATS = 32;
if (activeHeartbeatReqs.size() > MAX_ACTIVE_HEARTBEATS) {
CCAPI_LOGGER_WARN("MarketDataServiceDeribit::sendHeartbeat. Too many active heartbeat reqs ("
+ std::to_string(activeHeartbeatReqs.size()) + "): "
+ ccapi::toString(activeHeartbeatReqs));
activeHeartbeatReqs.clear();
}
activeHeartbeatReqs.insert(rpcId);
CCAPI_LOGGER_INFO("MarketDataServiceDeribit::sendHeartbeat. Sending heartbeat rpcId: " + std::to_string(rpcId));
this->send(hdl, msg, wspp::frame::opcode::text, ec);
if (ec) {
this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "request");
}
}
void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override;
//////////////////////////////////////////////////
// END - BTS Custom Code
//////////////////////////////////////////////////
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -387,7 +304,7 @@ class MarketDataServiceDeribit : public MarketDataService {
document.Accept(writer);
std::string msg = stringBuffer.GetString();
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(hdl, msg, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, msg, ec);
@@ -600,79 +517,6 @@ class MarketDataServiceDeribit : public MarketDataService {
std::map<std::string, std::set<int64_t>> subscriptionJsonrpcIdSetByConnectionIdMap;
std::string restTarget;
};
//////////////////////////////////////////////////
// BEGIN - BTS Custom Code
//////////////////////////////////////////////////
template <>
inline std::pair<std::string, bool> MarketDataServiceDeribit::readJson<std::string>(rapidjson::Document &doc, const std::string &key) {
auto member = doc.FindMember(key.c_str());
if (member == doc.MemberEnd() || !member->value.IsString()) {
return {{}, false};
}
return {member->value.GetString(), true};
}
template <>
inline std::pair<std::int64_t, bool> MarketDataServiceDeribit::readJson<std::int64_t>(rapidjson::Document &doc, const std::string &key) {
auto member = doc.FindMember(key.c_str());
if (member == doc.MemberEnd()) {
return {0, false};
}
const auto &v = member->value;
if (v.IsInt64()) {
return {v.GetInt64(), true};
}
if (v.IsInt()) {
return {v.GetInt(), true};
}
if (v.IsUint64()) {
return {static_cast<std::int64_t>(v.GetUint64()), true};
}
if (v.IsUint()) {
return {static_cast<std::int64_t>(v.GetUint()), true};
}
if (v.IsString()) {
const char *cstr = v.GetString();
char* endPtr;
const std::int64_t result = std::strtol(cstr, &endPtr, 10);
if (*endPtr == '\0') {
return {result, true};
}
}
return {0, false};
}
inline void MarketDataServiceDeribit::onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) {
if (isHeartbeatRequest(textMessage)) {
sendHeartbeat(hdl);
return;
}
rj::Document doc;
doc.Parse<rj::kParseNumbersAsStringsFlag>(textMessage.c_str());
const auto [rpcId, hasRpcId] = readJson<std::int64_t>(doc, "id");
if (hasRpcId) {
if (activeHeartbeatReqs.erase(rpcId) != 0) {
return;
}
const auto [resStr, hasResStr] = readJson<std::string>(doc, "result");
if (hasResStr && resStr == "ok") {
if (activeReqs.erase(rpcId) == 0) {
CCAPI_LOGGER_ERROR("MarketDataServiceDeribit::onTextMessage. Received rpc response with unknown id:\n{}" + textMessage);
} else {
CCAPI_LOGGER_DEBUG("MarketDataServiceDeribit::onTextMessage. Received rpc response:\n{}" + textMessage);
}
return;
}
}
MarketDataService::onTextMessage(hdl, textMessage, timeReceived);
}
//////////////////////////////////////////////////
// END - BTS Custom Code
//////////////////////////////////////////////////
} /* namespace ccapi */
#endif
#endif
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceErisx : public MarketDataService {
public:
MarketDataServiceErisx(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_ERISX;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
@@ -69,14 +69,14 @@ class MarketDataServiceErisx : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceFtx : public MarketDataServiceFtxBase {
public:
MarketDataServiceFtx(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_FTX;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
@@ -19,7 +19,7 @@ class MarketDataServiceFtx : public MarketDataServiceFtxBase {
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceFtxBase : public MarketDataService {
public:
MarketDataServiceFtxBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->shouldAlignSnapshot = true;
this->getRecentTradesTarget = "/api/markets/{market_name}/trades";
@@ -86,14 +86,14 @@ class MarketDataServiceFtxBase : public MarketDataService {
return intToHex(csCalc);
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceFtxUs : public MarketDataServiceFtxBase {
public:
MarketDataServiceFtxUs(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceFtxBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_FTX_US;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws";
@@ -19,7 +19,7 @@ class MarketDataServiceFtxUs : public MarketDataServiceFtxBase {
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceGateio : public MarketDataServiceGateioBase {
public:
MarketDataServiceGateio(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v4/";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_GATEIO_API_KEY;
this->setupCredential({this->apiKeyName});
std::string prefix = "/api/v4";
@@ -36,6 +36,7 @@ class MarketDataServiceGateio : public MarketDataServiceGateioBase {
this->websocketChannelTrades = CCAPI_WEBSOCKET_GATEIO_CHANNEL_TRADES;
this->websocketChannelBookTicker = CCAPI_WEBSOCKET_GATEIO_CHANNEL_BOOK_TICKER;
this->websocketChannelOrderBook = CCAPI_WEBSOCKET_GATEIO_CHANNEL_ORDER_BOOK;
this->websocketChannelCandlesticks = CCAPI_WEBSOCKET_GATEIO_CHANNEL_CANDLESTICKS;
this->symbolName = "currency_pair";
}
virtual ~MarketDataServiceGateio() {}
@@ -7,14 +7,14 @@ namespace ccapi {
class MarketDataServiceGateioBase : public MarketDataService {
public:
MarketDataServiceGateioBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {}
virtual ~MarketDataServiceGateioBase() {}
#ifndef CCAPI_EXPOSE_INTERNAL
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl,
@@ -32,19 +32,19 @@ class MarketDataServiceGateioBase : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
if (marketDepthRequested == 1) {
channelId = this->websocketChannelBookTicker;
} else {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
std::string updateSpeed;
if (this->isDerivatives) {
updateSpeed = "0";
} else {
if (conflateIntervalMilliSeconds < 1000) {
if (conflateIntervalMilliseconds < 1000) {
updateSpeed = "100ms";
} else {
updateSpeed = "1000ms";
@@ -55,6 +55,10 @@ class MarketDataServiceGateioBase : public MarketDataService {
}
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
} else if (field == CCAPI_CANDLESTICK) {
std::string interval =
this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), "s", "m", "h", "d", "w");
channelId = this->websocketChannelCandlesticks + interval;
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
@@ -62,20 +66,28 @@ class MarketDataServiceGateioBase : public MarketDataService {
std::vector<std::string> sendStringList;
for (const auto& subscriptionListByChannelIdSymbolId : this->subscriptionListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id)) {
auto channelId = subscriptionListByChannelIdSymbolId.first;
if (channelId == this->websocketChannelBookTicker || channelId == this->websocketChannelTrades) {
if (channelId == this->websocketChannelBookTicker || channelId == this->websocketChannelTrades ||
channelId.rfind(this->websocketChannelCandlesticks, 0) == 0) {
std::vector<std::string> exchangeSubscriptionIdList;
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
document.AddMember("time", rj::Value(UtilTime::getUnixTimestamp(now)).Move(), allocator);
document.AddMember("channel", rj::Value(channelId.c_str(), allocator).Move(), allocator);
std::string channel(channelId);
if (channelId.rfind(this->websocketChannelCandlesticks, 0) == 0) {
channel = this->websocketChannelCandlesticks;
}
document.AddMember("channel", rj::Value(channel.c_str(), allocator).Move(), allocator);
rj::Value payload(rj::kArrayType);
for (const auto& subscriptionListByInstrument : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListByInstrument.first;
if (channelId == this->websocketChannelBookTicker) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true;
}
if (channelId.rfind(this->websocketChannelCandlesticks, 0) == 0) {
payload.PushBack(rj::Value(std::string(channelId.substr(this->websocketChannelCandlesticks.length())).c_str(), allocator).Move(), allocator);
}
payload.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
std::string exchangeSubscriptionId = channelId + "|" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
@@ -83,13 +95,12 @@ class MarketDataServiceGateioBase : public MarketDataService {
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
}
document.AddMember("payload", payload, allocator);
if (!this->isDerivatives) {
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
}
// if (!this->isDerivatives) {
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
// }
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
@@ -121,15 +132,15 @@ class MarketDataServiceGateioBase : public MarketDataService {
std::string exchangeSubscriptionId = std::string(this->websocketChannelOrderBook) + "|" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
if (!this->isDerivatives) {
std::vector<std::string> exchangeSubscriptionIdList;
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
}
// if (!this->isDerivatives) {
std::vector<std::string> exchangeSubscriptionIdList;
exchangeSubscriptionIdList.push_back(exchangeSubscriptionId);
document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator);
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id]
[this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] =
exchangeSubscriptionIdList;
this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1;
// }
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
@@ -141,14 +152,14 @@ class MarketDataServiceGateioBase : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -165,20 +176,19 @@ class MarketDataServiceGateioBase : public MarketDataService {
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) {
int id = std::stoi(document["id"].GetString());
if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() &&
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) {
if (this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.find(wsConnection.id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.end() &&
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).find(id) !=
this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).end()) {
for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).at(id)) {
auto splitted = UtilString::split(exchangeSubscriptionId, '|');
std::string channelId = splitted.at(0);
std::string symbolId = splitted.at(1);
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).find(symbolId) !=
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).end()) {
std::vector<std::string> correlationIdList_2 =
this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).at(channelId).at(symbolId);
const auto& it = this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).lower_bound(channelId);
if (it != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).end()) {
const std::string& k = it->first;
if (k.compare(0, channelId.size(), channelId) == 0) {
std::vector<std::string> correlationIdList_2 = it->second.at(symbolId);
correlationIdList.insert(correlationIdList.end(), correlationIdList_2.begin(), correlationIdList_2.end());
}
}
@@ -199,124 +209,171 @@ class MarketDataServiceGateioBase : public MarketDataService {
if (eventType == "update" || eventType == "all") {
std::string channel = document["channel"].GetString();
const rj::Value& result = document["result"];
std::string symbol;
std::string originalChannelId(channel);
if (result.IsObject()) {
auto it = result.FindMember(symbolName.c_str());
auto its = result.FindMember("s");
symbol = it != result.MemberEnd() ? it->value.GetString() : (its != result.MemberEnd() ? its->value.GetString() : "");
}
MarketDataMessage marketDataMessage;
std::string exchangeSubscriptionId;
std::string channelId;
std::string symbolId;
std::map<std::string, std::string> optionMap;
if (!symbol.empty()) {
exchangeSubscriptionId = channel + "|" + symbol;
channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID];
symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID];
optionMap = this->optionMapByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId];
} else {
channelId = channel;
}
if (channelId == this->websocketChannelBookTicker) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(result["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
{
std::string p = result["b"].GetString();
if (!p.empty()) {
std::string channelId(originalChannelId);
std::string symbolId;
if (channel == this->websocketChannelCandlesticks) {
std::string n = result["n"].GetString();
auto first_of = n.find_first_of("_");
channelId = originalChannelId + n.substr(0, first_of);
symbolId = n.substr(first_of + 1);
} else {
auto it = result.FindMember(symbolName.c_str());
auto its = result.FindMember("s");
symbolId = it != result.MemberEnd() ? it->value.GetString() : (its != result.MemberEnd() ? its->value.GetString() : "");
}
MarketDataMessage marketDataMessage;
std::string exchangeSubscriptionId;
std::map<std::string, std::string> optionMap;
if (!symbolId.empty()) {
exchangeSubscriptionId = channelId + "|" + symbolId;
optionMap = (*this->optionMapByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).lower_bound("channelId")).second.at(symbolId);
}
if (channel == this->websocketChannelBookTicker) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(result["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
{
std::string p = result["b"].GetString();
if (!p.empty()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(p)});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(result["B"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
}
}
{
std::string p = result["a"].GetString();
if (!p.empty()) {
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(p)});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(result["A"].GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channel == this->websocketChannelOrderBook) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(result["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
int bidIndex = 0;
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
for (const auto& x : result["bids"].GetArray()) {
if (bidIndex >= maxMarketDepth) {
break;
}
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(p)});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(result["B"].GetString())});
dataPoint.insert(
{MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString((this->isDerivatives ? x["p"] : x[0]).GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString((this->isDerivatives ? x["s"] : x[1]).GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
++bidIndex;
}
}
{
std::string p = result["a"].GetString();
if (!p.empty()) {
int askIndex = 0;
for (const auto& x : result["asks"].GetArray()) {
if (askIndex >= maxMarketDepth) {
break;
}
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(p)});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(result["A"].GetString())});
dataPoint.insert(
{MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString((this->isDerivatives ? x["p"] : x[0]).GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString((this->isDerivatives ? x["s"] : x[1]).GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
++askIndex;
}
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId.rfind(this->websocketChannelOrderBook, 0) == 0) {
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH;
marketDataMessage.recapType = this->processedInitialSnapshotByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId]
? MarketDataMessage::RecapType::NONE
: MarketDataMessage::RecapType::SOLICITED;
marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(result["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
int bidIndex = 0;
int maxMarketDepth = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
for (const auto& x : result["bids"].GetArray()) {
if (bidIndex >= maxMarketDepth) {
break;
}
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString((this->isDerivatives ? x["p"] : x[0]).GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString((this->isDerivatives ? x["s"] : x[1]).GetString())});
marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint));
++bidIndex;
}
int askIndex = 0;
for (const auto& x : result["asks"].GetArray()) {
if (askIndex >= maxMarketDepth) {
break;
}
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString((this->isDerivatives ? x["p"] : x[0]).GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString((this->isDerivatives ? x["s"] : x[1]).GetString())});
marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint));
++askIndex;
}
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channelId == this->websocketChannelTrades) {
if (this->isDerivatives) {
for (const auto& x : result.GetArray()) {
symbol = x["contract"].GetString();
exchangeSubscriptionId = channel + "|" + symbol;
marketDataMessageList.emplace_back(std::move(marketDataMessage));
} else if (channel == this->websocketChannelTrades) {
if (!this->isDerivatives) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::makeTimePointMilli(UtilTime::divideMilli(x["create_time_ms"].GetString()));
marketDataMessage.tp = UtilTime::makeTimePointMilli(UtilTime::divideMilli(result["create_time_ms"].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
std::string size = x["size"].GetString();
std::string sizeAbs;
bool isBuyerMaker;
if (size.at(0) == '-') {
sizeAbs = size.substr(1);
isBuyerMaker = true;
} else {
sizeAbs = size;
isBuyerMaker = false;
}
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(sizeAbs)});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, isBuyerMaker ? "1" : "0"});
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(result["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(result["amount"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(result["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(result["side"].GetString()) == "sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else {
} else if (channel == this->websocketChannelCandlesticks) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::makeTimePointMilli(UtilTime::divideMilli(result["create_time_ms"].GetString()));
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = TimePoint(std::chrono::seconds(std::stoll(result["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(result["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(std::string(result["amount"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(result["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(result["side"].GetString()) == "sell" ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, result["o"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, result["h"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, result["l"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, result["c"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, result["a"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, result["v"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (result.IsArray()) {
if (channel == this->websocketChannelTrades) {
if (this->isDerivatives) {
for (const auto& x : result.GetArray()) {
std::string symbolId = x["contract"].GetString();
std::string exchangeSubscriptionId = channel + "|" + symbolId;
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
marketDataMessage.tp = UtilTime::makeTimePointMilli(UtilTime::divideMilli(x["create_time_ms"].GetString()));
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
MarketDataMessage::TypeForDataPoint dataPoint;
std::string size = x["size"].GetString();
std::string sizeAbs;
bool isBuyerMaker;
if (size.at(0) == '-') {
sizeAbs = size.substr(1);
isBuyerMaker = true;
} else {
sizeAbs = size;
isBuyerMaker = false;
}
dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, UtilString::normalizeDecimalString(std::string(x["price"].GetString()))});
dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, UtilString::normalizeDecimalString(sizeAbs)});
dataPoint.insert({MarketDataMessage::DataFieldType::TRADE_ID, std::string(x["id"].GetString())});
dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, isBuyerMaker ? "1" : "0"});
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
} else if (channel == this->websocketChannelCandlesticks) {
if (this->isDerivatives) {
for (const auto& x : result.GetArray()) {
std::string n = x["n"].GetString();
auto first_of = n.find_first_of("_");
std::string channelId = originalChannelId + n.substr(0, first_of);
std::string symbolId = n.substr(first_of + 1);
std::string exchangeSubscriptionId = channelId + "|" + symbolId;
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
marketDataMessage.tp = TimePoint(std::chrono::seconds(std::stoll(x["t"].GetString())));
marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x["o"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x["h"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x["l"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x["c"].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x["v"].GetString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
}
}
}
}
}
@@ -326,6 +383,7 @@ class MarketDataServiceGateioBase : public MarketDataService {
std::string websocketChannelTrades;
std::string websocketChannelBookTicker;
std::string websocketChannelOrderBook;
std::string websocketChannelCandlesticks;
};
} /* namespace ccapi */
#endif
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceGateioPerpetualFutures : public MarketDataServiceGateioBase {
public:
MarketDataServiceGateioPerpetualFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceGateioBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_GATEIO_PERPETUAL_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v4/ws/";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->apiKeyName = CCAPI_GATEIO_PERPETUAL_FUTURES_API_KEY;
this->setupCredential({this->apiKeyName});
std::string prefix = "/api/v4";
@@ -37,6 +37,7 @@ class MarketDataServiceGateioPerpetualFutures : public MarketDataServiceGateioBa
this->websocketChannelTrades = CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_TRADES;
this->websocketChannelBookTicker = CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_BOOK_TICKER;
this->websocketChannelOrderBook = CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_ORDER_BOOK;
this->websocketChannelCandlesticks = CCAPI_WEBSOCKET_GATEIO_PERPETUAL_FUTURES_CHANNEL_CANDLESTICKS;
this->symbolName = "contract";
}
virtual ~MarketDataServiceGateioPerpetualFutures() {}
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceGemini : public MarketDataService {
public:
MarketDataServiceGemini(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_GEMINI;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/v1/marketdata";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/v1/trades/:symbol";
this->getInstrumentTarget = "/v1/symbols/details/:symbol";
this->getInstrumentsTarget = "/v1/symbols";
@@ -39,7 +39,7 @@ class MarketDataServiceGemini : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
if (marketDepthRequested == 1) {
int marketDepthSubscribedToExchange = 1;
@@ -49,7 +49,7 @@ class MarketDataServiceGemini : public MarketDataService {
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override { return std::vector<std::string>(); }
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void onOpen(wspp::connection_hdl hdl) override {
MarketDataService::onOpen(hdl);
WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl));
@@ -131,7 +131,7 @@ class MarketDataServiceGemini : public MarketDataService {
if (marketDepthSubscribedToExchange == 1) {
this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnectionPtr->id][channelId][symbolId] = true;
}
auto exchangeSubscriptionId = wsConnectionPtr->url;
auto exchangeSubscriptionId = wsConnectionPtr->getUrl();
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnectionPtr->id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnectionPtr->id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
std::vector<std::string> correlationIdList_2 =
@@ -191,14 +191,14 @@ class MarketDataServiceGemini : public MarketDataService {
}
#endif
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -208,7 +208,7 @@ class MarketDataServiceGemini : public MarketDataService {
auto type = std::string(document["type"].GetString());
if (this->sessionOptions.enableCheckSequence) {
int sequence = std::stoi(document["socket_sequence"].GetString());
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
if (!this->checkSequence(wsConnection, sequence)) {
this->onOutOfSequence(wsConnection, sequence, hdl, textMessage, timeReceived, "");
return;
@@ -222,10 +222,10 @@ class MarketDataServiceGemini : public MarketDataService {
}
if (type == "update" && !document["events"].GetArray().Empty()) {
MarketDataMessage marketDataMessage;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
marketDataMessage.exchangeSubscriptionId = wsConnection.url;
#else
marketDataMessage.exchangeSubscriptionId = wsConnectionPtr->url;
marketDataMessage.exchangeSubscriptionId = wsConnectionPtr->getUrl();
#endif
TimePoint time = timeReceived;
auto it = document.FindMember("timestampms");
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceHuobi : public MarketDataServiceHuobiBase {
public:
MarketDataServiceHuobi(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceHuobiBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/market/history/trade";
this->getInstrumentTarget = "/v1/common/symbols";
this->getInstrumentsTarget = "/v1/common/symbols";
@@ -35,24 +35,19 @@ class MarketDataServiceHuobi : public MarketDataServiceHuobiBase {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
CCAPI_LOGGER_TRACE("");
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
CCAPI_LOGGER_TRACE("");
if (conflateIntervalMilliSeconds < 100) {
CCAPI_LOGGER_TRACE("");
if (conflateIntervalMilliseconds < 100) {
if (marketDepthRequested == 1) {
CCAPI_LOGGER_TRACE("");
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO;
} else {
CCAPI_LOGGER_TRACE("");
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BY_PRICE_REFRESH_UPDATE;
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({5, 10, 20}));
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
}
} else if (conflateIntervalMilliSeconds < 1000) {
} else if (conflateIntervalMilliseconds < 1000) {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO;
} else {
@@ -7,10 +7,10 @@ namespace ccapi {
class MarketDataServiceHuobiBase : public MarketDataService {
public:
MarketDataServiceHuobiBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->needDecompressWebsocketMessage = true;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
ErrorCode ec = this->inflater.init(false, 31);
#else
this->inflater.setWindowBitsOverride(31);
@@ -26,7 +26,7 @@ class MarketDataServiceHuobiBase : public MarketDataService {
protected:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl, "{\"ping\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + "}", wspp::frame::opcode::text, ec);
@@ -108,14 +108,14 @@ class MarketDataServiceHuobiBase : public MarketDataService {
return url + "|" + field + "|" + subscription.getSerializedOptions();
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -266,7 +266,7 @@ class MarketDataServiceHuobiBase : public MarketDataService {
payload += document["ping"].GetString();
payload += "}";
ErrorCode ec;
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
this->send(hdl, payload, wspp::frame::opcode::text, ec);
#else
this->send(wsConnectionPtr, payload, ec);
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceHuobiCoinSwap : public MarketDataServiceHuobiDerivativesBase {
public:
MarketDataServiceHuobiCoinSwap(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceHuobiDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI_COIN_SWAP;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/swap-ws";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = CCAPI_HUOBI_COIN_SWAP_GET_RECENT_TRADES_PATH;
this->getInstrumentTarget = "/swap-api/v1/swap_contract_info";
this->getInstrumentsTarget = "/swap-api/v1/swap_contract_info";
@@ -7,7 +7,7 @@ namespace ccapi {
class MarketDataServiceHuobiDerivativesBase : public MarketDataServiceHuobiBase {
public:
MarketDataServiceHuobiDerivativesBase(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceHuobiBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->isDerivatives = true;
}
@@ -15,9 +15,9 @@ class MarketDataServiceHuobiDerivativesBase : public MarketDataServiceHuobiBase
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
if (conflateIntervalMilliSeconds < 1000) {
if (conflateIntervalMilliseconds < 1000) {
if (marketDepthRequested == 1) {
channelId = CCAPI_WEBSOCKET_HUOBI_CHANNEL_MARKET_BBO;
} else {
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceHuobiUsdtSwap : public MarketDataServiceHuobiDerivativesBase {
public:
MarketDataServiceHuobiUsdtSwap(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceHuobiDerivativesBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_HUOBI_USDT_SWAP;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/linear-swap-ws";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = CCAPI_HUOBI_USDT_SWAP_GET_RECENT_TRADES_PATH;
this->getInstrumentTarget = "/linear-swap-api/v1/swap_contract_info";
this->getInstrumentsTarget = "/linear-swap-api/v1/swap_contract_info";
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceKraken : public MarketDataService {
public:
MarketDataServiceKraken(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
this->getRecentTradesTarget = "/0/public/Trades";
this->getInstrumentTarget = "/0/public/AssetPairs";
this->getInstrumentsTarget = "/0/public/AssetPairs";
@@ -37,7 +37,7 @@ class MarketDataServiceKraken : public MarketDataService {
private:
#endif
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override {
auto now = UtilTime::now();
this->send(hdl, "{\"reqid\":" + std::to_string(UtilTime::getUnixTimestamp(now)) + ",\"event\":\"ping\"}", wspp::frame::opcode::text, ec);
@@ -52,12 +52,15 @@ class MarketDataServiceKraken : public MarketDataService {
void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection,
const Subscription& subscription, const std::map<std::string, std::string> optionMap) override {
auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX));
auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS));
if (field == CCAPI_MARKET_DEPTH) {
int marketDepthSubscribedToExchange = 1;
marketDepthSubscribedToExchange = this->calculateMarketDepthSubscribedToExchange(marketDepthRequested, std::vector<int>({10, 25, 100, 500, 1000}));
marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector<int>({10, 25, 100, 500, 1000}));
channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange);
this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange;
} else if (field == CCAPI_CANDLESTICK) {
std::string interval = std::to_string(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)) / 60);
channelId += "-" + interval;
}
}
std::vector<std::string> createSendStringList(const WsConnection& wsConnection) override {
@@ -120,19 +123,43 @@ class MarketDataServiceKraken : public MarketDataService {
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
} else if (channelId.rfind(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC, 0) == 0) {
rj::Document document;
document.SetObject();
rj::Document::AllocatorType& allocator = document.GetAllocator();
document.AddMember("event", rj::Value("subscribe").Move(), allocator);
rj::Value instrument(rj::kArrayType);
for (const auto& subscriptionListBySymbolId : subscriptionListByChannelIdSymbolId.second) {
auto symbolId = subscriptionListBySymbolId.first;
std::string exchangeSubscriptionId = channelId + "|" + symbolId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId;
this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId;
instrument.PushBack(rj::Value(symbolId.c_str(), allocator).Move(), allocator);
}
document.AddMember("pair", instrument, allocator);
rj::Value subscription(rj::kObjectType);
subscription.AddMember("interval", rj::Value(std::stoi(channelId.substr(std::string(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC).length() + 1))).Move(),
allocator);
subscription.AddMember("name", rj::Value(std::string(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC).c_str(), allocator).Move(), allocator);
document.AddMember("subscription", subscription, allocator);
rj::StringBuffer stringBuffer;
rj::Writer<rj::StringBuffer> writer(stringBuffer);
document.Accept(writer);
std::string sendString = stringBuffer.GetString();
sendStringList.push_back(sendString);
}
}
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -220,10 +247,10 @@ class MarketDataServiceKraken : public MarketDataService {
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (channelNameWithSuffix == CCAPI_WEBSOCKET_KRAKEN_CHANNEL_TRADE) {
auto symbolId = std::string(document[documentSize - 1].GetString());
for (const auto& x : document[1].GetArray()) {
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE;
auto symbolId = std::string(document[documentSize - 1].GetString());
marketDataMessage.exchangeSubscriptionId = channelNameWithSuffix + "|" + symbolId;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
auto timePair = UtilTime::divide(std::string(x[2].GetString()));
@@ -237,6 +264,27 @@ class MarketDataServiceKraken : public MarketDataService {
marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (channelNameWithSuffix.rfind(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC, 0) == 0) {
int intervalSeconds = std::stoi(channelNameWithSuffix.substr(std::string(CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC).length() + 1)) * 60;
auto symbolId = std::string(document[documentSize - 1].GetString());
const rj::Value& x = document[1].GetArray();
MarketDataMessage marketDataMessage;
marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK;
marketDataMessage.exchangeSubscriptionId = channelNameWithSuffix + "|" + symbolId;
marketDataMessage.recapType = MarketDataMessage::RecapType::NONE;
auto timePair = UtilTime::divide(std::string(x[1].GetString()));
auto tp = TimePoint(std::chrono::duration<int64_t>(timePair.first - intervalSeconds));
marketDataMessage.tp = tp;
MarketDataMessage::TypeForDataPoint dataPoint;
dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[2].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[3].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[4].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[5].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[7].GetString()});
dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME,
Decimal(UtilString::printDoubleScientific(std::stod(x[6].GetString()) * std::stod(x[7].GetString()))).toString()});
marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint));
marketDataMessageList.emplace_back(std::move(marketDataMessage));
}
} else if (document.IsObject() && document.HasMember("event")) {
std::string eventPayload = std::string(document["event"].GetString());
@@ -252,6 +300,8 @@ class MarketDataServiceKraken : public MarketDataService {
std::string exchangeSubscriptionId = document["subscription"]["name"].GetString();
if (exchangeSubscriptionId == CCAPI_WEBSOCKET_KRAKEN_CHANNEL_BOOK) {
exchangeSubscriptionId += "-" + std::string(document["subscription"]["depth"].GetString());
} else if (exchangeSubscriptionId == CCAPI_WEBSOCKET_KRAKEN_CHANNEL_OHLC) {
exchangeSubscriptionId += "-" + std::string(document["subscription"]["interval"].GetString());
}
std::string symbolId = document["pair"].GetString();
exchangeSubscriptionId += "|" + symbolId;
@@ -7,26 +7,26 @@ namespace ccapi {
class MarketDataServiceKrakenFutures : public MarketDataService {
public:
MarketDataServiceKrakenFutures(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_KRAKEN_FUTURES;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws/v1";
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#else
try {
this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
#endif
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #endif
std::string prefix("/derivatives/api/v3");
this->getRecentTradesTarget = prefix + "/history";
this->getInstrumentTarget = prefix + "/instruments";
@@ -80,14 +80,14 @@ class MarketDataServiceKrakenFutures : public MarketDataService {
return sendStringList;
}
void processTextMessage(
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage
#else
std::shared_ptr<WsConnection> wsConnectionPtr, boost::beast::string_view textMessageView
#endif
,
const TimePoint& timeReceived, Event& event, std::vector<MarketDataMessage>& marketDataMessageList) override {
#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
#else
WsConnection& wsConnection = *wsConnectionPtr;
std::string textMessage(textMessageView);
@@ -7,19 +7,19 @@ namespace ccapi {
class MarketDataServiceKucoin : public MarketDataServiceKucoinBase {
public:
MarketDataServiceKucoin(std::function<void(Event&, Queue<Event>*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs,
std::shared_ptr<ServiceContext> serviceContextPtr)
ServiceContext* serviceContextPtr)
: MarketDataServiceKucoinBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {
this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN;
this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName);
this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName);
this->setHostRestFromUrlRest(this->baseUrlRest);
// this->setHostWsFromUrlWs(this->baseUrlWs);
try {
this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
} catch (const std::exception& e) {
CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
}
// #ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET
// try {
// this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest);
// } catch (const std::exception& e) {
// CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what());
// }
// #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP
// #else
// try {
// this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs);
@@ -32,16 +32,22 @@ class MarketDataServiceKucoin : public MarketDataServiceKucoinBase {
this->apiPassphraseName = CCAPI_KUCOIN_API_PASSPHRASE;
this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName});
this->getRecentTradesTarget = "/api/v1/market/histories";
this->getHistoricalTradesTarget = "/api/v1/market/histories";
this->getRecentCandlesticksTarget = "/api/v1/market/candles";
this->getHistoricalCandlesticksTarget = "/api/v1/market/candles";
this->getMarketDepthTarget = "/api/v1/market/orderbook/level2";
this->getInstrumentTarget = "/api/v1/symbols";
this->getInstrumentsTarget = "/api/v1/symbols";
this->channelMarketTicker = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_TICKER;
this->channelMarketLevel2Depth5 = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2DEPTH5;
this->channelMarketLevel2Depth50 = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2DEPTH50;
this->channelMarketLevel2 = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_LEVEL2;
this->channelMarketKlines = CCAPI_WEBSOCKET_KUCOIN_CHANNEL_MARKET_KLINES;
this->tickerSubject = "trade.ticker";
this->tickerBestBidPriceKey = "bestBid";
this->tickerBestAskPriceKey = "bestAsk";
this->matchSubject = "trade.l3match";
this->klineSubject = "trade.candles.update";
this->level2Subject = "level2";
this->recentTradesTimeKey = "time";
}
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more