diff --git a/linux/include/ccapi_cpp/ccapi_date.h b/linux/include/ccapi_cpp/ccapi_date.h deleted file mode 100644 index cbe214070..000000000 --- a/linux/include/ccapi_cpp/ccapi_date.h +++ /dev/null @@ -1,5580 +0,0 @@ -#ifndef INCLUDE_CCAPI_CPP_CCAPI_DATE_H_ -#define INCLUDE_CCAPI_CPP_CCAPI_DATE_H_ -// https://github.com/HowardHinnant/date/releases/tag/v3.0.0 - -// The MIT License (MIT) -// -// Copyright (c) 2015, 2016, 2017 Howard Hinnant -// Copyright (c) 2016 Adrian Colomitchi -// Copyright (c) 2017 Florian Dang -// Copyright (c) 2017 Paul Thompson -// Copyright (c) 2018, 2019 Tomasz KamiƄski -// Copyright (c) 2019 Jiangang Zhuang -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -// -// Our apologies. When the previous paragraph was written, lowercase had not yet -// been invented (that would involve another several millennia of evolution). -// We did not mean to shout. - -#ifndef HAS_STRING_VIEW -#if __cplusplus >= 201703 || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) -#define HAS_STRING_VIEW 1 -#else -#define HAS_STRING_VIEW 0 -#endif -#endif // HAS_STRING_VIEW - -#include -#include -#include -#include -#include -#if !(__cplusplus >= 201402) -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if HAS_STRING_VIEW -#include -#endif -#include -#include - -#ifdef __GNUC__ -#pragma GCC diagnostic push -#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 7) -#pragma GCC diagnostic ignored "-Wpedantic" -#endif -#if __GNUC__ < 5 -// GCC 4.9 Bug 61489 Wrong warning with -Wmissing-field-initializers -#pragma GCC diagnostic ignored "-Wmissing-field-initializers" -#endif -#endif - -#ifdef _MSC_VER -#pragma warning(push) -// warning C4127: conditional expression is constant -#pragma warning(disable : 4127) -#endif - -namespace date { - -//---------------+ -// Configuration | -//---------------+ - -#ifndef ONLY_C_LOCALE -#define ONLY_C_LOCALE 0 -#endif - -#if defined(_MSC_VER) && (!defined(__clang__) || (_MSC_VER < 1910)) -// MSVC -#ifndef _SILENCE_CXX17_UNCAUGHT_EXCEPTION_DEPRECATION_WARNING -#define _SILENCE_CXX17_UNCAUGHT_EXCEPTION_DEPRECATION_WARNING -#endif -#if _MSC_VER < 1910 -// before VS2017 -#define CONSTDATA const -#define CONSTCD11 -#define CONSTCD14 -#define NOEXCEPT _NOEXCEPT -#else -// VS2017 and later -#define CONSTDATA constexpr const -#define CONSTCD11 constexpr -#define CONSTCD14 constexpr -#define NOEXCEPT noexcept -#endif - -#elif defined(__SUNPRO_CC) && __SUNPRO_CC <= 0x5150 -// Oracle Developer Studio 12.6 and earlier -#define CONSTDATA constexpr const -#define CONSTCD11 constexpr -#define CONSTCD14 -#define NOEXCEPT noexcept - -#elif __cplusplus >= 201402 -// C++14 -#define CONSTDATA constexpr const -#define CONSTCD11 constexpr -#define CONSTCD14 constexpr -#define NOEXCEPT noexcept -#else -// C++11 -#define CONSTDATA constexpr const -#define CONSTCD11 constexpr -#define CONSTCD14 -#define NOEXCEPT noexcept -#endif - -#ifndef HAS_UNCAUGHT_EXCEPTIONS -#if __cplusplus > 201703 || (defined(_MSVC_LANG) && _MSVC_LANG > 201703L) -#define HAS_UNCAUGHT_EXCEPTIONS 1 -#else -#define HAS_UNCAUGHT_EXCEPTIONS 0 -#endif -#endif // HAS_UNCAUGHT_EXCEPTIONS - -#ifndef HAS_VOID_T -#if __cplusplus >= 201703 || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) -#define HAS_VOID_T 1 -#else -#define HAS_VOID_T 0 -#endif -#endif // HAS_VOID_T - -// Protect from Oracle sun macro -#ifdef sun -#undef sun -#endif - -// Work around for a NVCC compiler bug which causes it to fail -// to compile std::ratio_{multiply,divide} when used directly -// in the std::chrono::duration template instantiations below -namespace detail { -template -using ratio_multiply = decltype(std::ratio_multiply{}); - -template -using ratio_divide = decltype(std::ratio_divide{}); -} // namespace detail - -//-----------+ -// Interface | -//-----------+ - -// durations - -using days = std::chrono::duration, std::chrono::hours::period>>; - -using weeks = std::chrono::duration, days::period>>; - -using years = std::chrono::duration, days::period>>; - -using months = std::chrono::duration>>; - -// time_point - -template -using sys_time = std::chrono::time_point; - -using sys_days = sys_time; -using sys_seconds = sys_time; - -struct local_t {}; - -template -using local_time = std::chrono::time_point; - -using local_seconds = local_time; -using local_days = local_time; - -// types - -struct last_spec { - explicit last_spec() = default; -}; - -class day; -class month; -class year; - -class weekday; -class weekday_indexed; -class weekday_last; - -class month_day; -class month_day_last; -class month_weekday; -class month_weekday_last; - -class year_month; - -class year_month_day; -class year_month_day_last; -class year_month_weekday; -class year_month_weekday_last; - -// date composition operators - -CONSTCD11 year_month operator/(const year& y, const month& m) NOEXCEPT; -CONSTCD11 year_month operator/(const year& y, int m) NOEXCEPT; - -CONSTCD11 month_day operator/(const day& d, const month& m) NOEXCEPT; -CONSTCD11 month_day operator/(const day& d, int m) NOEXCEPT; -CONSTCD11 month_day operator/(const month& m, const day& d) NOEXCEPT; -CONSTCD11 month_day operator/(const month& m, int d) NOEXCEPT; -CONSTCD11 month_day operator/(int m, const day& d) NOEXCEPT; - -CONSTCD11 month_day_last operator/(const month& m, last_spec) NOEXCEPT; -CONSTCD11 month_day_last operator/(int m, last_spec) NOEXCEPT; -CONSTCD11 month_day_last operator/(last_spec, const month& m) NOEXCEPT; -CONSTCD11 month_day_last operator/(last_spec, int m) NOEXCEPT; - -CONSTCD11 month_weekday operator/(const month& m, const weekday_indexed& wdi) NOEXCEPT; -CONSTCD11 month_weekday operator/(int m, const weekday_indexed& wdi) NOEXCEPT; -CONSTCD11 month_weekday operator/(const weekday_indexed& wdi, const month& m) NOEXCEPT; -CONSTCD11 month_weekday operator/(const weekday_indexed& wdi, int m) NOEXCEPT; - -CONSTCD11 month_weekday_last operator/(const month& m, const weekday_last& wdl) NOEXCEPT; -CONSTCD11 month_weekday_last operator/(int m, const weekday_last& wdl) NOEXCEPT; -CONSTCD11 month_weekday_last operator/(const weekday_last& wdl, const month& m) NOEXCEPT; -CONSTCD11 month_weekday_last operator/(const weekday_last& wdl, int m) NOEXCEPT; - -CONSTCD11 year_month_day operator/(const year_month& ym, const day& d) NOEXCEPT; -CONSTCD11 year_month_day operator/(const year_month& ym, int d) NOEXCEPT; -CONSTCD11 year_month_day operator/(const year& y, const month_day& md) NOEXCEPT; -CONSTCD11 year_month_day operator/(int y, const month_day& md) NOEXCEPT; -CONSTCD11 year_month_day operator/(const month_day& md, const year& y) NOEXCEPT; -CONSTCD11 year_month_day operator/(const month_day& md, int y) NOEXCEPT; - -CONSTCD11 -year_month_day_last operator/(const year_month& ym, last_spec) NOEXCEPT; -CONSTCD11 -year_month_day_last operator/(const year& y, const month_day_last& mdl) NOEXCEPT; -CONSTCD11 -year_month_day_last operator/(int y, const month_day_last& mdl) NOEXCEPT; -CONSTCD11 -year_month_day_last operator/(const month_day_last& mdl, const year& y) NOEXCEPT; -CONSTCD11 -year_month_day_last operator/(const month_day_last& mdl, int y) NOEXCEPT; - -CONSTCD11 -year_month_weekday operator/(const year_month& ym, const weekday_indexed& wdi) NOEXCEPT; - -CONSTCD11 -year_month_weekday operator/(const year& y, const month_weekday& mwd) NOEXCEPT; - -CONSTCD11 -year_month_weekday operator/(int y, const month_weekday& mwd) NOEXCEPT; - -CONSTCD11 -year_month_weekday operator/(const month_weekday& mwd, const year& y) NOEXCEPT; - -CONSTCD11 -year_month_weekday operator/(const month_weekday& mwd, int y) NOEXCEPT; - -CONSTCD11 -year_month_weekday_last operator/(const year_month& ym, const weekday_last& wdl) NOEXCEPT; - -CONSTCD11 -year_month_weekday_last operator/(const year& y, const month_weekday_last& mwdl) NOEXCEPT; - -CONSTCD11 -year_month_weekday_last operator/(int y, const month_weekday_last& mwdl) NOEXCEPT; - -CONSTCD11 -year_month_weekday_last operator/(const month_weekday_last& mwdl, const year& y) NOEXCEPT; - -CONSTCD11 -year_month_weekday_last operator/(const month_weekday_last& mwdl, int y) NOEXCEPT; - -// Detailed interface - -// day - -class day { - unsigned char d_; - - public: - day() = default; - explicit CONSTCD11 day(unsigned d) NOEXCEPT; - - CONSTCD14 day& operator++() NOEXCEPT; - CONSTCD14 day operator++(int) NOEXCEPT; - CONSTCD14 day& operator--() NOEXCEPT; - CONSTCD14 day operator--(int) NOEXCEPT; - - CONSTCD14 day& operator+=(const days& d) NOEXCEPT; - CONSTCD14 day& operator-=(const days& d) NOEXCEPT; - - CONSTCD11 explicit operator unsigned() const NOEXCEPT; - CONSTCD11 bool ok() const NOEXCEPT; -}; - -CONSTCD11 bool operator==(const day& x, const day& y) NOEXCEPT; -CONSTCD11 bool operator!=(const day& x, const day& y) NOEXCEPT; -CONSTCD11 bool operator<(const day& x, const day& y) NOEXCEPT; -CONSTCD11 bool operator>(const day& x, const day& y) NOEXCEPT; -CONSTCD11 bool operator<=(const day& x, const day& y) NOEXCEPT; -CONSTCD11 bool operator>=(const day& x, const day& y) NOEXCEPT; - -CONSTCD11 day operator+(const day& x, const days& y) NOEXCEPT; -CONSTCD11 day operator+(const days& x, const day& y) NOEXCEPT; -CONSTCD11 day operator-(const day& x, const days& y) NOEXCEPT; -CONSTCD11 days operator-(const day& x, const day& y) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const day& d); - -// month - -class month { - unsigned char m_; - - public: - month() = default; - explicit CONSTCD11 month(unsigned m) NOEXCEPT; - - CONSTCD14 month& operator++() NOEXCEPT; - CONSTCD14 month operator++(int) NOEXCEPT; - CONSTCD14 month& operator--() NOEXCEPT; - CONSTCD14 month operator--(int) NOEXCEPT; - - CONSTCD14 month& operator+=(const months& m) NOEXCEPT; - CONSTCD14 month& operator-=(const months& m) NOEXCEPT; - - CONSTCD11 explicit operator unsigned() const NOEXCEPT; - CONSTCD11 bool ok() const NOEXCEPT; -}; - -CONSTCD11 bool operator==(const month& x, const month& y) NOEXCEPT; -CONSTCD11 bool operator!=(const month& x, const month& y) NOEXCEPT; -CONSTCD11 bool operator<(const month& x, const month& y) NOEXCEPT; -CONSTCD11 bool operator>(const month& x, const month& y) NOEXCEPT; -CONSTCD11 bool operator<=(const month& x, const month& y) NOEXCEPT; -CONSTCD11 bool operator>=(const month& x, const month& y) NOEXCEPT; - -CONSTCD14 month operator+(const month& x, const months& y) NOEXCEPT; -CONSTCD14 month operator+(const months& x, const month& y) NOEXCEPT; -CONSTCD14 month operator-(const month& x, const months& y) NOEXCEPT; -CONSTCD14 months operator-(const month& x, const month& y) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const month& m); - -// year - -class year { - short y_; - - public: - year() = default; - explicit CONSTCD11 year(int y) NOEXCEPT; - - CONSTCD14 year& operator++() NOEXCEPT; - CONSTCD14 year operator++(int) NOEXCEPT; - CONSTCD14 year& operator--() NOEXCEPT; - CONSTCD14 year operator--(int) NOEXCEPT; - - CONSTCD14 year& operator+=(const years& y) NOEXCEPT; - CONSTCD14 year& operator-=(const years& y) NOEXCEPT; - - CONSTCD11 year operator-() const NOEXCEPT; - CONSTCD11 year operator+() const NOEXCEPT; - - CONSTCD11 bool is_leap() const NOEXCEPT; - - CONSTCD11 explicit operator int() const NOEXCEPT; - CONSTCD11 bool ok() const NOEXCEPT; - - static CONSTCD11 year min() NOEXCEPT { return year{-32767}; } - static CONSTCD11 year max() NOEXCEPT { return year{32767}; } -}; - -CONSTCD11 bool operator==(const year& x, const year& y) NOEXCEPT; -CONSTCD11 bool operator!=(const year& x, const year& y) NOEXCEPT; -CONSTCD11 bool operator<(const year& x, const year& y) NOEXCEPT; -CONSTCD11 bool operator>(const year& x, const year& y) NOEXCEPT; -CONSTCD11 bool operator<=(const year& x, const year& y) NOEXCEPT; -CONSTCD11 bool operator>=(const year& x, const year& y) NOEXCEPT; - -CONSTCD11 year operator+(const year& x, const years& y) NOEXCEPT; -CONSTCD11 year operator+(const years& x, const year& y) NOEXCEPT; -CONSTCD11 year operator-(const year& x, const years& y) NOEXCEPT; -CONSTCD11 years operator-(const year& x, const year& y) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const year& y); - -// weekday - -class weekday { - unsigned char wd_; - - public: - weekday() = default; - explicit CONSTCD11 weekday(unsigned wd) NOEXCEPT; - CONSTCD14 weekday(const sys_days& dp) NOEXCEPT; - CONSTCD14 explicit weekday(const local_days& dp) NOEXCEPT; - - CONSTCD14 weekday& operator++() NOEXCEPT; - CONSTCD14 weekday operator++(int) NOEXCEPT; - CONSTCD14 weekday& operator--() NOEXCEPT; - CONSTCD14 weekday operator--(int) NOEXCEPT; - - CONSTCD14 weekday& operator+=(const days& d) NOEXCEPT; - CONSTCD14 weekday& operator-=(const days& d) NOEXCEPT; - - CONSTCD11 bool ok() const NOEXCEPT; - - CONSTCD11 unsigned c_encoding() const NOEXCEPT; - CONSTCD11 unsigned iso_encoding() const NOEXCEPT; - - CONSTCD11 weekday_indexed operator[](unsigned index) const NOEXCEPT; - CONSTCD11 weekday_last operator[](last_spec) const NOEXCEPT; - - private: - static CONSTCD14 unsigned char weekday_from_days(int z) NOEXCEPT; - - friend CONSTCD11 bool operator==(const weekday& x, const weekday& y) NOEXCEPT; - friend CONSTCD14 days operator-(const weekday& x, const weekday& y) NOEXCEPT; - friend CONSTCD14 weekday operator+(const weekday& x, const days& y) NOEXCEPT; - template - friend std::basic_ostream& operator<<(std::basic_ostream& os, const weekday& wd); - friend class weekday_indexed; -}; - -CONSTCD11 bool operator==(const weekday& x, const weekday& y) NOEXCEPT; -CONSTCD11 bool operator!=(const weekday& x, const weekday& y) NOEXCEPT; - -CONSTCD14 weekday operator+(const weekday& x, const days& y) NOEXCEPT; -CONSTCD14 weekday operator+(const days& x, const weekday& y) NOEXCEPT; -CONSTCD14 weekday operator-(const weekday& x, const days& y) NOEXCEPT; -CONSTCD14 days operator-(const weekday& x, const weekday& y) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const weekday& wd); - -// weekday_indexed - -class weekday_indexed { - unsigned char wd_ : 4; - unsigned char index_ : 4; - - public: - weekday_indexed() = default; - CONSTCD11 weekday_indexed(const date::weekday& wd, unsigned index) NOEXCEPT; - - CONSTCD11 date::weekday weekday() const NOEXCEPT; - CONSTCD11 unsigned index() const NOEXCEPT; - CONSTCD11 bool ok() const NOEXCEPT; -}; - -CONSTCD11 bool operator==(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT; -CONSTCD11 bool operator!=(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const weekday_indexed& wdi); - -// weekday_last - -class weekday_last { - date::weekday wd_; - - public: - explicit CONSTCD11 weekday_last(const date::weekday& wd) NOEXCEPT; - - CONSTCD11 date::weekday weekday() const NOEXCEPT; - CONSTCD11 bool ok() const NOEXCEPT; -}; - -CONSTCD11 bool operator==(const weekday_last& x, const weekday_last& y) NOEXCEPT; -CONSTCD11 bool operator!=(const weekday_last& x, const weekday_last& y) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const weekday_last& wdl); - -namespace detail { - -struct unspecified_month_disambiguator {}; - -} // namespace detail - -// year_month - -class year_month { - date::year y_; - date::month m_; - - public: - year_month() = default; - CONSTCD11 year_month(const date::year& y, const date::month& m) NOEXCEPT; - - CONSTCD11 date::year year() const NOEXCEPT; - CONSTCD11 date::month month() const NOEXCEPT; - - template - CONSTCD14 year_month& operator+=(const months& dm) NOEXCEPT; - template - CONSTCD14 year_month& operator-=(const months& dm) NOEXCEPT; - CONSTCD14 year_month& operator+=(const years& dy) NOEXCEPT; - CONSTCD14 year_month& operator-=(const years& dy) NOEXCEPT; - - CONSTCD11 bool ok() const NOEXCEPT; -}; - -CONSTCD11 bool operator==(const year_month& x, const year_month& y) NOEXCEPT; -CONSTCD11 bool operator!=(const year_month& x, const year_month& y) NOEXCEPT; -CONSTCD11 bool operator<(const year_month& x, const year_month& y) NOEXCEPT; -CONSTCD11 bool operator>(const year_month& x, const year_month& y) NOEXCEPT; -CONSTCD11 bool operator<=(const year_month& x, const year_month& y) NOEXCEPT; -CONSTCD11 bool operator>=(const year_month& x, const year_month& y) NOEXCEPT; - -template -CONSTCD14 year_month operator+(const year_month& ym, const months& dm) NOEXCEPT; -template -CONSTCD14 year_month operator+(const months& dm, const year_month& ym) NOEXCEPT; -template -CONSTCD14 year_month operator-(const year_month& ym, const months& dm) NOEXCEPT; - -CONSTCD11 months operator-(const year_month& x, const year_month& y) NOEXCEPT; -CONSTCD11 year_month operator+(const year_month& ym, const years& dy) NOEXCEPT; -CONSTCD11 year_month operator+(const years& dy, const year_month& ym) NOEXCEPT; -CONSTCD11 year_month operator-(const year_month& ym, const years& dy) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const year_month& ym); - -// month_day - -class month_day { - date::month m_; - date::day d_; - - public: - month_day() = default; - CONSTCD11 month_day(const date::month& m, const date::day& d) NOEXCEPT; - - CONSTCD11 date::month month() const NOEXCEPT; - CONSTCD11 date::day day() const NOEXCEPT; - - CONSTCD14 bool ok() const NOEXCEPT; -}; - -CONSTCD11 bool operator==(const month_day& x, const month_day& y) NOEXCEPT; -CONSTCD11 bool operator!=(const month_day& x, const month_day& y) NOEXCEPT; -CONSTCD11 bool operator<(const month_day& x, const month_day& y) NOEXCEPT; -CONSTCD11 bool operator>(const month_day& x, const month_day& y) NOEXCEPT; -CONSTCD11 bool operator<=(const month_day& x, const month_day& y) NOEXCEPT; -CONSTCD11 bool operator>=(const month_day& x, const month_day& y) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const month_day& md); - -// month_day_last - -class month_day_last { - date::month m_; - - public: - CONSTCD11 explicit month_day_last(const date::month& m) NOEXCEPT; - - CONSTCD11 date::month month() const NOEXCEPT; - CONSTCD11 bool ok() const NOEXCEPT; -}; - -CONSTCD11 bool operator==(const month_day_last& x, const month_day_last& y) NOEXCEPT; -CONSTCD11 bool operator!=(const month_day_last& x, const month_day_last& y) NOEXCEPT; -CONSTCD11 bool operator<(const month_day_last& x, const month_day_last& y) NOEXCEPT; -CONSTCD11 bool operator>(const month_day_last& x, const month_day_last& y) NOEXCEPT; -CONSTCD11 bool operator<=(const month_day_last& x, const month_day_last& y) NOEXCEPT; -CONSTCD11 bool operator>=(const month_day_last& x, const month_day_last& y) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const month_day_last& mdl); - -// month_weekday - -class month_weekday { - date::month m_; - date::weekday_indexed wdi_; - - public: - CONSTCD11 month_weekday(const date::month& m, const date::weekday_indexed& wdi) NOEXCEPT; - - CONSTCD11 date::month month() const NOEXCEPT; - CONSTCD11 date::weekday_indexed weekday_indexed() const NOEXCEPT; - - CONSTCD11 bool ok() const NOEXCEPT; -}; - -CONSTCD11 bool operator==(const month_weekday& x, const month_weekday& y) NOEXCEPT; -CONSTCD11 bool operator!=(const month_weekday& x, const month_weekday& y) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const month_weekday& mwd); - -// month_weekday_last - -class month_weekday_last { - date::month m_; - date::weekday_last wdl_; - - public: - CONSTCD11 month_weekday_last(const date::month& m, const date::weekday_last& wd) NOEXCEPT; - - CONSTCD11 date::month month() const NOEXCEPT; - CONSTCD11 date::weekday_last weekday_last() const NOEXCEPT; - - CONSTCD11 bool ok() const NOEXCEPT; -}; - -CONSTCD11 -bool operator==(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT; -CONSTCD11 -bool operator!=(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const month_weekday_last& mwdl); - -// class year_month_day - -class year_month_day { - date::year y_; - date::month m_; - date::day d_; - - public: - year_month_day() = default; - CONSTCD11 year_month_day(const date::year& y, const date::month& m, const date::day& d) NOEXCEPT; - CONSTCD14 year_month_day(const year_month_day_last& ymdl) NOEXCEPT; - - CONSTCD14 year_month_day(sys_days dp) NOEXCEPT; - CONSTCD14 explicit year_month_day(local_days dp) NOEXCEPT; - - template - CONSTCD14 year_month_day& operator+=(const months& m) NOEXCEPT; - template - CONSTCD14 year_month_day& operator-=(const months& m) NOEXCEPT; - CONSTCD14 year_month_day& operator+=(const years& y) NOEXCEPT; - CONSTCD14 year_month_day& operator-=(const years& y) NOEXCEPT; - - CONSTCD11 date::year year() const NOEXCEPT; - CONSTCD11 date::month month() const NOEXCEPT; - CONSTCD11 date::day day() const NOEXCEPT; - - CONSTCD14 operator sys_days() const NOEXCEPT; - CONSTCD14 explicit operator local_days() const NOEXCEPT; - CONSTCD14 bool ok() const NOEXCEPT; - - private: - static CONSTCD14 year_month_day from_days(days dp) NOEXCEPT; - CONSTCD14 days to_days() const NOEXCEPT; -}; - -CONSTCD11 bool operator==(const year_month_day& x, const year_month_day& y) NOEXCEPT; -CONSTCD11 bool operator!=(const year_month_day& x, const year_month_day& y) NOEXCEPT; -CONSTCD11 bool operator<(const year_month_day& x, const year_month_day& y) NOEXCEPT; -CONSTCD11 bool operator>(const year_month_day& x, const year_month_day& y) NOEXCEPT; -CONSTCD11 bool operator<=(const year_month_day& x, const year_month_day& y) NOEXCEPT; -CONSTCD11 bool operator>=(const year_month_day& x, const year_month_day& y) NOEXCEPT; - -template -CONSTCD14 year_month_day operator+(const year_month_day& ymd, const months& dm) NOEXCEPT; -template -CONSTCD14 year_month_day operator+(const months& dm, const year_month_day& ymd) NOEXCEPT; -template -CONSTCD14 year_month_day operator-(const year_month_day& ymd, const months& dm) NOEXCEPT; -CONSTCD11 year_month_day operator+(const year_month_day& ymd, const years& dy) NOEXCEPT; -CONSTCD11 year_month_day operator+(const years& dy, const year_month_day& ymd) NOEXCEPT; -CONSTCD11 year_month_day operator-(const year_month_day& ymd, const years& dy) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const year_month_day& ymd); - -// year_month_day_last - -class year_month_day_last { - date::year y_; - date::month_day_last mdl_; - - public: - CONSTCD11 year_month_day_last(const date::year& y, const date::month_day_last& mdl) NOEXCEPT; - - template - CONSTCD14 year_month_day_last& operator+=(const months& m) NOEXCEPT; - template - CONSTCD14 year_month_day_last& operator-=(const months& m) NOEXCEPT; - CONSTCD14 year_month_day_last& operator+=(const years& y) NOEXCEPT; - CONSTCD14 year_month_day_last& operator-=(const years& y) NOEXCEPT; - - CONSTCD11 date::year year() const NOEXCEPT; - CONSTCD11 date::month month() const NOEXCEPT; - CONSTCD11 date::month_day_last month_day_last() const NOEXCEPT; - CONSTCD14 date::day day() const NOEXCEPT; - - CONSTCD14 operator sys_days() const NOEXCEPT; - CONSTCD14 explicit operator local_days() const NOEXCEPT; - CONSTCD11 bool ok() const NOEXCEPT; -}; - -CONSTCD11 -bool operator==(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; -CONSTCD11 -bool operator!=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; -CONSTCD11 -bool operator<(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; -CONSTCD11 -bool operator>(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; -CONSTCD11 -bool operator<=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; -CONSTCD11 -bool operator>=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT; - -template -CONSTCD14 year_month_day_last operator+(const year_month_day_last& ymdl, const months& dm) NOEXCEPT; - -template -CONSTCD14 year_month_day_last operator+(const months& dm, const year_month_day_last& ymdl) NOEXCEPT; - -CONSTCD11 -year_month_day_last operator+(const year_month_day_last& ymdl, const years& dy) NOEXCEPT; - -CONSTCD11 -year_month_day_last operator+(const years& dy, const year_month_day_last& ymdl) NOEXCEPT; - -template -CONSTCD14 year_month_day_last operator-(const year_month_day_last& ymdl, const months& dm) NOEXCEPT; - -CONSTCD11 -year_month_day_last operator-(const year_month_day_last& ymdl, const years& dy) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const year_month_day_last& ymdl); - -// year_month_weekday - -class year_month_weekday { - date::year y_; - date::month m_; - date::weekday_indexed wdi_; - - public: - year_month_weekday() = default; - CONSTCD11 year_month_weekday(const date::year& y, const date::month& m, const date::weekday_indexed& wdi) NOEXCEPT; - CONSTCD14 year_month_weekday(const sys_days& dp) NOEXCEPT; - CONSTCD14 explicit year_month_weekday(const local_days& dp) NOEXCEPT; - - template - CONSTCD14 year_month_weekday& operator+=(const months& m) NOEXCEPT; - template - CONSTCD14 year_month_weekday& operator-=(const months& m) NOEXCEPT; - CONSTCD14 year_month_weekday& operator+=(const years& y) NOEXCEPT; - CONSTCD14 year_month_weekday& operator-=(const years& y) NOEXCEPT; - - CONSTCD11 date::year year() const NOEXCEPT; - CONSTCD11 date::month month() const NOEXCEPT; - CONSTCD11 date::weekday weekday() const NOEXCEPT; - CONSTCD11 unsigned index() const NOEXCEPT; - CONSTCD11 date::weekday_indexed weekday_indexed() const NOEXCEPT; - - CONSTCD14 operator sys_days() const NOEXCEPT; - CONSTCD14 explicit operator local_days() const NOEXCEPT; - CONSTCD14 bool ok() const NOEXCEPT; - - private: - static CONSTCD14 year_month_weekday from_days(days dp) NOEXCEPT; - CONSTCD14 days to_days() const NOEXCEPT; -}; - -CONSTCD11 -bool operator==(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT; -CONSTCD11 -bool operator!=(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT; - -template -CONSTCD14 year_month_weekday operator+(const year_month_weekday& ymwd, const months& dm) NOEXCEPT; - -template -CONSTCD14 year_month_weekday operator+(const months& dm, const year_month_weekday& ymwd) NOEXCEPT; - -CONSTCD11 -year_month_weekday operator+(const year_month_weekday& ymwd, const years& dy) NOEXCEPT; - -CONSTCD11 -year_month_weekday operator+(const years& dy, const year_month_weekday& ymwd) NOEXCEPT; - -template -CONSTCD14 year_month_weekday operator-(const year_month_weekday& ymwd, const months& dm) NOEXCEPT; - -CONSTCD11 -year_month_weekday operator-(const year_month_weekday& ymwd, const years& dy) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const year_month_weekday& ymwdi); - -// year_month_weekday_last - -class year_month_weekday_last { - date::year y_; - date::month m_; - date::weekday_last wdl_; - - public: - CONSTCD11 year_month_weekday_last(const date::year& y, const date::month& m, const date::weekday_last& wdl) NOEXCEPT; - - template - CONSTCD14 year_month_weekday_last& operator+=(const months& m) NOEXCEPT; - template - CONSTCD14 year_month_weekday_last& operator-=(const months& m) NOEXCEPT; - CONSTCD14 year_month_weekday_last& operator+=(const years& y) NOEXCEPT; - CONSTCD14 year_month_weekday_last& operator-=(const years& y) NOEXCEPT; - - CONSTCD11 date::year year() const NOEXCEPT; - CONSTCD11 date::month month() const NOEXCEPT; - CONSTCD11 date::weekday weekday() const NOEXCEPT; - CONSTCD11 date::weekday_last weekday_last() const NOEXCEPT; - - CONSTCD14 operator sys_days() const NOEXCEPT; - CONSTCD14 explicit operator local_days() const NOEXCEPT; - CONSTCD11 bool ok() const NOEXCEPT; - - private: - CONSTCD14 days to_days() const NOEXCEPT; -}; - -CONSTCD11 -bool operator==(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT; - -CONSTCD11 -bool operator!=(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT; - -template -CONSTCD14 year_month_weekday_last operator+(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT; - -template -CONSTCD14 year_month_weekday_last operator+(const months& dm, const year_month_weekday_last& ymwdl) NOEXCEPT; - -CONSTCD11 -year_month_weekday_last operator+(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT; - -CONSTCD11 -year_month_weekday_last operator+(const years& dy, const year_month_weekday_last& ymwdl) NOEXCEPT; - -template -CONSTCD14 year_month_weekday_last operator-(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT; - -CONSTCD11 -year_month_weekday_last operator-(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT; - -template -std::basic_ostream& operator<<(std::basic_ostream& os, const year_month_weekday_last& ymwdl); - -#if !defined(_MSC_VER) || (_MSC_VER >= 1900) -inline namespace literals { - -CONSTCD11 date::day operator"" _d(unsigned long long d) NOEXCEPT; -CONSTCD11 date::year operator"" _y(unsigned long long y) NOEXCEPT; - -} // namespace literals -#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) - -// CONSTDATA date::month January{1}; -// CONSTDATA date::month February{2}; -// CONSTDATA date::month March{3}; -// CONSTDATA date::month April{4}; -// CONSTDATA date::month May{5}; -// CONSTDATA date::month June{6}; -// CONSTDATA date::month July{7}; -// CONSTDATA date::month August{8}; -// CONSTDATA date::month September{9}; -// CONSTDATA date::month October{10}; -// CONSTDATA date::month November{11}; -// CONSTDATA date::month December{12}; -// -// CONSTDATA date::weekday Sunday{0u}; -// CONSTDATA date::weekday Monday{1u}; -// CONSTDATA date::weekday Tuesday{2u}; -// CONSTDATA date::weekday Wednesday{3u}; -// CONSTDATA date::weekday Thursday{4u}; -// CONSTDATA date::weekday Friday{5u}; -// CONSTDATA date::weekday Saturday{6u}; - -#if HAS_VOID_T - -template > -struct is_clock : std::false_type {}; - -template -struct is_clock> - : std::true_type {}; - -#endif // HAS_VOID_T - -//----------------+ -// Implementation | -//----------------+ - -// utilities -namespace detail { - -template > -class save_istream { - protected: - std::basic_ios& is_; - CharT fill_; - std::ios::fmtflags flags_; - std::streamsize width_; - std::basic_ostream* tie_; - std::locale loc_; - - public: - ~save_istream() { - is_.fill(fill_); - is_.flags(flags_); - is_.width(width_); - is_.imbue(loc_); - is_.tie(tie_); - } - - save_istream(const save_istream&) = delete; - save_istream& operator=(const save_istream&) = delete; - - explicit save_istream(std::basic_ios& is) - : is_(is), fill_(is.fill()), flags_(is.flags()), width_(is.width(0)), tie_(is.tie(nullptr)), loc_(is.getloc()) { - if (tie_ != nullptr) tie_->flush(); - } -}; - -template > -class save_ostream : private save_istream { - public: - ~save_ostream() { - if ((this->flags_ & std::ios::unitbuf) && -#if HAS_UNCAUGHT_EXCEPTIONS - std::uncaught_exceptions() == 0 && -#else - !std::uncaught_exception() && -#endif - this->is_.good()) - this->is_.rdbuf()->pubsync(); - } - - save_ostream(const save_ostream&) = delete; - save_ostream& operator=(const save_ostream&) = delete; - - explicit save_ostream(std::basic_ios& os) : save_istream(os) {} -}; - -template -struct choose_trunc_type { - static const int digits = std::numeric_limits::digits; - using type = typename std::conditional < digits < 32, std::int32_t, - typename std::conditional::type>::type; -}; - -template -CONSTCD11 inline typename std::enable_if::value, T>::type trunc(T t) NOEXCEPT { - return t; -} - -template -CONSTCD14 inline typename std::enable_if::value, T>::type trunc(T t) NOEXCEPT { - using std::numeric_limits; - using I = typename choose_trunc_type::type; - CONSTDATA auto digits = numeric_limits::digits; - static_assert(digits < numeric_limits::digits, ""); - CONSTDATA auto max = I{1} << (digits - 1); - CONSTDATA auto min = -max; - const auto negative = t < T{0}; - if (min <= t && t <= max && t != 0 && t == t) { - t = static_cast(static_cast(t)); - if (t == 0 && negative) t = -t; - } - return t; -} - -template -struct static_gcd { - static const std::intmax_t value = static_gcd::value; -}; - -template -struct static_gcd { - static const std::intmax_t value = Xp; -}; - -template <> -struct static_gcd<0, 0> { - static const std::intmax_t value = 1; -}; - -template -struct no_overflow { - private: - static const std::intmax_t gcd_n1_n2 = static_gcd::value; - static const std::intmax_t gcd_d1_d2 = static_gcd::value; - static const std::intmax_t n1 = R1::num / gcd_n1_n2; - static const std::intmax_t d1 = R1::den / gcd_d1_d2; - static const std::intmax_t n2 = R2::num / gcd_n1_n2; - static const std::intmax_t d2 = R2::den / gcd_d1_d2; - static const std::intmax_t max = std::numeric_limits::max(); - - template - struct mul // overflow == false - { - static const std::intmax_t value = Xp * Yp; - }; - - template - struct mul { - static const std::intmax_t value = 1; - }; - - public: - static const bool value = (n1 <= max / d2) && (n2 <= max / d1); - typedef std::ratio::value, mul::value> type; -}; - -} // namespace detail - -// trunc towards zero -template -CONSTCD11 inline typename std::enable_if::value, To>::type trunc(const std::chrono::duration& d) { - return To{detail::trunc(std::chrono::duration_cast(d).count())}; -} - -template -CONSTCD11 inline typename std::enable_if::value, To>::type trunc( - const std::chrono::duration& d) { - using std::chrono::duration; - using std::chrono::duration_cast; - using rep = typename std::common_type::type; - return To{detail::trunc(duration_cast(duration_cast>(d)).count())}; -} - -#ifndef HAS_CHRONO_ROUNDING -#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 190023918 || (_MSC_FULL_VER >= 190000000 && defined(__clang__))) -#define HAS_CHRONO_ROUNDING 1 -#elif defined(__cpp_lib_chrono) && __cplusplus > 201402 && __cpp_lib_chrono >= 201510 -#define HAS_CHRONO_ROUNDING 1 -#elif defined(_LIBCPP_VERSION) && __cplusplus > 201402 && _LIBCPP_VERSION >= 3800 -#define HAS_CHRONO_ROUNDING 1 -#else -#define HAS_CHRONO_ROUNDING 0 -#endif -#endif // HAS_CHRONO_ROUNDING - -#if HAS_CHRONO_ROUNDING == 0 - -// round down -template -CONSTCD14 inline typename std::enable_if::value, To>::type floor(const std::chrono::duration& d) { - auto t = trunc(d); - if (t > d) return t - To{1}; - return t; -} - -template -CONSTCD14 inline typename std::enable_if::value, To>::type floor( - const std::chrono::duration& d) { - using rep = typename std::common_type::type; - return floor(floor>(d)); -} - -// round to nearest, to even on tie -template -CONSTCD14 inline To round(const std::chrono::duration& d) { - auto t0 = floor(d); - auto t1 = t0 + To{1}; - if (t1 == To{0} && t0 < To{0}) t1 = -t1; - auto diff0 = d - t0; - auto diff1 = t1 - d; - if (diff0 == diff1) { - if (t0 - trunc(t0 / 2) * 2 == To{0}) return t0; - return t1; - } - if (diff0 < diff1) return t0; - return t1; -} - -// round up -template -CONSTCD14 inline To ceil(const std::chrono::duration& d) { - auto t = trunc(d); - if (t < d) return t + To{1}; - return t; -} - -template ::is_signed>::type> -CONSTCD11 std::chrono::duration abs(std::chrono::duration d) { - return d >= d.zero() ? d : -d; -} - -// round down -template -CONSTCD11 inline std::chrono::time_point floor(const std::chrono::time_point& tp) { - using std::chrono::time_point; - return time_point{date::floor(tp.time_since_epoch())}; -} - -// round to nearest, to even on tie -template -CONSTCD11 inline std::chrono::time_point round(const std::chrono::time_point& tp) { - using std::chrono::time_point; - return time_point{round(tp.time_since_epoch())}; -} - -// round up -template -CONSTCD11 inline std::chrono::time_point ceil(const std::chrono::time_point& tp) { - using std::chrono::time_point; - return time_point{ceil(tp.time_since_epoch())}; -} - -#else // HAS_CHRONO_ROUNDING == 1 - -using std::chrono::abs; -using std::chrono::ceil; -using std::chrono::floor; -using std::chrono::round; - -#endif // HAS_CHRONO_ROUNDING - -// trunc towards zero -template -CONSTCD11 inline std::chrono::time_point trunc(const std::chrono::time_point& tp) { - using std::chrono::time_point; - return time_point{trunc(tp.time_since_epoch())}; -} - -// day - -CONSTCD11 inline day::day(unsigned d) NOEXCEPT : d_(static_cast(d)) {} -CONSTCD14 inline day& day::operator++() NOEXCEPT { - ++d_; - return *this; -} -CONSTCD14 inline day day::operator++(int) NOEXCEPT { - auto tmp(*this); - ++(*this); - return tmp; -} -CONSTCD14 inline day& day::operator--() NOEXCEPT { - --d_; - return *this; -} -CONSTCD14 inline day day::operator--(int) NOEXCEPT { - auto tmp(*this); - --(*this); - return tmp; -} -CONSTCD14 inline day& day::operator+=(const days& d) NOEXCEPT { - *this = *this + d; - return *this; -} -CONSTCD14 inline day& day::operator-=(const days& d) NOEXCEPT { - *this = *this - d; - return *this; -} -CONSTCD11 inline day::operator unsigned() const NOEXCEPT { return d_; } -CONSTCD11 inline bool day::ok() const NOEXCEPT { return 1 <= d_ && d_ <= 31; } - -CONSTCD11 -inline bool operator==(const day& x, const day& y) NOEXCEPT { return static_cast(x) == static_cast(y); } - -CONSTCD11 -inline bool operator!=(const day& x, const day& y) NOEXCEPT { return !(x == y); } - -CONSTCD11 -inline bool operator<(const day& x, const day& y) NOEXCEPT { return static_cast(x) < static_cast(y); } - -CONSTCD11 -inline bool operator>(const day& x, const day& y) NOEXCEPT { return y < x; } - -CONSTCD11 -inline bool operator<=(const day& x, const day& y) NOEXCEPT { return !(y < x); } - -CONSTCD11 -inline bool operator>=(const day& x, const day& y) NOEXCEPT { return !(x < y); } - -CONSTCD11 -inline days operator-(const day& x, const day& y) NOEXCEPT { return days{static_cast(static_cast(x) - static_cast(y))}; } - -CONSTCD11 -inline day operator+(const day& x, const days& y) NOEXCEPT { return day{static_cast(x) + static_cast(y.count())}; } - -CONSTCD11 -inline day operator+(const days& x, const day& y) NOEXCEPT { return y + x; } - -CONSTCD11 -inline day operator-(const day& x, const days& y) NOEXCEPT { return x + -y; } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const day& d) { - detail::save_ostream _(os); - os.fill('0'); - os.flags(std::ios::dec | std::ios::right); - os.width(2); - os << static_cast(d); - if (!d.ok()) os << " is not a valid day"; - return os; -} - -// month - -CONSTCD11 inline month::month(unsigned m) NOEXCEPT : m_(static_cast(m)) {} -CONSTCD14 inline month& month::operator++() NOEXCEPT { - *this += months{1}; - return *this; -} -CONSTCD14 inline month month::operator++(int) NOEXCEPT { - auto tmp(*this); - ++(*this); - return tmp; -} -CONSTCD14 inline month& month::operator--() NOEXCEPT { - *this -= months{1}; - return *this; -} -CONSTCD14 inline month month::operator--(int) NOEXCEPT { - auto tmp(*this); - --(*this); - return tmp; -} - -CONSTCD14 -inline month& month::operator+=(const months& m) NOEXCEPT { - *this = *this + m; - return *this; -} - -CONSTCD14 -inline month& month::operator-=(const months& m) NOEXCEPT { - *this = *this - m; - return *this; -} - -CONSTCD11 inline month::operator unsigned() const NOEXCEPT { return m_; } -CONSTCD11 inline bool month::ok() const NOEXCEPT { return 1 <= m_ && m_ <= 12; } - -CONSTCD11 -inline bool operator==(const month& x, const month& y) NOEXCEPT { return static_cast(x) == static_cast(y); } - -CONSTCD11 -inline bool operator!=(const month& x, const month& y) NOEXCEPT { return !(x == y); } - -CONSTCD11 -inline bool operator<(const month& x, const month& y) NOEXCEPT { return static_cast(x) < static_cast(y); } - -CONSTCD11 -inline bool operator>(const month& x, const month& y) NOEXCEPT { return y < x; } - -CONSTCD11 -inline bool operator<=(const month& x, const month& y) NOEXCEPT { return !(y < x); } - -CONSTCD11 -inline bool operator>=(const month& x, const month& y) NOEXCEPT { return !(x < y); } - -CONSTCD14 -inline months operator-(const month& x, const month& y) NOEXCEPT { - auto const d = static_cast(x) - static_cast(y); - return months(d <= 11 ? d : d + 12); -} - -CONSTCD14 -inline month operator+(const month& x, const months& y) NOEXCEPT { - auto const mu = static_cast(static_cast(x)) + y.count() - 1; - auto const yr = (mu >= 0 ? mu : mu - 11) / 12; - return month{static_cast(mu - yr * 12 + 1)}; -} - -CONSTCD14 -inline month operator+(const months& x, const month& y) NOEXCEPT { return y + x; } - -CONSTCD14 -inline month operator-(const month& x, const months& y) NOEXCEPT { return x + -y; } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const month& m) { - if (m.ok()) { - CharT fmt[] = {'%', 'b', 0}; - os << format(os.getloc(), fmt, m); - } else - os << static_cast(m) << " is not a valid month"; - return os; -} - -// year - -CONSTCD11 inline year::year(int y) NOEXCEPT : y_(static_cast(y)) {} -CONSTCD14 inline year& year::operator++() NOEXCEPT { - ++y_; - return *this; -} -CONSTCD14 inline year year::operator++(int) NOEXCEPT { - auto tmp(*this); - ++(*this); - return tmp; -} -CONSTCD14 inline year& year::operator--() NOEXCEPT { - --y_; - return *this; -} -CONSTCD14 inline year year::operator--(int) NOEXCEPT { - auto tmp(*this); - --(*this); - return tmp; -} -CONSTCD14 inline year& year::operator+=(const years& y) NOEXCEPT { - *this = *this + y; - return *this; -} -CONSTCD14 inline year& year::operator-=(const years& y) NOEXCEPT { - *this = *this - y; - return *this; -} -CONSTCD11 inline year year::operator-() const NOEXCEPT { return year{-y_}; } -CONSTCD11 inline year year::operator+() const NOEXCEPT { return *this; } - -CONSTCD11 -inline bool year::is_leap() const NOEXCEPT { return y_ % 4 == 0 && (y_ % 100 != 0 || y_ % 400 == 0); } - -CONSTCD11 inline year::operator int() const NOEXCEPT { return y_; } - -CONSTCD11 -inline bool year::ok() const NOEXCEPT { return y_ != std::numeric_limits::min(); } - -CONSTCD11 -inline bool operator==(const year& x, const year& y) NOEXCEPT { return static_cast(x) == static_cast(y); } - -CONSTCD11 -inline bool operator!=(const year& x, const year& y) NOEXCEPT { return !(x == y); } - -CONSTCD11 -inline bool operator<(const year& x, const year& y) NOEXCEPT { return static_cast(x) < static_cast(y); } - -CONSTCD11 -inline bool operator>(const year& x, const year& y) NOEXCEPT { return y < x; } - -CONSTCD11 -inline bool operator<=(const year& x, const year& y) NOEXCEPT { return !(y < x); } - -CONSTCD11 -inline bool operator>=(const year& x, const year& y) NOEXCEPT { return !(x < y); } - -CONSTCD11 -inline years operator-(const year& x, const year& y) NOEXCEPT { return years{static_cast(x) - static_cast(y)}; } - -CONSTCD11 -inline year operator+(const year& x, const years& y) NOEXCEPT { return year{static_cast(x) + y.count()}; } - -CONSTCD11 -inline year operator+(const years& x, const year& y) NOEXCEPT { return y + x; } - -CONSTCD11 -inline year operator-(const year& x, const years& y) NOEXCEPT { return year{static_cast(x) - y.count()}; } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const year& y) { - detail::save_ostream _(os); - os.fill('0'); - os.flags(std::ios::dec | std::ios::internal); - os.width(4 + (y < year{0})); - os.imbue(std::locale::classic()); - os << static_cast(y); - if (!y.ok()) os << " is not a valid year"; - return os; -} - -// weekday - -CONSTCD14 -inline unsigned char weekday::weekday_from_days(int z) NOEXCEPT { - auto u = static_cast(z); - return static_cast(z >= -4 ? (u + 4) % 7 : u % 7); -} - -CONSTCD11 -inline weekday::weekday(unsigned wd) NOEXCEPT : wd_(static_cast(wd != 7 ? wd : 0)) {} - -CONSTCD14 -inline weekday::weekday(const sys_days& dp) NOEXCEPT : wd_(weekday_from_days(dp.time_since_epoch().count())) {} - -CONSTCD14 -inline weekday::weekday(const local_days& dp) NOEXCEPT : wd_(weekday_from_days(dp.time_since_epoch().count())) {} - -CONSTCD14 inline weekday& weekday::operator++() NOEXCEPT { - *this += days{1}; - return *this; -} -CONSTCD14 inline weekday weekday::operator++(int) NOEXCEPT { - auto tmp(*this); - ++(*this); - return tmp; -} -CONSTCD14 inline weekday& weekday::operator--() NOEXCEPT { - *this -= days{1}; - return *this; -} -CONSTCD14 inline weekday weekday::operator--(int) NOEXCEPT { - auto tmp(*this); - --(*this); - return tmp; -} - -CONSTCD14 -inline weekday& weekday::operator+=(const days& d) NOEXCEPT { - *this = *this + d; - return *this; -} - -CONSTCD14 -inline weekday& weekday::operator-=(const days& d) NOEXCEPT { - *this = *this - d; - return *this; -} - -CONSTCD11 inline bool weekday::ok() const NOEXCEPT { return wd_ <= 6; } - -CONSTCD11 -inline unsigned weekday::c_encoding() const NOEXCEPT { return unsigned{wd_}; } - -CONSTCD11 -inline unsigned weekday::iso_encoding() const NOEXCEPT { return unsigned{((wd_ == 0u) ? 7u : wd_)}; } - -CONSTCD11 -inline bool operator==(const weekday& x, const weekday& y) NOEXCEPT { return x.wd_ == y.wd_; } - -CONSTCD11 -inline bool operator!=(const weekday& x, const weekday& y) NOEXCEPT { return !(x == y); } - -CONSTCD14 -inline days operator-(const weekday& x, const weekday& y) NOEXCEPT { - auto const wdu = x.wd_ - y.wd_; - auto const wk = (wdu >= 0 ? wdu : wdu - 6) / 7; - return days{wdu - wk * 7}; -} - -CONSTCD14 -inline weekday operator+(const weekday& x, const days& y) NOEXCEPT { - auto const wdu = static_cast(static_cast(x.wd_)) + y.count(); - auto const wk = (wdu >= 0 ? wdu : wdu - 6) / 7; - return weekday{static_cast(wdu - wk * 7)}; -} - -CONSTCD14 -inline weekday operator+(const days& x, const weekday& y) NOEXCEPT { return y + x; } - -CONSTCD14 -inline weekday operator-(const weekday& x, const days& y) NOEXCEPT { return x + -y; } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const weekday& wd) { - if (wd.ok()) { - CharT fmt[] = {'%', 'a', 0}; - os << format(fmt, wd); - } else - os << static_cast(wd.wd_) << " is not a valid weekday"; - return os; -} - -#if !defined(_MSC_VER) || (_MSC_VER >= 1900) -inline namespace literals { - -CONSTCD11 -inline date::day operator"" _d(unsigned long long d) NOEXCEPT { return date::day{static_cast(d)}; } - -CONSTCD11 -inline date::year operator"" _y(unsigned long long y) NOEXCEPT { return date::year(static_cast(y)); } -#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900) - -CONSTDATA date::last_spec last{}; - -CONSTDATA date::month jan{1}; -CONSTDATA date::month feb{2}; -CONSTDATA date::month mar{3}; -CONSTDATA date::month apr{4}; -CONSTDATA date::month may{5}; -CONSTDATA date::month jun{6}; -CONSTDATA date::month jul{7}; -CONSTDATA date::month aug{8}; -CONSTDATA date::month sep{9}; -CONSTDATA date::month oct{10}; -CONSTDATA date::month nov{11}; -CONSTDATA date::month dec{12}; - -CONSTDATA date::weekday sun{0u}; -CONSTDATA date::weekday mon{1u}; -CONSTDATA date::weekday tue{2u}; -CONSTDATA date::weekday wed{3u}; -CONSTDATA date::weekday thu{4u}; -CONSTDATA date::weekday fri{5u}; -CONSTDATA date::weekday sat{6u}; - -#if !defined(_MSC_VER) || (_MSC_VER >= 1900) -} // inline namespace literals -#endif - -CONSTDATA date::month January{1}; -CONSTDATA date::month February{2}; -CONSTDATA date::month March{3}; -CONSTDATA date::month April{4}; -CONSTDATA date::month May{5}; -CONSTDATA date::month June{6}; -CONSTDATA date::month July{7}; -CONSTDATA date::month August{8}; -CONSTDATA date::month September{9}; -CONSTDATA date::month October{10}; -CONSTDATA date::month November{11}; -CONSTDATA date::month December{12}; - -CONSTDATA date::weekday Monday{1}; -CONSTDATA date::weekday Tuesday{2}; -CONSTDATA date::weekday Wednesday{3}; -CONSTDATA date::weekday Thursday{4}; -CONSTDATA date::weekday Friday{5}; -CONSTDATA date::weekday Saturday{6}; -CONSTDATA date::weekday Sunday{7}; - -// weekday_indexed - -CONSTCD11 -inline weekday weekday_indexed::weekday() const NOEXCEPT { return date::weekday{static_cast(wd_)}; } - -CONSTCD11 inline unsigned weekday_indexed::index() const NOEXCEPT { return index_; } - -CONSTCD11 -inline bool weekday_indexed::ok() const NOEXCEPT { return weekday().ok() && 1 <= index_ && index_ <= 5; } - -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif // __GNUC__ - -CONSTCD11 -inline weekday_indexed::weekday_indexed(const date::weekday& wd, unsigned index) NOEXCEPT : wd_(static_cast(static_cast(wd.wd_))), - index_(static_cast(index)) {} - -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif // __GNUC__ - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const weekday_indexed& wdi) { - os << wdi.weekday() << '[' << wdi.index(); - if (!(1 <= wdi.index() && wdi.index() <= 5)) os << " is not a valid index"; - os << ']'; - return os; -} - -CONSTCD11 -inline weekday_indexed weekday::operator[](unsigned index) const NOEXCEPT { return {*this, index}; } - -CONSTCD11 -inline bool operator==(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT { return x.weekday() == y.weekday() && x.index() == y.index(); } - -CONSTCD11 -inline bool operator!=(const weekday_indexed& x, const weekday_indexed& y) NOEXCEPT { return !(x == y); } - -// weekday_last - -CONSTCD11 inline date::weekday weekday_last::weekday() const NOEXCEPT { return wd_; } -CONSTCD11 inline bool weekday_last::ok() const NOEXCEPT { return wd_.ok(); } -CONSTCD11 inline weekday_last::weekday_last(const date::weekday& wd) NOEXCEPT : wd_(wd) {} - -CONSTCD11 -inline bool operator==(const weekday_last& x, const weekday_last& y) NOEXCEPT { return x.weekday() == y.weekday(); } - -CONSTCD11 -inline bool operator!=(const weekday_last& x, const weekday_last& y) NOEXCEPT { return !(x == y); } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const weekday_last& wdl) { - return os << wdl.weekday() << "[last]"; -} - -CONSTCD11 -inline weekday_last weekday::operator[](last_spec) const NOEXCEPT { return weekday_last{*this}; } - -// year_month - -CONSTCD11 -inline year_month::year_month(const date::year& y, const date::month& m) NOEXCEPT : y_(y), m_(m) {} - -CONSTCD11 inline year year_month::year() const NOEXCEPT { return y_; } -CONSTCD11 inline month year_month::month() const NOEXCEPT { return m_; } -CONSTCD11 inline bool year_month::ok() const NOEXCEPT { return y_.ok() && m_.ok(); } - -template -CONSTCD14 inline year_month& year_month::operator+=(const months& dm) NOEXCEPT { - *this = *this + dm; - return *this; -} - -template -CONSTCD14 inline year_month& year_month::operator-=(const months& dm) NOEXCEPT { - *this = *this - dm; - return *this; -} - -CONSTCD14 -inline year_month& year_month::operator+=(const years& dy) NOEXCEPT { - *this = *this + dy; - return *this; -} - -CONSTCD14 -inline year_month& year_month::operator-=(const years& dy) NOEXCEPT { - *this = *this - dy; - return *this; -} - -CONSTCD11 -inline bool operator==(const year_month& x, const year_month& y) NOEXCEPT { return x.year() == y.year() && x.month() == y.month(); } - -CONSTCD11 -inline bool operator!=(const year_month& x, const year_month& y) NOEXCEPT { return !(x == y); } - -CONSTCD11 -inline bool operator<(const year_month& x, const year_month& y) NOEXCEPT { - return x.year() < y.year() ? true : (x.year() > y.year() ? false : (x.month() < y.month())); -} - -CONSTCD11 -inline bool operator>(const year_month& x, const year_month& y) NOEXCEPT { return y < x; } - -CONSTCD11 -inline bool operator<=(const year_month& x, const year_month& y) NOEXCEPT { return !(y < x); } - -CONSTCD11 -inline bool operator>=(const year_month& x, const year_month& y) NOEXCEPT { return !(x < y); } - -template -CONSTCD14 inline year_month operator+(const year_month& ym, const months& dm) NOEXCEPT { - auto dmi = static_cast(static_cast(ym.month())) - 1 + dm.count(); - auto dy = (dmi >= 0 ? dmi : dmi - 11) / 12; - dmi = dmi - dy * 12 + 1; - return (ym.year() + years(dy)) / month(static_cast(dmi)); -} - -template -CONSTCD14 inline year_month operator+(const months& dm, const year_month& ym) NOEXCEPT { - return ym + dm; -} - -template -CONSTCD14 inline year_month operator-(const year_month& ym, const months& dm) NOEXCEPT { - return ym + -dm; -} - -CONSTCD11 -inline months operator-(const year_month& x, const year_month& y) NOEXCEPT { - return (x.year() - y.year()) + months(static_cast(x.month()) - static_cast(y.month())); -} - -CONSTCD11 -inline year_month operator+(const year_month& ym, const years& dy) NOEXCEPT { return (ym.year() + dy) / ym.month(); } - -CONSTCD11 -inline year_month operator+(const years& dy, const year_month& ym) NOEXCEPT { return ym + dy; } - -CONSTCD11 -inline year_month operator-(const year_month& ym, const years& dy) NOEXCEPT { return ym + -dy; } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const year_month& ym) { - return os << ym.year() << '/' << ym.month(); -} - -// month_day - -CONSTCD11 -inline month_day::month_day(const date::month& m, const date::day& d) NOEXCEPT : m_(m), d_(d) {} - -CONSTCD11 inline date::month month_day::month() const NOEXCEPT { return m_; } -CONSTCD11 inline date::day month_day::day() const NOEXCEPT { return d_; } - -CONSTCD14 -inline bool month_day::ok() const NOEXCEPT { - CONSTDATA date::day d[] = {date::day(31), date::day(29), date::day(31), date::day(30), date::day(31), date::day(30), - date::day(31), date::day(31), date::day(30), date::day(31), date::day(30), date::day(31)}; - return m_.ok() && date::day{1} <= d_ && d_ <= d[static_cast(m_) - 1]; -} - -CONSTCD11 -inline bool operator==(const month_day& x, const month_day& y) NOEXCEPT { return x.month() == y.month() && x.day() == y.day(); } - -CONSTCD11 -inline bool operator!=(const month_day& x, const month_day& y) NOEXCEPT { return !(x == y); } - -CONSTCD11 -inline bool operator<(const month_day& x, const month_day& y) NOEXCEPT { - return x.month() < y.month() ? true : (x.month() > y.month() ? false : (x.day() < y.day())); -} - -CONSTCD11 -inline bool operator>(const month_day& x, const month_day& y) NOEXCEPT { return y < x; } - -CONSTCD11 -inline bool operator<=(const month_day& x, const month_day& y) NOEXCEPT { return !(y < x); } - -CONSTCD11 -inline bool operator>=(const month_day& x, const month_day& y) NOEXCEPT { return !(x < y); } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const month_day& md) { - return os << md.month() << '/' << md.day(); -} - -// month_day_last - -CONSTCD11 inline month month_day_last::month() const NOEXCEPT { return m_; } -CONSTCD11 inline bool month_day_last::ok() const NOEXCEPT { return m_.ok(); } -CONSTCD11 inline month_day_last::month_day_last(const date::month& m) NOEXCEPT : m_(m) {} - -CONSTCD11 -inline bool operator==(const month_day_last& x, const month_day_last& y) NOEXCEPT { return x.month() == y.month(); } - -CONSTCD11 -inline bool operator!=(const month_day_last& x, const month_day_last& y) NOEXCEPT { return !(x == y); } - -CONSTCD11 -inline bool operator<(const month_day_last& x, const month_day_last& y) NOEXCEPT { return x.month() < y.month(); } - -CONSTCD11 -inline bool operator>(const month_day_last& x, const month_day_last& y) NOEXCEPT { return y < x; } - -CONSTCD11 -inline bool operator<=(const month_day_last& x, const month_day_last& y) NOEXCEPT { return !(y < x); } - -CONSTCD11 -inline bool operator>=(const month_day_last& x, const month_day_last& y) NOEXCEPT { return !(x < y); } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const month_day_last& mdl) { - return os << mdl.month() << "/last"; -} - -// month_weekday - -CONSTCD11 -inline month_weekday::month_weekday(const date::month& m, const date::weekday_indexed& wdi) NOEXCEPT : m_(m), wdi_(wdi) {} - -CONSTCD11 inline month month_weekday::month() const NOEXCEPT { return m_; } - -CONSTCD11 -inline weekday_indexed month_weekday::weekday_indexed() const NOEXCEPT { return wdi_; } - -CONSTCD11 -inline bool month_weekday::ok() const NOEXCEPT { return m_.ok() && wdi_.ok(); } - -CONSTCD11 -inline bool operator==(const month_weekday& x, const month_weekday& y) NOEXCEPT { return x.month() == y.month() && x.weekday_indexed() == y.weekday_indexed(); } - -CONSTCD11 -inline bool operator!=(const month_weekday& x, const month_weekday& y) NOEXCEPT { return !(x == y); } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const month_weekday& mwd) { - return os << mwd.month() << '/' << mwd.weekday_indexed(); -} - -// month_weekday_last - -CONSTCD11 -inline month_weekday_last::month_weekday_last(const date::month& m, const date::weekday_last& wdl) NOEXCEPT : m_(m), wdl_(wdl) {} - -CONSTCD11 inline month month_weekday_last::month() const NOEXCEPT { return m_; } - -CONSTCD11 -inline weekday_last month_weekday_last::weekday_last() const NOEXCEPT { return wdl_; } - -CONSTCD11 -inline bool month_weekday_last::ok() const NOEXCEPT { return m_.ok() && wdl_.ok(); } - -CONSTCD11 -inline bool operator==(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT { - return x.month() == y.month() && x.weekday_last() == y.weekday_last(); -} - -CONSTCD11 -inline bool operator!=(const month_weekday_last& x, const month_weekday_last& y) NOEXCEPT { return !(x == y); } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const month_weekday_last& mwdl) { - return os << mwdl.month() << '/' << mwdl.weekday_last(); -} - -// year_month_day_last - -CONSTCD11 -inline year_month_day_last::year_month_day_last(const date::year& y, const date::month_day_last& mdl) NOEXCEPT : y_(y), mdl_(mdl) {} - -template -CONSTCD14 inline year_month_day_last& year_month_day_last::operator+=(const months& m) NOEXCEPT { - *this = *this + m; - return *this; -} - -template -CONSTCD14 inline year_month_day_last& year_month_day_last::operator-=(const months& m) NOEXCEPT { - *this = *this - m; - return *this; -} - -CONSTCD14 -inline year_month_day_last& year_month_day_last::operator+=(const years& y) NOEXCEPT { - *this = *this + y; - return *this; -} - -CONSTCD14 -inline year_month_day_last& year_month_day_last::operator-=(const years& y) NOEXCEPT { - *this = *this - y; - return *this; -} - -CONSTCD11 inline year year_month_day_last::year() const NOEXCEPT { return y_; } -CONSTCD11 inline month year_month_day_last::month() const NOEXCEPT { return mdl_.month(); } - -CONSTCD11 -inline month_day_last year_month_day_last::month_day_last() const NOEXCEPT { return mdl_; } - -CONSTCD14 -inline day year_month_day_last::day() const NOEXCEPT { - CONSTDATA date::day d[] = {date::day(31), date::day(28), date::day(31), date::day(30), date::day(31), date::day(30), - date::day(31), date::day(31), date::day(30), date::day(31), date::day(30), date::day(31)}; - return (month() != February || !y_.is_leap()) && mdl_.ok() ? d[static_cast(month()) - 1] : date::day{29}; -} - -CONSTCD14 -inline year_month_day_last::operator sys_days() const NOEXCEPT { return sys_days(year() / month() / day()); } - -CONSTCD14 -inline year_month_day_last::operator local_days() const NOEXCEPT { return local_days(year() / month() / day()); } - -CONSTCD11 -inline bool year_month_day_last::ok() const NOEXCEPT { return y_.ok() && mdl_.ok(); } - -CONSTCD11 -inline bool operator==(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT { - return x.year() == y.year() && x.month_day_last() == y.month_day_last(); -} - -CONSTCD11 -inline bool operator!=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT { return !(x == y); } - -CONSTCD11 -inline bool operator<(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT { - return x.year() < y.year() ? true : (x.year() > y.year() ? false : (x.month_day_last() < y.month_day_last())); -} - -CONSTCD11 -inline bool operator>(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT { return y < x; } - -CONSTCD11 -inline bool operator<=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT { return !(y < x); } - -CONSTCD11 -inline bool operator>=(const year_month_day_last& x, const year_month_day_last& y) NOEXCEPT { return !(x < y); } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const year_month_day_last& ymdl) { - return os << ymdl.year() << '/' << ymdl.month_day_last(); -} - -template -CONSTCD14 inline year_month_day_last operator+(const year_month_day_last& ymdl, const months& dm) NOEXCEPT { - return (ymdl.year() / ymdl.month() + dm) / last; -} - -template -CONSTCD14 inline year_month_day_last operator+(const months& dm, const year_month_day_last& ymdl) NOEXCEPT { - return ymdl + dm; -} - -template -CONSTCD14 inline year_month_day_last operator-(const year_month_day_last& ymdl, const months& dm) NOEXCEPT { - return ymdl + (-dm); -} - -CONSTCD11 -inline year_month_day_last operator+(const year_month_day_last& ymdl, const years& dy) NOEXCEPT { return {ymdl.year() + dy, ymdl.month_day_last()}; } - -CONSTCD11 -inline year_month_day_last operator+(const years& dy, const year_month_day_last& ymdl) NOEXCEPT { return ymdl + dy; } - -CONSTCD11 -inline year_month_day_last operator-(const year_month_day_last& ymdl, const years& dy) NOEXCEPT { return ymdl + (-dy); } - -// year_month_day - -CONSTCD11 -inline year_month_day::year_month_day(const date::year& y, const date::month& m, const date::day& d) NOEXCEPT : y_(y), m_(m), d_(d) {} - -CONSTCD14 -inline year_month_day::year_month_day(const year_month_day_last& ymdl) NOEXCEPT : y_(ymdl.year()), m_(ymdl.month()), d_(ymdl.day()) {} - -CONSTCD14 -inline year_month_day::year_month_day(sys_days dp) NOEXCEPT : year_month_day(from_days(dp.time_since_epoch())) {} - -CONSTCD14 -inline year_month_day::year_month_day(local_days dp) NOEXCEPT : year_month_day(from_days(dp.time_since_epoch())) {} - -CONSTCD11 inline year year_month_day::year() const NOEXCEPT { return y_; } -CONSTCD11 inline month year_month_day::month() const NOEXCEPT { return m_; } -CONSTCD11 inline day year_month_day::day() const NOEXCEPT { return d_; } - -template -CONSTCD14 inline year_month_day& year_month_day::operator+=(const months& m) NOEXCEPT { - *this = *this + m; - return *this; -} - -template -CONSTCD14 inline year_month_day& year_month_day::operator-=(const months& m) NOEXCEPT { - *this = *this - m; - return *this; -} - -CONSTCD14 -inline year_month_day& year_month_day::operator+=(const years& y) NOEXCEPT { - *this = *this + y; - return *this; -} - -CONSTCD14 -inline year_month_day& year_month_day::operator-=(const years& y) NOEXCEPT { - *this = *this - y; - return *this; -} - -CONSTCD14 -inline days year_month_day::to_days() const NOEXCEPT { - static_assert(std::numeric_limits::digits >= 18, "This algorithm has not been ported to a 16 bit unsigned integer"); - static_assert(std::numeric_limits::digits >= 20, "This algorithm has not been ported to a 16 bit signed integer"); - auto const y = static_cast(y_) - (m_ <= February); - auto const m = static_cast(m_); - auto const d = static_cast(d_); - auto const era = (y >= 0 ? y : y - 399) / 400; - auto const yoe = static_cast(y - era * 400); // [0, 399] - auto const doy = (153 * (m > 2 ? m - 3 : m + 9) + 2) / 5 + d - 1; // [0, 365] - auto const doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] - return days{era * 146097 + static_cast(doe) - 719468}; -} - -CONSTCD14 -inline year_month_day::operator sys_days() const NOEXCEPT { return sys_days{to_days()}; } - -CONSTCD14 -inline year_month_day::operator local_days() const NOEXCEPT { return local_days{to_days()}; } - -CONSTCD14 -inline bool year_month_day::ok() const NOEXCEPT { - if (!(y_.ok() && m_.ok())) return false; - return date::day{1} <= d_ && d_ <= (y_ / m_ / last).day(); -} - -CONSTCD11 -inline bool operator==(const year_month_day& x, const year_month_day& y) NOEXCEPT { - return x.year() == y.year() && x.month() == y.month() && x.day() == y.day(); -} - -CONSTCD11 -inline bool operator!=(const year_month_day& x, const year_month_day& y) NOEXCEPT { return !(x == y); } - -CONSTCD11 -inline bool operator<(const year_month_day& x, const year_month_day& y) NOEXCEPT { - return x.year() < y.year() ? true : (x.year() > y.year() ? false : (x.month() < y.month() ? true : (x.month() > y.month() ? false : (x.day() < y.day())))); -} - -CONSTCD11 -inline bool operator>(const year_month_day& x, const year_month_day& y) NOEXCEPT { return y < x; } - -CONSTCD11 -inline bool operator<=(const year_month_day& x, const year_month_day& y) NOEXCEPT { return !(y < x); } - -CONSTCD11 -inline bool operator>=(const year_month_day& x, const year_month_day& y) NOEXCEPT { return !(x < y); } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const year_month_day& ymd) { - detail::save_ostream _(os); - os.fill('0'); - os.flags(std::ios::dec | std::ios::right); - os.imbue(std::locale::classic()); - os << ymd.year() << '-'; - os.width(2); - os << static_cast(ymd.month()) << '-'; - os << ymd.day(); - if (!ymd.ok()) os << " is not a valid date"; - return os; -} - -CONSTCD14 -inline year_month_day year_month_day::from_days(days dp) NOEXCEPT { - static_assert(std::numeric_limits::digits >= 18, "This algorithm has not been ported to a 16 bit unsigned integer"); - static_assert(std::numeric_limits::digits >= 20, "This algorithm has not been ported to a 16 bit signed integer"); - auto const z = dp.count() + 719468; - auto const era = (z >= 0 ? z : z - 146096) / 146097; - auto const doe = static_cast(z - era * 146097); // [0, 146096] - auto const yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399] - auto const y = static_cast(yoe) + era * 400; - auto const doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365] - auto const mp = (5 * doy + 2) / 153; // [0, 11] - auto const d = doy - (153 * mp + 2) / 5 + 1; // [1, 31] - auto const m = mp < 10 ? mp + 3 : mp - 9; // [1, 12] - return year_month_day{date::year{y + (m <= 2)}, date::month(m), date::day(d)}; -} - -template -CONSTCD14 inline year_month_day operator+(const year_month_day& ymd, const months& dm) NOEXCEPT { - return (ymd.year() / ymd.month() + dm) / ymd.day(); -} - -template -CONSTCD14 inline year_month_day operator+(const months& dm, const year_month_day& ymd) NOEXCEPT { - return ymd + dm; -} - -template -CONSTCD14 inline year_month_day operator-(const year_month_day& ymd, const months& dm) NOEXCEPT { - return ymd + (-dm); -} - -CONSTCD11 -inline year_month_day operator+(const year_month_day& ymd, const years& dy) NOEXCEPT { return (ymd.year() + dy) / ymd.month() / ymd.day(); } - -CONSTCD11 -inline year_month_day operator+(const years& dy, const year_month_day& ymd) NOEXCEPT { return ymd + dy; } - -CONSTCD11 -inline year_month_day operator-(const year_month_day& ymd, const years& dy) NOEXCEPT { return ymd + (-dy); } - -// year_month_weekday - -CONSTCD11 -inline year_month_weekday::year_month_weekday(const date::year& y, const date::month& m, const date::weekday_indexed& wdi) NOEXCEPT : y_(y), m_(m), wdi_(wdi) {} - -CONSTCD14 -inline year_month_weekday::year_month_weekday(const sys_days& dp) NOEXCEPT : year_month_weekday(from_days(dp.time_since_epoch())) {} - -CONSTCD14 -inline year_month_weekday::year_month_weekday(const local_days& dp) NOEXCEPT : year_month_weekday(from_days(dp.time_since_epoch())) {} - -template -CONSTCD14 inline year_month_weekday& year_month_weekday::operator+=(const months& m) NOEXCEPT { - *this = *this + m; - return *this; -} - -template -CONSTCD14 inline year_month_weekday& year_month_weekday::operator-=(const months& m) NOEXCEPT { - *this = *this - m; - return *this; -} - -CONSTCD14 -inline year_month_weekday& year_month_weekday::operator+=(const years& y) NOEXCEPT { - *this = *this + y; - return *this; -} - -CONSTCD14 -inline year_month_weekday& year_month_weekday::operator-=(const years& y) NOEXCEPT { - *this = *this - y; - return *this; -} - -CONSTCD11 inline year year_month_weekday::year() const NOEXCEPT { return y_; } -CONSTCD11 inline month year_month_weekday::month() const NOEXCEPT { return m_; } - -CONSTCD11 -inline weekday year_month_weekday::weekday() const NOEXCEPT { return wdi_.weekday(); } - -CONSTCD11 -inline unsigned year_month_weekday::index() const NOEXCEPT { return wdi_.index(); } - -CONSTCD11 -inline weekday_indexed year_month_weekday::weekday_indexed() const NOEXCEPT { return wdi_; } - -CONSTCD14 -inline year_month_weekday::operator sys_days() const NOEXCEPT { return sys_days{to_days()}; } - -CONSTCD14 -inline year_month_weekday::operator local_days() const NOEXCEPT { return local_days{to_days()}; } - -CONSTCD14 -inline bool year_month_weekday::ok() const NOEXCEPT { - if (!y_.ok() || !m_.ok() || !wdi_.weekday().ok() || wdi_.index() < 1) return false; - if (wdi_.index() <= 4) return true; - auto d2 = wdi_.weekday() - date::weekday(static_cast(y_ / m_ / 1)) + days((wdi_.index() - 1) * 7 + 1); - return static_cast(d2.count()) <= static_cast((y_ / m_ / last).day()); -} - -CONSTCD14 -inline year_month_weekday year_month_weekday::from_days(days d) NOEXCEPT { - sys_days dp{d}; - auto const wd = date::weekday(dp); - auto const ymd = year_month_day(dp); - return {ymd.year(), ymd.month(), wd[(static_cast(ymd.day()) - 1) / 7 + 1]}; -} - -CONSTCD14 -inline days year_month_weekday::to_days() const NOEXCEPT { - auto d = sys_days(y_ / m_ / 1); - return (d + (wdi_.weekday() - date::weekday(d) + days{(wdi_.index() - 1) * 7})).time_since_epoch(); -} - -CONSTCD11 -inline bool operator==(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT { - return x.year() == y.year() && x.month() == y.month() && x.weekday_indexed() == y.weekday_indexed(); -} - -CONSTCD11 -inline bool operator!=(const year_month_weekday& x, const year_month_weekday& y) NOEXCEPT { return !(x == y); } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const year_month_weekday& ymwdi) { - return os << ymwdi.year() << '/' << ymwdi.month() << '/' << ymwdi.weekday_indexed(); -} - -template -CONSTCD14 inline year_month_weekday operator+(const year_month_weekday& ymwd, const months& dm) NOEXCEPT { - return (ymwd.year() / ymwd.month() + dm) / ymwd.weekday_indexed(); -} - -template -CONSTCD14 inline year_month_weekday operator+(const months& dm, const year_month_weekday& ymwd) NOEXCEPT { - return ymwd + dm; -} - -template -CONSTCD14 inline year_month_weekday operator-(const year_month_weekday& ymwd, const months& dm) NOEXCEPT { - return ymwd + (-dm); -} - -CONSTCD11 -inline year_month_weekday operator+(const year_month_weekday& ymwd, const years& dy) NOEXCEPT { - return {ymwd.year() + dy, ymwd.month(), ymwd.weekday_indexed()}; -} - -CONSTCD11 -inline year_month_weekday operator+(const years& dy, const year_month_weekday& ymwd) NOEXCEPT { return ymwd + dy; } - -CONSTCD11 -inline year_month_weekday operator-(const year_month_weekday& ymwd, const years& dy) NOEXCEPT { return ymwd + (-dy); } - -// year_month_weekday_last - -CONSTCD11 -inline year_month_weekday_last::year_month_weekday_last(const date::year& y, const date::month& m, const date::weekday_last& wdl) NOEXCEPT : y_(y), - m_(m), - wdl_(wdl) {} - -template -CONSTCD14 inline year_month_weekday_last& year_month_weekday_last::operator+=(const months& m) NOEXCEPT { - *this = *this + m; - return *this; -} - -template -CONSTCD14 inline year_month_weekday_last& year_month_weekday_last::operator-=(const months& m) NOEXCEPT { - *this = *this - m; - return *this; -} - -CONSTCD14 -inline year_month_weekday_last& year_month_weekday_last::operator+=(const years& y) NOEXCEPT { - *this = *this + y; - return *this; -} - -CONSTCD14 -inline year_month_weekday_last& year_month_weekday_last::operator-=(const years& y) NOEXCEPT { - *this = *this - y; - return *this; -} - -CONSTCD11 inline year year_month_weekday_last::year() const NOEXCEPT { return y_; } -CONSTCD11 inline month year_month_weekday_last::month() const NOEXCEPT { return m_; } - -CONSTCD11 -inline weekday year_month_weekday_last::weekday() const NOEXCEPT { return wdl_.weekday(); } - -CONSTCD11 -inline weekday_last year_month_weekday_last::weekday_last() const NOEXCEPT { return wdl_; } - -CONSTCD14 -inline year_month_weekday_last::operator sys_days() const NOEXCEPT { return sys_days{to_days()}; } - -CONSTCD14 -inline year_month_weekday_last::operator local_days() const NOEXCEPT { return local_days{to_days()}; } - -CONSTCD11 -inline bool year_month_weekday_last::ok() const NOEXCEPT { return y_.ok() && m_.ok() && wdl_.ok(); } - -CONSTCD14 -inline days year_month_weekday_last::to_days() const NOEXCEPT { - auto const d = sys_days(y_ / m_ / last); - return (d - (date::weekday{d} - wdl_.weekday())).time_since_epoch(); -} - -CONSTCD11 -inline bool operator==(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT { - return x.year() == y.year() && x.month() == y.month() && x.weekday_last() == y.weekday_last(); -} - -CONSTCD11 -inline bool operator!=(const year_month_weekday_last& x, const year_month_weekday_last& y) NOEXCEPT { return !(x == y); } - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const year_month_weekday_last& ymwdl) { - return os << ymwdl.year() << '/' << ymwdl.month() << '/' << ymwdl.weekday_last(); -} - -template -CONSTCD14 inline year_month_weekday_last operator+(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT { - return (ymwdl.year() / ymwdl.month() + dm) / ymwdl.weekday_last(); -} - -template -CONSTCD14 inline year_month_weekday_last operator+(const months& dm, const year_month_weekday_last& ymwdl) NOEXCEPT { - return ymwdl + dm; -} - -template -CONSTCD14 inline year_month_weekday_last operator-(const year_month_weekday_last& ymwdl, const months& dm) NOEXCEPT { - return ymwdl + (-dm); -} - -CONSTCD11 -inline year_month_weekday_last operator+(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT { - return {ymwdl.year() + dy, ymwdl.month(), ymwdl.weekday_last()}; -} - -CONSTCD11 -inline year_month_weekday_last operator+(const years& dy, const year_month_weekday_last& ymwdl) NOEXCEPT { return ymwdl + dy; } - -CONSTCD11 -inline year_month_weekday_last operator-(const year_month_weekday_last& ymwdl, const years& dy) NOEXCEPT { return ymwdl + (-dy); } - -// year_month from operator/() - -CONSTCD11 -inline year_month operator/(const year& y, const month& m) NOEXCEPT { return {y, m}; } - -CONSTCD11 -inline year_month operator/(const year& y, int m) NOEXCEPT { return y / month(static_cast(m)); } - -// month_day from operator/() - -CONSTCD11 -inline month_day operator/(const month& m, const day& d) NOEXCEPT { return {m, d}; } - -CONSTCD11 -inline month_day operator/(const day& d, const month& m) NOEXCEPT { return m / d; } - -CONSTCD11 -inline month_day operator/(const month& m, int d) NOEXCEPT { return m / day(static_cast(d)); } - -CONSTCD11 -inline month_day operator/(int m, const day& d) NOEXCEPT { return month(static_cast(m)) / d; } - -CONSTCD11 inline month_day operator/(const day& d, int m) NOEXCEPT { return m / d; } - -// month_day_last from operator/() - -CONSTCD11 -inline month_day_last operator/(const month& m, last_spec) NOEXCEPT { return month_day_last{m}; } - -CONSTCD11 -inline month_day_last operator/(last_spec, const month& m) NOEXCEPT { return m / last; } - -CONSTCD11 -inline month_day_last operator/(int m, last_spec) NOEXCEPT { return month(static_cast(m)) / last; } - -CONSTCD11 -inline month_day_last operator/(last_spec, int m) NOEXCEPT { return m / last; } - -// month_weekday from operator/() - -CONSTCD11 -inline month_weekday operator/(const month& m, const weekday_indexed& wdi) NOEXCEPT { return {m, wdi}; } - -CONSTCD11 -inline month_weekday operator/(const weekday_indexed& wdi, const month& m) NOEXCEPT { return m / wdi; } - -CONSTCD11 -inline month_weekday operator/(int m, const weekday_indexed& wdi) NOEXCEPT { return month(static_cast(m)) / wdi; } - -CONSTCD11 -inline month_weekday operator/(const weekday_indexed& wdi, int m) NOEXCEPT { return m / wdi; } - -// month_weekday_last from operator/() - -CONSTCD11 -inline month_weekday_last operator/(const month& m, const weekday_last& wdl) NOEXCEPT { return {m, wdl}; } - -CONSTCD11 -inline month_weekday_last operator/(const weekday_last& wdl, const month& m) NOEXCEPT { return m / wdl; } - -CONSTCD11 -inline month_weekday_last operator/(int m, const weekday_last& wdl) NOEXCEPT { return month(static_cast(m)) / wdl; } - -CONSTCD11 -inline month_weekday_last operator/(const weekday_last& wdl, int m) NOEXCEPT { return m / wdl; } - -// year_month_day from operator/() - -CONSTCD11 -inline year_month_day operator/(const year_month& ym, const day& d) NOEXCEPT { return {ym.year(), ym.month(), d}; } - -CONSTCD11 -inline year_month_day operator/(const year_month& ym, int d) NOEXCEPT { return ym / day(static_cast(d)); } - -CONSTCD11 -inline year_month_day operator/(const year& y, const month_day& md) NOEXCEPT { return y / md.month() / md.day(); } - -CONSTCD11 -inline year_month_day operator/(int y, const month_day& md) NOEXCEPT { return year(y) / md; } - -CONSTCD11 -inline year_month_day operator/(const month_day& md, const year& y) NOEXCEPT { return y / md; } - -CONSTCD11 -inline year_month_day operator/(const month_day& md, int y) NOEXCEPT { return year(y) / md; } - -// year_month_day_last from operator/() - -CONSTCD11 -inline year_month_day_last operator/(const year_month& ym, last_spec) NOEXCEPT { return {ym.year(), month_day_last{ym.month()}}; } - -CONSTCD11 -inline year_month_day_last operator/(const year& y, const month_day_last& mdl) NOEXCEPT { return {y, mdl}; } - -CONSTCD11 -inline year_month_day_last operator/(int y, const month_day_last& mdl) NOEXCEPT { return year(y) / mdl; } - -CONSTCD11 -inline year_month_day_last operator/(const month_day_last& mdl, const year& y) NOEXCEPT { return y / mdl; } - -CONSTCD11 -inline year_month_day_last operator/(const month_day_last& mdl, int y) NOEXCEPT { return year(y) / mdl; } - -// year_month_weekday from operator/() - -CONSTCD11 -inline year_month_weekday operator/(const year_month& ym, const weekday_indexed& wdi) NOEXCEPT { return {ym.year(), ym.month(), wdi}; } - -CONSTCD11 -inline year_month_weekday operator/(const year& y, const month_weekday& mwd) NOEXCEPT { return {y, mwd.month(), mwd.weekday_indexed()}; } - -CONSTCD11 -inline year_month_weekday operator/(int y, const month_weekday& mwd) NOEXCEPT { return year(y) / mwd; } - -CONSTCD11 -inline year_month_weekday operator/(const month_weekday& mwd, const year& y) NOEXCEPT { return y / mwd; } - -CONSTCD11 -inline year_month_weekday operator/(const month_weekday& mwd, int y) NOEXCEPT { return year(y) / mwd; } - -// year_month_weekday_last from operator/() - -CONSTCD11 -inline year_month_weekday_last operator/(const year_month& ym, const weekday_last& wdl) NOEXCEPT { return {ym.year(), ym.month(), wdl}; } - -CONSTCD11 -inline year_month_weekday_last operator/(const year& y, const month_weekday_last& mwdl) NOEXCEPT { return {y, mwdl.month(), mwdl.weekday_last()}; } - -CONSTCD11 -inline year_month_weekday_last operator/(int y, const month_weekday_last& mwdl) NOEXCEPT { return year(y) / mwdl; } - -CONSTCD11 -inline year_month_weekday_last operator/(const month_weekday_last& mwdl, const year& y) NOEXCEPT { return y / mwdl; } - -CONSTCD11 -inline year_month_weekday_last operator/(const month_weekday_last& mwdl, int y) NOEXCEPT { return year(y) / mwdl; } - -template -struct fields; - -template -std::basic_ostream& to_stream(std::basic_ostream& os, const CharT* fmt, const fields& fds, - const std::string* abbrev = nullptr, const std::chrono::seconds* offset_sec = nullptr); - -template -std::basic_istream& from_stream(std::basic_istream& is, const CharT* fmt, fields& fds, - std::basic_string* abbrev = nullptr, std::chrono::minutes* offset = nullptr); - -// hh_mm_ss - -namespace detail { - -struct undocumented { - explicit undocumented() = default; -}; - -// width::value is the number of fractional decimal digits in 1/n -// width<0>::value and width<1>::value are defined to be 0 -// If 1/n takes more than 18 fractional decimal digits, -// the result is truncated to 19. -// Example: width<2>::value == 1 -// Example: width<3>::value == 19 -// Example: width<4>::value == 2 -// Example: width<10>::value == 1 -// Example: width<1000>::value == 3 -template -struct width { - static CONSTDATA unsigned value = 1 + width::value; -}; - -template -struct width { - static CONSTDATA unsigned value = 0; -}; - -template -struct static_pow10 { - private: - static CONSTDATA std::uint64_t h = static_pow10::value; - - public: - static CONSTDATA std::uint64_t value = h * h * (exp % 2 ? 10 : 1); -}; - -template <> -struct static_pow10<0> { - static CONSTDATA std::uint64_t value = 1; -}; - -template -class decimal_format_seconds { - using CT = typename std::common_type::type; - using rep = typename CT::rep; - - public: - static unsigned constexpr width = detail::width::value < 19 ? detail::width::value : 6u; - using precision = std::chrono::duration::value>>; - - private: - std::chrono::seconds s_; - precision sub_s_; - - public: - CONSTCD11 decimal_format_seconds() : s_(), sub_s_() {} - - CONSTCD11 explicit decimal_format_seconds(const Duration& d) NOEXCEPT : s_(std::chrono::duration_cast(d)), - sub_s_(std::chrono::duration_cast(d - s_)) {} - - CONSTCD14 std::chrono::seconds& seconds() NOEXCEPT { return s_; } - CONSTCD11 std::chrono::seconds seconds() const NOEXCEPT { return s_; } - CONSTCD11 precision subseconds() const NOEXCEPT { return sub_s_; } - - CONSTCD14 precision to_duration() const NOEXCEPT { return s_ + sub_s_; } - - CONSTCD11 bool in_conventional_range() const NOEXCEPT { return sub_s_ < std::chrono::seconds{1} && s_ < std::chrono::minutes{1}; } - - template - friend std::basic_ostream& operator<<(std::basic_ostream& os, const decimal_format_seconds& x) { - return x.print(os, std::chrono::treat_as_floating_point{}); - } - - template - std::basic_ostream& print(std::basic_ostream& os, std::true_type) const { - date::detail::save_ostream _(os); - std::chrono::duration d = s_ + sub_s_; - if (d < std::chrono::seconds{10}) os << '0'; - os << std::fixed << d.count(); - return os; - } - - template - std::basic_ostream& print(std::basic_ostream& os, std::false_type) const { - date::detail::save_ostream _(os); - os.fill('0'); - os.flags(std::ios::dec | std::ios::right); - os.width(2); - os << s_.count(); - if (width > 0) { -#if !ONLY_C_LOCALE - os << std::use_facet>(os.getloc()).decimal_point(); -#else - os << '.'; -#endif - date::detail::save_ostream _s(os); - os.imbue(std::locale::classic()); - os.width(width); - os << sub_s_.count(); - } - return os; - } -}; - -template -inline CONSTCD11 typename std::enable_if::is_signed, std::chrono::duration>::type abs( - std::chrono::duration d) { - return d >= d.zero() ? +d : -d; -} - -template -inline CONSTCD11 typename std::enable_if::is_signed, std::chrono::duration>::type abs( - std::chrono::duration d) { - return d; -} - -} // namespace detail - -template -class hh_mm_ss { - using dfs = detail::decimal_format_seconds::type>; - - std::chrono::hours h_; - std::chrono::minutes m_; - dfs s_; - bool neg_; - - public: - static unsigned CONSTDATA fractional_width = dfs::width; - using precision = typename dfs::precision; - - CONSTCD11 hh_mm_ss() NOEXCEPT : hh_mm_ss(Duration::zero()) {} - - CONSTCD11 explicit hh_mm_ss(Duration d) NOEXCEPT : h_(std::chrono::duration_cast(detail::abs(d))), - m_(std::chrono::duration_cast(detail::abs(d)) - h_), - s_(detail::abs(d) - h_ - m_), - neg_(d < Duration::zero()) {} - - CONSTCD11 std::chrono::hours hours() const NOEXCEPT { return h_; } - CONSTCD11 std::chrono::minutes minutes() const NOEXCEPT { return m_; } - CONSTCD11 std::chrono::seconds seconds() const NOEXCEPT { return s_.seconds(); } - CONSTCD14 std::chrono::seconds& seconds(detail::undocumented) NOEXCEPT { return s_.seconds(); } - CONSTCD11 precision subseconds() const NOEXCEPT { return s_.subseconds(); } - CONSTCD11 bool is_negative() const NOEXCEPT { return neg_; } - - CONSTCD11 explicit operator precision() const NOEXCEPT { return to_duration(); } - CONSTCD11 precision to_duration() const NOEXCEPT { return (s_.to_duration() + m_ + h_) * (1 - 2 * neg_); } - - CONSTCD11 bool in_conventional_range() const NOEXCEPT { return !neg_ && h_ < days{1} && m_ < std::chrono::hours{1} && s_.in_conventional_range(); } - - private: - template - friend std::basic_ostream& operator<<(std::basic_ostream& os, hh_mm_ss const& tod) { - if (tod.is_negative()) os << '-'; - if (tod.h_ < std::chrono::hours{10}) os << '0'; - os << tod.h_.count() << ':'; - if (tod.m_ < std::chrono::minutes{10}) os << '0'; - os << tod.m_.count() << ':' << tod.s_; - return os; - } - - template - friend std::basic_ostream& date::to_stream(std::basic_ostream& os, const CharT* fmt, const fields& fds, - const std::string* abbrev, const std::chrono::seconds* offset_sec); - - template - friend std::basic_istream& date::from_stream(std::basic_istream& is, const CharT* fmt, fields& fds, - std::basic_string* abbrev, std::chrono::minutes* offset); -}; - -inline CONSTCD14 bool is_am(std::chrono::hours const& h) NOEXCEPT { - using std::chrono::hours; - return hours{0} <= h && h < hours{12}; -} - -inline CONSTCD14 bool is_pm(std::chrono::hours const& h) NOEXCEPT { - using std::chrono::hours; - return hours{12} <= h && h < hours{24}; -} - -inline CONSTCD14 std::chrono::hours make12(std::chrono::hours h) NOEXCEPT { - using std::chrono::hours; - if (h < hours{12}) { - if (h == hours{0}) h = hours{12}; - } else { - if (h != hours{12}) h = h - hours{12}; - } - return h; -} - -inline CONSTCD14 std::chrono::hours make24(std::chrono::hours h, bool is_pm) NOEXCEPT { - using std::chrono::hours; - if (is_pm) { - if (h != hours{12}) h = h + hours{12}; - } else if (h == hours{12}) - h = hours{0}; - return h; -} - -template -using time_of_day = hh_mm_ss; - -template ::value>::type> -CONSTCD11 inline hh_mm_ss> make_time(const std::chrono::duration& d) { - return hh_mm_ss>(d); -} - -template -inline typename std::enable_if::value && - std::ratio_less::value, - std::basic_ostream&>::type -operator<<(std::basic_ostream& os, const sys_time& tp) { - auto const dp = date::floor(tp); - return os << year_month_day(dp) << ' ' << make_time(tp - dp); -} - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const sys_days& dp) { - return os << year_month_day(dp); -} - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const local_time& ut) { - return (os << sys_time{ut.time_since_epoch()}); -} - -namespace detail { - -template -class string_literal; - -template -inline CONSTCD14 string_literal::type, N1 + N2 - 1> operator+( - const string_literal& x, const string_literal& y) NOEXCEPT; - -template -class string_literal { - CharT p_[N]; - - CONSTCD11 string_literal() NOEXCEPT : p_{} {} - - public: - using const_iterator = const CharT*; - - string_literal(string_literal const&) = default; - string_literal& operator=(string_literal const&) = delete; - - template ::type> - CONSTCD11 string_literal(CharT c) NOEXCEPT : p_{c} {} - - template ::type> - CONSTCD11 string_literal(CharT c1, CharT c2) NOEXCEPT : p_{c1, c2} {} - - template ::type> - CONSTCD11 string_literal(CharT c1, CharT c2, CharT c3) NOEXCEPT : p_{c1, c2, c3} {} - - CONSTCD14 string_literal(const CharT (&a)[N]) NOEXCEPT : p_{} { - for (std::size_t i = 0; i < N; ++i) p_[i] = a[i]; - } - - template ::type> - CONSTCD14 string_literal(const char (&a)[N]) NOEXCEPT : p_{} { - for (std::size_t i = 0; i < N; ++i) p_[i] = a[i]; - } - - template ::value>::type> - CONSTCD14 string_literal(string_literal const& a) NOEXCEPT : p_{} { - for (std::size_t i = 0; i < N; ++i) p_[i] = a[i]; - } - - CONSTCD11 const CharT* data() const NOEXCEPT { return p_; } - CONSTCD11 std::size_t size() const NOEXCEPT { return N - 1; } - - CONSTCD11 const_iterator begin() const NOEXCEPT { return p_; } - CONSTCD11 const_iterator end() const NOEXCEPT { return p_ + N - 1; } - - CONSTCD11 CharT const& operator[](std::size_t n) const NOEXCEPT { return p_[n]; } - - template - friend std::basic_ostream& operator<<(std::basic_ostream& os, const string_literal& s) { - return os << s.p_; - } - - template - friend CONSTCD14 string_literal::type, N1 + N2 - 1> operator+( - const string_literal& x, const string_literal& y) NOEXCEPT; -}; - -template -CONSTCD11 inline string_literal operator+(const string_literal& x, const string_literal& y) NOEXCEPT { - return string_literal(x[0], y[0]); -} - -template -CONSTCD11 inline string_literal operator+(const string_literal& x, const string_literal& y) NOEXCEPT { - return string_literal(x[0], x[1], y[0]); -} - -template -CONSTCD14 inline string_literal::type, N1 + N2 - 1> operator+( - const string_literal& x, const string_literal& y) NOEXCEPT { - using CT = typename std::conditional::type; - - string_literal r; - std::size_t i = 0; - for (; i < N1 - 1; ++i) r.p_[i] = CT(x.p_[i]); - for (std::size_t j = 0; j < N2; ++j, ++i) r.p_[i] = CT(y.p_[j]); - - return r; -} - -template -inline std::basic_string operator+(std::basic_string x, const string_literal& y) { - x.append(y.data(), y.size()); - return x; -} - -#if __cplusplus >= 201402 && (!defined(__EDG_VERSION__) || __EDG_VERSION__ > 411) && (!defined(__SUNPRO_CC) || __SUNPRO_CC > 0x5150) - -template ::value || std::is_same::value || - std::is_same::value || std::is_same::value>> -CONSTCD14 inline string_literal msl(CharT c) NOEXCEPT { - return string_literal{c}; -} - -CONSTCD14 -inline std::size_t to_string_len(std::intmax_t i) { - std::size_t r = 0; - do { - i /= 10; - ++r; - } while (i > 0); - return r; -} - -template - CONSTCD14 inline std::enable_if_t < N<10, string_literal> msl() NOEXCEPT { - return msl(char(N % 10 + '0')); -} - -template -CONSTCD14 inline std::enable_if_t<10 <= N, string_literal> msl() NOEXCEPT { - return msl() + msl(char(N % 10 + '0')); -} - -template -CONSTCD14 inline std::enable_if_t::type::den != 1, - string_literal::type::num) + to_string_len(std::ratio::type::den) + 4>> -msl(std::ratio) NOEXCEPT { - using R = typename std::ratio::type; - return msl(CharT{'['}) + msl() + msl(CharT{'/'}) + msl() + msl(CharT{']'}); -} - -template -CONSTCD14 inline std::enable_if_t::type::den == 1, string_literal::type::num) + 3>> msl( - std::ratio) NOEXCEPT { - using R = typename std::ratio::type; - return msl(CharT{'['}) + msl() + msl(CharT{']'}); -} - -#else // __cplusplus < 201402 || (defined(__EDG_VERSION__) && __EDG_VERSION__ <= 411) - -inline std::string to_string(std::uint64_t x) { return std::to_string(x); } - -template -inline std::basic_string to_string(std::uint64_t x) { - auto y = std::to_string(x); - return std::basic_string(y.begin(), y.end()); -} - -template -inline typename std::enable_if::type::den != 1, std::basic_string>::type msl(std::ratio) { - using R = typename std::ratio::type; - return std::basic_string(1, '[') + to_string(R::num) + CharT{'/'} + to_string(R::den) + CharT{']'}; -} - -template -inline typename std::enable_if::type::den == 1, std::basic_string>::type msl(std::ratio) { - using R = typename std::ratio::type; - return std::basic_string(1, '[') + to_string(R::num) + CharT{']'}; -} - -#endif // __cplusplus < 201402 || (defined(__EDG_VERSION__) && __EDG_VERSION__ <= 411) - -template -CONSTCD11 inline string_literal msl(std::atto) NOEXCEPT { - return string_literal{'a'}; -} - -template -CONSTCD11 inline string_literal msl(std::femto) NOEXCEPT { - return string_literal{'f'}; -} - -template -CONSTCD11 inline string_literal msl(std::pico) NOEXCEPT { - return string_literal{'p'}; -} - -template -CONSTCD11 inline string_literal msl(std::nano) NOEXCEPT { - return string_literal{'n'}; -} - -template -CONSTCD11 inline typename std::enable_if::value, string_literal>::type msl(std::micro) NOEXCEPT { - return string_literal{'\xC2', '\xB5'}; -} - -template -CONSTCD11 inline typename std::enable_if::value, string_literal>::type msl(std::micro) NOEXCEPT { - return string_literal{CharT{static_cast('\xB5')}}; -} - -template -CONSTCD11 inline string_literal msl(std::milli) NOEXCEPT { - return string_literal{'m'}; -} - -template -CONSTCD11 inline string_literal msl(std::centi) NOEXCEPT { - return string_literal{'c'}; -} - -template -CONSTCD11 inline string_literal msl(std::deca) NOEXCEPT { - return string_literal{'d', 'a'}; -} - -template -CONSTCD11 inline string_literal msl(std::deci) NOEXCEPT { - return string_literal{'d'}; -} - -template -CONSTCD11 inline string_literal msl(std::hecto) NOEXCEPT { - return string_literal{'h'}; -} - -template -CONSTCD11 inline string_literal msl(std::kilo) NOEXCEPT { - return string_literal{'k'}; -} - -template -CONSTCD11 inline string_literal msl(std::mega) NOEXCEPT { - return string_literal{'M'}; -} - -template -CONSTCD11 inline string_literal msl(std::giga) NOEXCEPT { - return string_literal{'G'}; -} - -template -CONSTCD11 inline string_literal msl(std::tera) NOEXCEPT { - return string_literal{'T'}; -} - -template -CONSTCD11 inline string_literal msl(std::peta) NOEXCEPT { - return string_literal{'P'}; -} - -template -CONSTCD11 inline string_literal msl(std::exa) NOEXCEPT { - return string_literal{'E'}; -} - -template -CONSTCD11 inline auto get_units(Period p) -> decltype(msl(p) + string_literal{'s'}) { - return msl(p) + string_literal{'s'}; -} - -template -CONSTCD11 inline string_literal get_units(std::ratio<1>) { - return string_literal{'s'}; -} - -template -CONSTCD11 inline string_literal get_units(std::ratio<3600>) { - return string_literal{'h'}; -} - -template -CONSTCD11 inline string_literal get_units(std::ratio<60>) { - return string_literal{'m', 'i', 'n'}; -} - -template -CONSTCD11 inline string_literal get_units(std::ratio<86400>) { - return string_literal{'d'}; -} - -template > -struct make_string; - -template <> -struct make_string { - template - static std::string from(Rep n) { - return std::to_string(n); - } -}; - -template -struct make_string { - template - static std::basic_string from(Rep n) { - auto s = std::to_string(n); - return std::basic_string(s.begin(), s.end()); - } -}; - -template <> -struct make_string { - template - static std::wstring from(Rep n) { - return std::to_wstring(n); - } -}; - -template -struct make_string { - template - static std::basic_string from(Rep n) { - auto s = std::to_wstring(n); - return std::basic_string(s.begin(), s.end()); - } -}; - -} // namespace detail - -// to_stream - -CONSTDATA year nanyear{-32768}; - -template -struct fields { - year_month_day ymd{nanyear / 0 / 0}; - weekday wd{8u}; - hh_mm_ss tod{}; - bool has_tod = false; - - fields() = default; - - fields(year_month_day ymd_) : ymd(ymd_) {} - fields(weekday wd_) : wd(wd_) {} - fields(hh_mm_ss tod_) : tod(tod_), has_tod(true) {} - - fields(year_month_day ymd_, weekday wd_) : ymd(ymd_), wd(wd_) {} - fields(year_month_day ymd_, hh_mm_ss tod_) : ymd(ymd_), tod(tod_), has_tod(true) {} - - fields(weekday wd_, hh_mm_ss tod_) : wd(wd_), tod(tod_), has_tod(true) {} - - fields(year_month_day ymd_, weekday wd_, hh_mm_ss tod_) : ymd(ymd_), wd(wd_), tod(tod_), has_tod(true) {} -}; - -namespace detail { - -template -unsigned extract_weekday(std::basic_ostream& os, const fields& fds) { - if (!fds.ymd.ok() && !fds.wd.ok()) { - // fds does not contain a valid weekday - os.setstate(std::ios::failbit); - return 8; - } - weekday wd; - if (fds.ymd.ok()) { - wd = weekday{sys_days(fds.ymd)}; - if (fds.wd.ok() && wd != fds.wd) { - // fds.ymd and fds.wd are inconsistent - os.setstate(std::ios::failbit); - return 8; - } - } else - wd = fds.wd; - return static_cast((wd - Sunday).count()); -} - -template -unsigned extract_month(std::basic_ostream& os, const fields& fds) { - if (!fds.ymd.month().ok()) { - // fds does not contain a valid month - os.setstate(std::ios::failbit); - return 0; - } - return static_cast(fds.ymd.month()); -} - -} // namespace detail - -#if ONLY_C_LOCALE - -namespace detail { - -inline std::pair weekday_names() { - static const std::string nm[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", - "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; - return std::make_pair(nm, nm + sizeof(nm) / sizeof(nm[0])); -} - -inline std::pair month_names() { - static const std::string nm[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", - "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; - return std::make_pair(nm, nm + sizeof(nm) / sizeof(nm[0])); -} - -inline std::pair ampm_names() { - static const std::string nm[] = {"AM", "PM"}; - return std::make_pair(nm, nm + sizeof(nm) / sizeof(nm[0])); -} - -template -FwdIter scan_keyword(std::basic_istream& is, FwdIter kb, FwdIter ke) { - size_t nkw = static_cast(std::distance(kb, ke)); - const unsigned char doesnt_match = '\0'; - const unsigned char might_match = '\1'; - const unsigned char does_match = '\2'; - unsigned char statbuf[100]; - unsigned char* status = statbuf; - std::unique_ptr stat_hold(0, free); - if (nkw > sizeof(statbuf)) { - status = (unsigned char*)std::malloc(nkw); - if (status == nullptr) throw std::bad_alloc(); - stat_hold.reset(status); - } - size_t n_might_match = nkw; // At this point, any keyword might match - size_t n_does_match = 0; // but none of them definitely do - // Initialize all statuses to might_match, except for "" keywords are does_match - unsigned char* st = status; - for (auto ky = kb; ky != ke; ++ky, ++st) { - if (!ky->empty()) - *st = might_match; - else { - *st = does_match; - --n_might_match; - ++n_does_match; - } - } - // While there might be a match, test keywords against the next CharT - for (size_t indx = 0; is && n_might_match > 0; ++indx) { - // Peek at the next CharT but don't consume it - auto ic = is.peek(); - if (ic == EOF) { - is.setstate(std::ios::eofbit); - break; - } - auto c = static_cast(toupper(ic)); - bool consume = false; - // For each keyword which might match, see if the indx character is c - // If a match if found, consume c - // If a match is found, and that is the last character in the keyword, - // then that keyword matches. - // If the keyword doesn't match this character, then change the keyword - // to doesn't match - st = status; - for (auto ky = kb; ky != ke; ++ky, ++st) { - if (*st == might_match) { - if (c == static_cast(toupper((*ky)[indx]))) { - consume = true; - if (ky->size() == indx + 1) { - *st = does_match; - --n_might_match; - ++n_does_match; - } - } else { - *st = doesnt_match; - --n_might_match; - } - } - } - // consume if we matched a character - if (consume) { - (void)is.get(); - // If we consumed a character and there might be a matched keyword that - // was marked matched on a previous iteration, then such keywords - // are now marked as not matching. - if (n_might_match + n_does_match > 1) { - st = status; - for (auto ky = kb; ky != ke; ++ky, ++st) { - if (*st == does_match && ky->size() != indx + 1) { - *st = doesnt_match; - --n_does_match; - } - } - } - } - } - // We've exited the loop because we hit eof and/or we have no more "might matches". - // Return the first matching result - for (st = status; kb != ke; ++kb, ++st) - if (*st == does_match) break; - if (kb == ke) is.setstate(std::ios::failbit); - return kb; -} - -} // namespace detail - -#endif // ONLY_C_LOCALE - -template -std::basic_ostream& to_stream(std::basic_ostream& os, const CharT* fmt, const fields& fds, const std::string* abbrev, - const std::chrono::seconds* offset_sec) { -#if ONLY_C_LOCALE - using detail::ampm_names; - using detail::month_names; - using detail::weekday_names; -#endif - using detail::extract_month; - using detail::extract_weekday; - using detail::get_units; - using detail::save_ostream; - using std::ios; - using std::chrono::duration_cast; - using std::chrono::hours; - using std::chrono::minutes; - using std::chrono::seconds; - date::detail::save_ostream ss(os); - os.fill(' '); - os.flags(std::ios::skipws | std::ios::dec); - os.width(0); - tm tm{}; - bool insert_negative = fds.has_tod && fds.tod.to_duration() < Duration::zero(); -#if !ONLY_C_LOCALE - auto& facet = std::use_facet>(os.getloc()); -#endif - const CharT* command = nullptr; - CharT modified = CharT{}; - for (; *fmt; ++fmt) { - switch (*fmt) { - case 'a': - case 'A': - if (command) { - if (modified == CharT{}) { - tm.tm_wday = static_cast(extract_weekday(os, fds)); - if (os.fail()) return os; -#if !ONLY_C_LOCALE - const CharT f[] = {'%', *fmt}; - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); -#else // ONLY_C_LOCALE - os << weekday_names().first[tm.tm_wday + 7 * (*fmt == 'a')]; -#endif // ONLY_C_LOCALE - } else { - os << CharT{'%'} << modified << *fmt; - modified = CharT{}; - } - command = nullptr; - } else - os << *fmt; - break; - case 'b': - case 'B': - case 'h': - if (command) { - if (modified == CharT{}) { - tm.tm_mon = static_cast(extract_month(os, fds)) - 1; -#if !ONLY_C_LOCALE - const CharT f[] = {'%', *fmt}; - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); -#else // ONLY_C_LOCALE - os << month_names().first[tm.tm_mon + 12 * (*fmt != 'B')]; -#endif // ONLY_C_LOCALE - } else { - os << CharT{'%'} << modified << *fmt; - modified = CharT{}; - } - command = nullptr; - } else - os << *fmt; - break; - case 'c': - case 'x': - if (command) { - if (modified == CharT{'O'}) - os << CharT{'%'} << modified << *fmt; - else { - if (!fds.ymd.ok()) os.setstate(std::ios::failbit); - if (*fmt == 'c' && !fds.has_tod) os.setstate(std::ios::failbit); -#if !ONLY_C_LOCALE - tm = std::tm{}; - auto const& ymd = fds.ymd; - auto ld = local_days(ymd); - if (*fmt == 'c') { - tm.tm_sec = static_cast(fds.tod.seconds().count()); - tm.tm_min = static_cast(fds.tod.minutes().count()); - tm.tm_hour = static_cast(fds.tod.hours().count()); - } - tm.tm_mday = static_cast(static_cast(ymd.day())); - tm.tm_mon = static_cast(extract_month(os, fds) - 1); - tm.tm_year = static_cast(ymd.year()) - 1900; - tm.tm_wday = static_cast(extract_weekday(os, fds)); - if (os.fail()) return os; - tm.tm_yday = static_cast((ld - local_days(ymd.year() / 1 / 1)).count()); - CharT f[3] = {'%'}; - auto fe = std::begin(f) + 1; - if (modified == CharT{'E'}) *fe++ = modified; - *fe++ = *fmt; - facet.put(os, os, os.fill(), &tm, std::begin(f), fe); -#else // ONLY_C_LOCALE - if (*fmt == 'c') { - auto wd = static_cast(extract_weekday(os, fds)); - os << weekday_names().first[static_cast(wd) + 7] << ' '; - os << month_names().first[extract_month(os, fds) - 1 + 12] << ' '; - auto d = static_cast(static_cast(fds.ymd.day())); - if (d < 10) os << ' '; - os << d << ' ' << make_time(duration_cast(fds.tod.to_duration())) << ' ' << fds.ymd.year(); - - } else // *fmt == 'x' - { - auto const& ymd = fds.ymd; - save_ostream _(os); - os.fill('0'); - os.flags(std::ios::dec | std::ios::right); - os.width(2); - os << static_cast(ymd.month()) << CharT{'/'}; - os.width(2); - os << static_cast(ymd.day()) << CharT{'/'}; - os.width(2); - os << static_cast(ymd.year()) % 100; - } -#endif // ONLY_C_LOCALE - } - command = nullptr; - modified = CharT{}; - } else - os << *fmt; - break; - case 'C': - if (command) { - if (modified == CharT{'O'}) - os << CharT{'%'} << modified << *fmt; - else { - if (!fds.ymd.year().ok()) os.setstate(std::ios::failbit); - auto y = static_cast(fds.ymd.year()); -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#endif - { - save_ostream _(os); - os.fill('0'); - os.flags(std::ios::dec | std::ios::right); - if (y >= 0) { - os.width(2); - os << y / 100; - } else { - os << CharT{'-'}; - os.width(2); - os << -(y - 99) / 100; - } - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'E'}) { - tm.tm_year = y - 1900; - CharT f[3] = {'%', 'E', 'C'}; - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - } - command = nullptr; - modified = CharT{}; - } else - os << *fmt; - break; - case 'd': - case 'e': - if (command) { - if (modified == CharT{'E'}) - os << CharT{'%'} << modified << *fmt; - else { - if (!fds.ymd.day().ok()) os.setstate(std::ios::failbit); - auto d = static_cast(static_cast(fds.ymd.day())); -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#endif - { - save_ostream _(os); - if (*fmt == CharT{'d'}) - os.fill('0'); - else - os.fill(' '); - os.flags(std::ios::dec | std::ios::right); - os.width(2); - os << d; - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - tm.tm_mday = d; - CharT f[3] = {'%', 'O', *fmt}; - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - } - command = nullptr; - modified = CharT{}; - } else - os << *fmt; - break; - case 'D': - if (command) { - if (modified == CharT{}) { - if (!fds.ymd.ok()) os.setstate(std::ios::failbit); - auto const& ymd = fds.ymd; - save_ostream _(os); - os.fill('0'); - os.flags(std::ios::dec | std::ios::right); - os.width(2); - os << static_cast(ymd.month()) << CharT{'/'}; - os.width(2); - os << static_cast(ymd.day()) << CharT{'/'}; - os.width(2); - os << static_cast(ymd.year()) % 100; - } else { - os << CharT{'%'} << modified << *fmt; - modified = CharT{}; - } - command = nullptr; - } else - os << *fmt; - break; - case 'F': - if (command) { - if (modified == CharT{}) { - if (!fds.ymd.ok()) os.setstate(std::ios::failbit); - auto const& ymd = fds.ymd; - save_ostream _(os); - os.imbue(std::locale::classic()); - os.fill('0'); - os.flags(std::ios::dec | std::ios::right); - os.width(4); - os << static_cast(ymd.year()) << CharT{'-'}; - os.width(2); - os << static_cast(ymd.month()) << CharT{'-'}; - os.width(2); - os << static_cast(ymd.day()); - } else { - os << CharT{'%'} << modified << *fmt; - modified = CharT{}; - } - command = nullptr; - } else - os << *fmt; - break; - case 'g': - case 'G': - if (command) { - if (modified == CharT{}) { - if (!fds.ymd.ok()) os.setstate(std::ios::failbit); - auto ld = local_days(fds.ymd); - auto y = year_month_day{ld + days{3}}.year(); - auto start = local_days((y - years{1}) / December / Thursday[last]) + (Monday - Thursday); - if (ld < start) --y; - if (*fmt == CharT{'G'}) - os << y; - else { - save_ostream _(os); - os.fill('0'); - os.flags(std::ios::dec | std::ios::right); - os.width(2); - os << std::abs(static_cast(y)) % 100; - } - } else { - os << CharT{'%'} << modified << *fmt; - modified = CharT{}; - } - command = nullptr; - } else - os << *fmt; - break; - case 'H': - case 'I': - if (command) { - if (modified == CharT{'E'}) - os << CharT{'%'} << modified << *fmt; - else { - if (!fds.has_tod) os.setstate(std::ios::failbit); - if (insert_negative) { - os << '-'; - insert_negative = false; - } - auto hms = fds.tod; -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#endif - { - auto h = *fmt == CharT{'I'} ? date::make12(hms.hours()) : hms.hours(); - if (h < hours{10}) os << CharT{'0'}; - os << h.count(); - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - const CharT f[] = {'%', modified, *fmt}; - tm.tm_hour = static_cast(hms.hours().count()); - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'j': - if (command) { - if (modified == CharT{}) { - if (fds.ymd.ok() || fds.has_tod) { - days doy; - if (fds.ymd.ok()) { - auto ld = local_days(fds.ymd); - auto y = fds.ymd.year(); - doy = ld - local_days(y / January / 1) + days{1}; - } else { - doy = duration_cast(fds.tod.to_duration()); - } - save_ostream _(os); - os.fill('0'); - os.flags(std::ios::dec | std::ios::right); - os.width(3); - os << doy.count(); - } else { - os.setstate(std::ios::failbit); - } - } else { - os << CharT{'%'} << modified << *fmt; - modified = CharT{}; - } - command = nullptr; - } else - os << *fmt; - break; - case 'm': - if (command) { - if (modified == CharT{'E'}) - os << CharT{'%'} << modified << *fmt; - else { - if (!fds.ymd.month().ok()) os.setstate(std::ios::failbit); - auto m = static_cast(fds.ymd.month()); -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#endif - { - if (m < 10) os << CharT{'0'}; - os << m; - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - const CharT f[] = {'%', modified, *fmt}; - tm.tm_mon = static_cast(m - 1); - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'M': - if (command) { - if (modified == CharT{'E'}) - os << CharT{'%'} << modified << *fmt; - else { - if (!fds.has_tod) os.setstate(std::ios::failbit); - if (insert_negative) { - os << '-'; - insert_negative = false; - } -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#endif - { - if (fds.tod.minutes() < minutes{10}) os << CharT{'0'}; - os << fds.tod.minutes().count(); - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - const CharT f[] = {'%', modified, *fmt}; - tm.tm_min = static_cast(fds.tod.minutes().count()); - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'n': - if (command) { - if (modified == CharT{}) - os << CharT{'\n'}; - else { - os << CharT{'%'} << modified << *fmt; - modified = CharT{}; - } - command = nullptr; - } else - os << *fmt; - break; - case 'p': - if (command) { - if (modified == CharT{}) { - if (!fds.has_tod) os.setstate(std::ios::failbit); -#if !ONLY_C_LOCALE - const CharT f[] = {'%', *fmt}; - tm.tm_hour = static_cast(fds.tod.hours().count()); - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); -#else - if (date::is_am(fds.tod.hours())) - os << ampm_names().first[0]; - else - os << ampm_names().first[1]; -#endif - } else { - os << CharT{'%'} << modified << *fmt; - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'Q': - case 'q': - if (command) { - if (modified == CharT{}) { - if (!fds.has_tod) os.setstate(std::ios::failbit); - auto d = fds.tod.to_duration(); - if (*fmt == 'q') - os << get_units(typename decltype(d)::period::type{}); - else - os << d.count(); - } else { - os << CharT{'%'} << modified << *fmt; - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'r': - if (command) { - if (modified == CharT{}) { - if (!fds.has_tod) os.setstate(std::ios::failbit); -#if !ONLY_C_LOCALE - const CharT f[] = {'%', *fmt}; - tm.tm_hour = static_cast(fds.tod.hours().count()); - tm.tm_min = static_cast(fds.tod.minutes().count()); - tm.tm_sec = static_cast(fds.tod.seconds().count()); - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); -#else - hh_mm_ss tod(duration_cast(fds.tod.to_duration())); - save_ostream _(os); - os.fill('0'); - os.width(2); - os << date::make12(tod.hours()).count() << CharT{':'}; - os.width(2); - os << tod.minutes().count() << CharT{':'}; - os.width(2); - os << tod.seconds().count() << CharT{' '}; - if (date::is_am(tod.hours())) - os << ampm_names().first[0]; - else - os << ampm_names().first[1]; -#endif - } else { - os << CharT{'%'} << modified << *fmt; - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'R': - if (command) { - if (modified == CharT{}) { - if (!fds.has_tod) os.setstate(std::ios::failbit); - if (fds.tod.hours() < hours{10}) os << CharT{'0'}; - os << fds.tod.hours().count() << CharT{':'}; - if (fds.tod.minutes() < minutes{10}) os << CharT{'0'}; - os << fds.tod.minutes().count(); - } else { - os << CharT{'%'} << modified << *fmt; - modified = CharT{}; - } - command = nullptr; - } else - os << *fmt; - break; - case 'S': - if (command) { - if (modified == CharT{'E'}) - os << CharT{'%'} << modified << *fmt; - else { - if (!fds.has_tod) os.setstate(std::ios::failbit); - if (insert_negative) { - os << '-'; - insert_negative = false; - } -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#endif - { - os << fds.tod.s_; - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - const CharT f[] = {'%', modified, *fmt}; - tm.tm_sec = static_cast(fds.tod.s_.seconds().count()); - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 't': - if (command) { - if (modified == CharT{}) - os << CharT{'\t'}; - else { - os << CharT{'%'} << modified << *fmt; - modified = CharT{}; - } - command = nullptr; - } else - os << *fmt; - break; - case 'T': - if (command) { - if (modified == CharT{}) { - if (!fds.has_tod) os.setstate(std::ios::failbit); - os << fds.tod; - } else { - os << CharT{'%'} << modified << *fmt; - modified = CharT{}; - } - command = nullptr; - } else - os << *fmt; - break; - case 'u': - if (command) { - if (modified == CharT{'E'}) - os << CharT{'%'} << modified << *fmt; - else { - auto wd = extract_weekday(os, fds); -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#endif - { - os << (wd != 0 ? wd : 7u); - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - const CharT f[] = {'%', modified, *fmt}; - tm.tm_wday = static_cast(wd); - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'U': - if (command) { - if (modified == CharT{'E'}) - os << CharT{'%'} << modified << *fmt; - else { - auto const& ymd = fds.ymd; - if (!ymd.ok()) os.setstate(std::ios::failbit); - auto ld = local_days(ymd); -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#endif - { - auto st = local_days(Sunday[1] / January / ymd.year()); - if (ld < st) - os << CharT{'0'} << CharT{'0'}; - else { - auto wn = duration_cast(ld - st).count() + 1; - if (wn < 10) os << CharT{'0'}; - os << wn; - } - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - const CharT f[] = {'%', modified, *fmt}; - tm.tm_year = static_cast(ymd.year()) - 1900; - tm.tm_wday = static_cast(extract_weekday(os, fds)); - if (os.fail()) return os; - tm.tm_yday = static_cast((ld - local_days(ymd.year() / 1 / 1)).count()); - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'V': - if (command) { - if (modified == CharT{'E'}) - os << CharT{'%'} << modified << *fmt; - else { - if (!fds.ymd.ok()) os.setstate(std::ios::failbit); - auto ld = local_days(fds.ymd); -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#endif - { - auto y = year_month_day{ld + days{3}}.year(); - auto st = local_days((y - years{1}) / 12 / Thursday[last]) + (Monday - Thursday); - if (ld < st) { - --y; - st = local_days((y - years{1}) / 12 / Thursday[last]) + (Monday - Thursday); - } - auto wn = duration_cast(ld - st).count() + 1; - if (wn < 10) os << CharT{'0'}; - os << wn; - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - const CharT f[] = {'%', modified, *fmt}; - auto const& ymd = fds.ymd; - tm.tm_year = static_cast(ymd.year()) - 1900; - tm.tm_wday = static_cast(extract_weekday(os, fds)); - if (os.fail()) return os; - tm.tm_yday = static_cast((ld - local_days(ymd.year() / 1 / 1)).count()); - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'w': - if (command) { - auto wd = extract_weekday(os, fds); - if (os.fail()) return os; -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#else - if (modified != CharT{'E'}) -#endif - { - os << wd; - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - const CharT f[] = {'%', modified, *fmt}; - tm.tm_wday = static_cast(wd); - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - else { - os << CharT{'%'} << modified << *fmt; - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'W': - if (command) { - if (modified == CharT{'E'}) - os << CharT{'%'} << modified << *fmt; - else { - auto const& ymd = fds.ymd; - if (!ymd.ok()) os.setstate(std::ios::failbit); - auto ld = local_days(ymd); -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#endif - { - auto st = local_days(Monday[1] / January / ymd.year()); - if (ld < st) - os << CharT{'0'} << CharT{'0'}; - else { - auto wn = duration_cast(ld - st).count() + 1; - if (wn < 10) os << CharT{'0'}; - os << wn; - } - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - const CharT f[] = {'%', modified, *fmt}; - tm.tm_year = static_cast(ymd.year()) - 1900; - tm.tm_wday = static_cast(extract_weekday(os, fds)); - if (os.fail()) return os; - tm.tm_yday = static_cast((ld - local_days(ymd.year() / 1 / 1)).count()); - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'X': - if (command) { - if (modified == CharT{'O'}) - os << CharT{'%'} << modified << *fmt; - else { - if (!fds.has_tod) os.setstate(std::ios::failbit); -#if !ONLY_C_LOCALE - tm = std::tm{}; - tm.tm_sec = static_cast(fds.tod.seconds().count()); - tm.tm_min = static_cast(fds.tod.minutes().count()); - tm.tm_hour = static_cast(fds.tod.hours().count()); - CharT f[3] = {'%'}; - auto fe = std::begin(f) + 1; - if (modified == CharT{'E'}) *fe++ = modified; - *fe++ = *fmt; - facet.put(os, os, os.fill(), &tm, std::begin(f), fe); -#else - os << fds.tod; -#endif - } - command = nullptr; - modified = CharT{}; - } else - os << *fmt; - break; - case 'y': - if (command) { - if (!fds.ymd.year().ok()) os.setstate(std::ios::failbit); - auto y = static_cast(fds.ymd.year()); -#if !ONLY_C_LOCALE - if (modified == CharT{}) { -#endif - y = std::abs(y) % 100; - if (y < 10) os << CharT{'0'}; - os << y; -#if !ONLY_C_LOCALE - } else { - const CharT f[] = {'%', modified, *fmt}; - tm.tm_year = y - 1900; - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'Y': - if (command) { - if (modified == CharT{'O'}) - os << CharT{'%'} << modified << *fmt; - else { - if (!fds.ymd.year().ok()) os.setstate(std::ios::failbit); - auto y = fds.ymd.year(); -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#endif - { - save_ostream _(os); - os.imbue(std::locale::classic()); - os << y; - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'E'}) { - const CharT f[] = {'%', modified, *fmt}; - tm.tm_year = static_cast(y) - 1900; - facet.put(os, os, os.fill(), &tm, std::begin(f), std::end(f)); - } -#endif - } - modified = CharT{}; - command = nullptr; - } else - os << *fmt; - break; - case 'z': - if (command) { - if (offset_sec == nullptr) { - // Can not format %z with unknown offset - os.setstate(ios::failbit); - return os; - } - auto m = duration_cast(*offset_sec); - auto neg = m < minutes{0}; - m = date::abs(m); - auto h = duration_cast(m); - m -= h; - if (neg) - os << CharT{'-'}; - else - os << CharT{'+'}; - if (h < hours{10}) os << CharT{'0'}; - os << h.count(); - if (modified != CharT{}) os << CharT{':'}; - if (m < minutes{10}) os << CharT{'0'}; - os << m.count(); - command = nullptr; - modified = CharT{}; - } else - os << *fmt; - break; - case 'Z': - if (command) { - if (modified == CharT{}) { - if (abbrev == nullptr) { - // Can not format %Z with unknown time_zone - os.setstate(ios::failbit); - return os; - } - for (auto c : *abbrev) os << CharT(c); - } else { - os << CharT{'%'} << modified << *fmt; - modified = CharT{}; - } - command = nullptr; - } else - os << *fmt; - break; - case 'E': - case 'O': - if (command) { - if (modified == CharT{}) { - modified = *fmt; - } else { - os << CharT{'%'} << modified << *fmt; - command = nullptr; - modified = CharT{}; - } - } else - os << *fmt; - break; - case '%': - if (command) { - if (modified == CharT{}) { - os << CharT{'%'}; - command = nullptr; - } else { - os << CharT{'%'} << modified << CharT{'%'}; - command = nullptr; - modified = CharT{}; - } - } else - command = fmt; - break; - default: - if (command) { - os << CharT{'%'}; - command = nullptr; - } - if (modified != CharT{}) { - os << modified; - modified = CharT{}; - } - os << *fmt; - break; - } - } - if (command) os << CharT{'%'}; - if (modified != CharT{}) os << modified; - return os; -} - -template -inline std::basic_ostream& to_stream(std::basic_ostream& os, const CharT* fmt, const year& y) { - using CT = std::chrono::seconds; - fields fds{y / 0 / 0}; - return to_stream(os, fmt, fds); -} - -template -inline std::basic_ostream& to_stream(std::basic_ostream& os, const CharT* fmt, const month& m) { - using CT = std::chrono::seconds; - fields fds{m / 0 / nanyear}; - return to_stream(os, fmt, fds); -} - -template -inline std::basic_ostream& to_stream(std::basic_ostream& os, const CharT* fmt, const day& d) { - using CT = std::chrono::seconds; - fields fds{d / 0 / nanyear}; - return to_stream(os, fmt, fds); -} - -template -inline std::basic_ostream& to_stream(std::basic_ostream& os, const CharT* fmt, const weekday& wd) { - using CT = std::chrono::seconds; - fields fds{wd}; - return to_stream(os, fmt, fds); -} - -template -inline std::basic_ostream& to_stream(std::basic_ostream& os, const CharT* fmt, const year_month& ym) { - using CT = std::chrono::seconds; - fields fds{ym / 0}; - return to_stream(os, fmt, fds); -} - -template -inline std::basic_ostream& to_stream(std::basic_ostream& os, const CharT* fmt, const month_day& md) { - using CT = std::chrono::seconds; - fields fds{md / nanyear}; - return to_stream(os, fmt, fds); -} - -template -inline std::basic_ostream& to_stream(std::basic_ostream& os, const CharT* fmt, const year_month_day& ymd) { - using CT = std::chrono::seconds; - fields fds{ymd}; - return to_stream(os, fmt, fds); -} - -template -inline std::basic_ostream& to_stream(std::basic_ostream& os, const CharT* fmt, const std::chrono::duration& d) { - using Duration = std::chrono::duration; - using CT = typename std::common_type::type; - fields fds{hh_mm_ss{d}}; - return to_stream(os, fmt, fds); -} - -template -std::basic_ostream& to_stream(std::basic_ostream& os, const CharT* fmt, const local_time& tp, - const std::string* abbrev = nullptr, const std::chrono::seconds* offset_sec = nullptr) { - using CT = typename std::common_type::type; - auto ld = floor(tp); - fields fds{year_month_day{ld}, hh_mm_ss{tp - local_seconds{ld}}}; - return to_stream(os, fmt, fds, abbrev, offset_sec); -} - -template -std::basic_ostream& to_stream(std::basic_ostream& os, const CharT* fmt, const sys_time& tp) { - using std::chrono::seconds; - using CT = typename std::common_type::type; - const std::string abbrev("UTC"); - CONSTDATA seconds offset{0}; - auto sd = floor(tp); - fields fds{year_month_day{sd}, hh_mm_ss{tp - sys_seconds{sd}}}; - return to_stream(os, fmt, fds, &abbrev, &offset); -} - -// format - -template -auto format(const std::locale& loc, const CharT* fmt, const Streamable& tp) - -> decltype(to_stream(std::declval&>(), fmt, tp), std::basic_string{}) { - std::basic_ostringstream os; - os.exceptions(std::ios::failbit | std::ios::badbit); - os.imbue(loc); - to_stream(os, fmt, tp); - return os.str(); -} - -template -auto format(const CharT* fmt, const Streamable& tp) -> decltype(to_stream(std::declval&>(), fmt, tp), std::basic_string{}) { - std::basic_ostringstream os; - os.exceptions(std::ios::failbit | std::ios::badbit); - to_stream(os, fmt, tp); - return os.str(); -} - -template -auto format(const std::locale& loc, const std::basic_string& fmt, const Streamable& tp) - -> decltype(to_stream(std::declval&>(), fmt.c_str(), tp), std::basic_string{}) { - std::basic_ostringstream os; - os.exceptions(std::ios::failbit | std::ios::badbit); - os.imbue(loc); - to_stream(os, fmt.c_str(), tp); - return os.str(); -} - -template -auto format(const std::basic_string& fmt, const Streamable& tp) - -> decltype(to_stream(std::declval&>(), fmt.c_str(), tp), std::basic_string{}) { - std::basic_ostringstream os; - os.exceptions(std::ios::failbit | std::ios::badbit); - to_stream(os, fmt.c_str(), tp); - return os.str(); -} - -// parse - -namespace detail { - -template -bool read_char(std::basic_istream& is, CharT fmt, std::ios::iostate& err) { - auto ic = is.get(); - if (Traits::eq_int_type(ic, Traits::eof()) || !Traits::eq(Traits::to_char_type(ic), fmt)) { - err |= std::ios::failbit; - is.setstate(std::ios::failbit); - return false; - } - return true; -} - -template -unsigned read_unsigned(std::basic_istream& is, unsigned m = 1, unsigned M = 10) { - unsigned x = 0; - unsigned count = 0; - while (true) { - auto ic = is.peek(); - if (Traits::eq_int_type(ic, Traits::eof())) break; - auto c = static_cast(Traits::to_char_type(ic)); - if (!('0' <= c && c <= '9')) break; - (void)is.get(); - ++count; - x = 10 * x + static_cast(c - '0'); - if (count == M) break; - } - if (count < m) is.setstate(std::ios::failbit); - return x; -} - -template -int read_signed(std::basic_istream& is, unsigned m = 1, unsigned M = 10) { - auto ic = is.peek(); - if (!Traits::eq_int_type(ic, Traits::eof())) { - auto c = static_cast(Traits::to_char_type(ic)); - if (('0' <= c && c <= '9') || c == '-' || c == '+') { - if (c == '-' || c == '+') (void)is.get(); - auto x = static_cast(read_unsigned(is, std::max(m, 1u), M)); - if (!is.fail()) { - if (c == '-') x = -x; - return x; - } - } - } - if (m > 0) is.setstate(std::ios::failbit); - return 0; -} - -template -long double read_long_double(std::basic_istream& is, unsigned m = 1, unsigned M = 10) { - unsigned count = 0; - auto decimal_point = Traits::to_int_type(std::use_facet>(is.getloc()).decimal_point()); - std::string buf; - while (true) { - auto ic = is.peek(); - if (Traits::eq_int_type(ic, Traits::eof())) break; - if (Traits::eq_int_type(ic, decimal_point)) { - buf += '.'; - decimal_point = Traits::eof(); - is.get(); - } else { - auto c = static_cast(Traits::to_char_type(ic)); - if (!('0' <= c && c <= '9')) break; - buf += c; - (void)is.get(); - } - if (++count == M) break; - } - if (count < m) { - is.setstate(std::ios::failbit); - return 0; - } - return std::stold(buf); -} - -struct rs { - int& i; - unsigned m; - unsigned M; -}; - -struct ru { - int& i; - unsigned m; - unsigned M; -}; - -struct rld { - long double& i; - unsigned m; - unsigned M; -}; - -template -void read(std::basic_istream&) {} - -template -void read(std::basic_istream& is, CharT a0, Args&&... args); - -template -void read(std::basic_istream& is, rs a0, Args&&... args); - -template -void read(std::basic_istream& is, ru a0, Args&&... args); - -template -void read(std::basic_istream& is, int a0, Args&&... args); - -template -void read(std::basic_istream& is, rld a0, Args&&... args); - -template -void read(std::basic_istream& is, CharT a0, Args&&... args) { - // No-op if a0 == CharT{} - if (a0 != CharT{}) { - auto ic = is.peek(); - if (Traits::eq_int_type(ic, Traits::eof())) { - is.setstate(std::ios::failbit | std::ios::eofbit); - return; - } - if (!Traits::eq(Traits::to_char_type(ic), a0)) { - is.setstate(std::ios::failbit); - return; - } - (void)is.get(); - } - read(is, std::forward(args)...); -} - -template -void read(std::basic_istream& is, rs a0, Args&&... args) { - auto x = read_signed(is, a0.m, a0.M); - if (is.fail()) return; - a0.i = x; - read(is, std::forward(args)...); -} - -template -void read(std::basic_istream& is, ru a0, Args&&... args) { - auto x = read_unsigned(is, a0.m, a0.M); - if (is.fail()) return; - a0.i = static_cast(x); - read(is, std::forward(args)...); -} - -template -void read(std::basic_istream& is, int a0, Args&&... args) { - if (a0 != -1) { - auto u = static_cast(a0); - CharT buf[std::numeric_limits::digits10 + 2u] = {}; - auto e = buf; - do { - *e++ = static_cast(CharT(u % 10) + CharT{'0'}); - u /= 10; - } while (u > 0); - std::reverse(buf, e); - for (auto p = buf; p != e && is.rdstate() == std::ios::goodbit; ++p) read(is, *p); - } - if (is.rdstate() == std::ios::goodbit) read(is, std::forward(args)...); -} - -template -void read(std::basic_istream& is, rld a0, Args&&... args) { - auto x = read_long_double(is, a0.m, a0.M); - if (is.fail()) return; - a0.i = x; - read(is, std::forward(args)...); -} - -template -inline void checked_set(T& value, T from, T not_a_value, std::basic_ios& is) { - if (!is.fail()) { - if (value == not_a_value) - value = std::move(from); - else if (value != from) - is.setstate(std::ios::failbit); - } -} - -} // namespace detail - -template > -std::basic_istream& from_stream(std::basic_istream& is, const CharT* fmt, fields& fds, - std::basic_string* abbrev, std::chrono::minutes* offset) { - using std::ios; - using std::numeric_limits; - using std::chrono::duration; - using std::chrono::duration_cast; - using std::chrono::hours; - using std::chrono::minutes; - using std::chrono::seconds; - typename std::basic_istream::sentry ok{is, true}; - if (ok) { - date::detail::save_istream ss(is); - is.fill(' '); - is.flags(std::ios::skipws | std::ios::dec); - is.width(0); -#if !ONLY_C_LOCALE - auto& f = std::use_facet>(is.getloc()); - std::tm tm{}; -#endif - const CharT* command = nullptr; - auto modified = CharT{}; - auto width = -1; - - CONSTDATA int not_a_year = numeric_limits::min(); - CONSTDATA int not_a_2digit_year = 100; - CONSTDATA int not_a_century = not_a_year / 100; - CONSTDATA int not_a_month = 0; - CONSTDATA int not_a_day = 0; - CONSTDATA int not_a_hour = numeric_limits::min(); - CONSTDATA int not_a_hour_12_value = 0; - CONSTDATA int not_a_minute = not_a_hour; - CONSTDATA Duration not_a_second = Duration::min(); - CONSTDATA int not_a_doy = -1; - CONSTDATA int not_a_weekday = 8; - CONSTDATA int not_a_week_num = 100; - CONSTDATA int not_a_ampm = -1; - CONSTDATA minutes not_a_offset = minutes::min(); - - int Y = not_a_year; // c, F, Y * - int y = not_a_2digit_year; // D, x, y * - int g = not_a_2digit_year; // g * - int G = not_a_year; // G * - int C = not_a_century; // C * - int m = not_a_month; // b, B, h, m, c, D, F, x * - int d = not_a_day; // c, d, D, e, F, x * - int j = not_a_doy; // j * - int wd = not_a_weekday; // a, A, u, w * - int H = not_a_hour; // c, H, R, T, X * - int I = not_a_hour_12_value; // I, r * - int p = not_a_ampm; // p, r * - int M = not_a_minute; // c, M, r, R, T, X * - Duration s = not_a_second; // c, r, S, T, X * - int U = not_a_week_num; // U * - int V = not_a_week_num; // V * - int W = not_a_week_num; // W * - std::basic_string temp_abbrev; // Z * - minutes temp_offset = not_a_offset; // z * - - using detail::checked_set; - using detail::read; - using detail::rld; - using detail::rs; - using detail::ru; - for (; *fmt != CharT{} && !is.fail(); ++fmt) { - switch (*fmt) { - case 'a': - case 'A': - case 'u': - case 'w': // wd: a, A, u, w - if (command) { - int trial_wd = not_a_weekday; - if (*fmt == 'a' || *fmt == 'A') { - if (modified == CharT{}) { -#if !ONLY_C_LOCALE - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - is.setstate(err); - if (!is.fail()) trial_wd = tm.tm_wday; -#else - auto nm = detail::weekday_names(); - auto i = detail::scan_keyword(is, nm.first, nm.second) - nm.first; - if (!is.fail()) trial_wd = i % 7; -#endif - } else - read(is, CharT{'%'}, width, modified, *fmt); - } else // *fmt == 'u' || *fmt == 'w' - { -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#else - if (modified != CharT{'E'}) -#endif - { - read(is, ru{trial_wd, 1, width == -1 ? 1u : static_cast(width)}); - if (!is.fail()) { - if (*fmt == 'u') { - if (!(1 <= trial_wd && trial_wd <= 7)) { - trial_wd = not_a_weekday; - is.setstate(ios::failbit); - } else if (trial_wd == 7) - trial_wd = 0; - } else // *fmt == 'w' - { - if (!(0 <= trial_wd && trial_wd <= 6)) { - trial_wd = not_a_weekday; - is.setstate(ios::failbit); - } - } - } - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - is.setstate(err); - if (!is.fail()) trial_wd = tm.tm_wday; - } -#endif - else - read(is, CharT{'%'}, width, modified, *fmt); - } - if (trial_wd != not_a_weekday) checked_set(wd, trial_wd, not_a_weekday, is); - } else // !command - read(is, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - break; - case 'b': - case 'B': - case 'h': - if (command) { - if (modified == CharT{}) { - int ttm = not_a_month; -#if !ONLY_C_LOCALE - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - if ((err & ios::failbit) == 0) ttm = tm.tm_mon + 1; - is.setstate(err); -#else - auto nm = detail::month_names(); - auto i = detail::scan_keyword(is, nm.first, nm.second) - nm.first; - if (!is.fail()) ttm = i % 12 + 1; -#endif - checked_set(m, ttm, not_a_month, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'c': - if (command) { - if (modified != CharT{'O'}) { -#if !ONLY_C_LOCALE - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - if ((err & ios::failbit) == 0) { - checked_set(Y, tm.tm_year + 1900, not_a_year, is); - checked_set(m, tm.tm_mon + 1, not_a_month, is); - checked_set(d, tm.tm_mday, not_a_day, is); - checked_set(H, tm.tm_hour, not_a_hour, is); - checked_set(M, tm.tm_min, not_a_minute, is); - checked_set(s, duration_cast(seconds{tm.tm_sec}), not_a_second, is); - } - is.setstate(err); -#else - // "%a %b %e %T %Y" - auto nm = detail::weekday_names(); - auto i = detail::scan_keyword(is, nm.first, nm.second) - nm.first; - checked_set(wd, static_cast(i % 7), not_a_weekday, is); - ws(is); - nm = detail::month_names(); - i = detail::scan_keyword(is, nm.first, nm.second) - nm.first; - checked_set(m, static_cast(i % 12 + 1), not_a_month, is); - ws(is); - int td = not_a_day; - read(is, rs{td, 1, 2}); - checked_set(d, td, not_a_day, is); - ws(is); - using dfs = detail::decimal_format_seconds; - CONSTDATA auto w = Duration::period::den == 1 ? 2 : 3 + dfs::width; - int tH; - int tM; - long double S; - read(is, ru{tH, 1, 2}, CharT{':'}, ru{tM, 1, 2}, CharT{':'}, rld{S, 1, w}); - checked_set(H, tH, not_a_hour, is); - checked_set(M, tM, not_a_minute, is); - checked_set(s, round(duration{S}), not_a_second, is); - ws(is); - int tY = not_a_year; - read(is, rs{tY, 1, 4u}); - checked_set(Y, tY, not_a_year, is); -#endif - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'x': - if (command) { - if (modified != CharT{'O'}) { -#if !ONLY_C_LOCALE - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - if ((err & ios::failbit) == 0) { - checked_set(Y, tm.tm_year + 1900, not_a_year, is); - checked_set(m, tm.tm_mon + 1, not_a_month, is); - checked_set(d, tm.tm_mday, not_a_day, is); - } - is.setstate(err); -#else - // "%m/%d/%y" - int ty = not_a_2digit_year; - int tm = not_a_month; - int td = not_a_day; - read(is, ru{tm, 1, 2}, CharT{'/'}, ru{td, 1, 2}, CharT{'/'}, rs{ty, 1, 2}); - checked_set(y, ty, not_a_2digit_year, is); - checked_set(m, tm, not_a_month, is); - checked_set(d, td, not_a_day, is); -#endif - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'X': - if (command) { - if (modified != CharT{'O'}) { -#if !ONLY_C_LOCALE - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - if ((err & ios::failbit) == 0) { - checked_set(H, tm.tm_hour, not_a_hour, is); - checked_set(M, tm.tm_min, not_a_minute, is); - checked_set(s, duration_cast(seconds{tm.tm_sec}), not_a_second, is); - } - is.setstate(err); -#else - // "%T" - using dfs = detail::decimal_format_seconds; - CONSTDATA auto w = Duration::period::den == 1 ? 2 : 3 + dfs::width; - int tH = not_a_hour; - int tM = not_a_minute; - long double S; - read(is, ru{tH, 1, 2}, CharT{':'}, ru{tM, 1, 2}, CharT{':'}, rld{S, 1, w}); - checked_set(H, tH, not_a_hour, is); - checked_set(M, tM, not_a_minute, is); - checked_set(s, round(duration{S}), not_a_second, is); -#endif - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'C': - if (command) { - int tC = not_a_century; -#if !ONLY_C_LOCALE - if (modified == CharT{}) { -#endif - read(is, rs{tC, 1, width == -1 ? 2u : static_cast(width)}); -#if !ONLY_C_LOCALE - } else { - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - if ((err & ios::failbit) == 0) { - auto tY = tm.tm_year + 1900; - tC = (tY >= 0 ? tY : tY - 99) / 100; - } - is.setstate(err); - } -#endif - checked_set(C, tC, not_a_century, is); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'D': - if (command) { - if (modified == CharT{}) { - int tn = not_a_month; - int td = not_a_day; - int ty = not_a_2digit_year; - read(is, ru{tn, 1, 2}, CharT{'\0'}, CharT{'/'}, CharT{'\0'}, ru{td, 1, 2}, CharT{'\0'}, CharT{'/'}, CharT{'\0'}, rs{ty, 1, 2}); - checked_set(y, ty, not_a_2digit_year, is); - checked_set(m, tn, not_a_month, is); - checked_set(d, td, not_a_day, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'F': - if (command) { - if (modified == CharT{}) { - int tY = not_a_year; - int tn = not_a_month; - int td = not_a_day; - read(is, rs{tY, 1, width == -1 ? 4u : static_cast(width)}, CharT{'-'}, ru{tn, 1, 2}, CharT{'-'}, ru{td, 1, 2}); - checked_set(Y, tY, not_a_year, is); - checked_set(m, tn, not_a_month, is); - checked_set(d, td, not_a_day, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'd': - case 'e': - if (command) { -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#else - if (modified != CharT{'E'}) -#endif - { - int td = not_a_day; - read(is, rs{td, 1, width == -1 ? 2u : static_cast(width)}); - checked_set(d, td, not_a_day, is); - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - command = nullptr; - width = -1; - modified = CharT{}; - if ((err & ios::failbit) == 0) checked_set(d, tm.tm_mday, not_a_day, is); - is.setstate(err); - } -#endif - else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'H': - if (command) { -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#else - if (modified != CharT{'E'}) -#endif - { - int tH = not_a_hour; - read(is, ru{tH, 1, width == -1 ? 2u : static_cast(width)}); - checked_set(H, tH, not_a_hour, is); - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - if ((err & ios::failbit) == 0) checked_set(H, tm.tm_hour, not_a_hour, is); - is.setstate(err); - } -#endif - else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'I': - if (command) { - if (modified == CharT{}) { - int tI = not_a_hour_12_value; - // reads in an hour into I, but most be in [1, 12] - read(is, rs{tI, 1, width == -1 ? 2u : static_cast(width)}); - if (!(1 <= tI && tI <= 12)) is.setstate(ios::failbit); - checked_set(I, tI, not_a_hour_12_value, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'j': - if (command) { - if (modified == CharT{}) { - int tj = not_a_doy; - read(is, ru{tj, 1, width == -1 ? 3u : static_cast(width)}); - checked_set(j, tj, not_a_doy, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'M': - if (command) { -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#else - if (modified != CharT{'E'}) -#endif - { - int tM = not_a_minute; - read(is, ru{tM, 1, width == -1 ? 2u : static_cast(width)}); - checked_set(M, tM, not_a_minute, is); - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - if ((err & ios::failbit) == 0) checked_set(M, tm.tm_min, not_a_minute, is); - is.setstate(err); - } -#endif - else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'm': - if (command) { -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#else - if (modified != CharT{'E'}) -#endif - { - int tn = not_a_month; - read(is, rs{tn, 1, width == -1 ? 2u : static_cast(width)}); - checked_set(m, tn, not_a_month, is); - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - if ((err & ios::failbit) == 0) checked_set(m, tm.tm_mon + 1, not_a_month, is); - is.setstate(err); - } -#endif - else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'n': - case 't': - if (command) { - if (modified == CharT{}) { - // %n matches a single white space character - // %t matches 0 or 1 white space characters - auto ic = is.peek(); - if (Traits::eq_int_type(ic, Traits::eof())) { - ios::iostate err = ios::eofbit; - if (*fmt == 'n') err |= ios::failbit; - is.setstate(err); - break; - } - if (isspace(ic)) { - (void)is.get(); - } else if (*fmt == 'n') - is.setstate(ios::failbit); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'p': - if (command) { - if (modified == CharT{}) { - int tp = not_a_ampm; -#if !ONLY_C_LOCALE - tm = std::tm{}; - tm.tm_hour = 1; - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - is.setstate(err); - if (tm.tm_hour == 1) - tp = 0; - else if (tm.tm_hour == 13) - tp = 1; - else - is.setstate(err); -#else - auto nm = detail::ampm_names(); - auto i = detail::scan_keyword(is, nm.first, nm.second) - nm.first; - tp = i; -#endif - checked_set(p, tp, not_a_ampm, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - - break; - case 'r': - if (command) { - if (modified == CharT{}) { -#if !ONLY_C_LOCALE - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - if ((err & ios::failbit) == 0) { - checked_set(H, tm.tm_hour, not_a_hour, is); - checked_set(M, tm.tm_min, not_a_hour, is); - checked_set(s, duration_cast(seconds{tm.tm_sec}), not_a_second, is); - } - is.setstate(err); -#else - // "%I:%M:%S %p" - using dfs = detail::decimal_format_seconds; - CONSTDATA auto w = Duration::period::den == 1 ? 2 : 3 + dfs::width; - long double S; - int tI = not_a_hour_12_value; - int tM = not_a_minute; - read(is, ru{tI, 1, 2}, CharT{':'}, ru{tM, 1, 2}, CharT{':'}, rld{S, 1, w}); - checked_set(I, tI, not_a_hour_12_value, is); - checked_set(M, tM, not_a_minute, is); - checked_set(s, round(duration{S}), not_a_second, is); - ws(is); - auto nm = detail::ampm_names(); - auto i = detail::scan_keyword(is, nm.first, nm.second) - nm.first; - checked_set(p, static_cast(i), not_a_ampm, is); -#endif - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'R': - if (command) { - if (modified == CharT{}) { - int tH = not_a_hour; - int tM = not_a_minute; - read(is, ru{tH, 1, 2}, CharT{'\0'}, CharT{':'}, CharT{'\0'}, ru{tM, 1, 2}, CharT{'\0'}); - checked_set(H, tH, not_a_hour, is); - checked_set(M, tM, not_a_minute, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'S': - if (command) { -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#else - if (modified != CharT{'E'}) -#endif - { - using dfs = detail::decimal_format_seconds; - CONSTDATA auto w = Duration::period::den == 1 ? 2 : 3 + dfs::width; - long double S; - read(is, rld{S, 1, width == -1 ? w : static_cast(width)}); - checked_set(s, round(duration{S}), not_a_second, is); - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'O'}) { - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - if ((err & ios::failbit) == 0) checked_set(s, duration_cast(seconds{tm.tm_sec}), not_a_second, is); - is.setstate(err); - } -#endif - else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'T': - if (command) { - if (modified == CharT{}) { - using dfs = detail::decimal_format_seconds; - CONSTDATA auto w = Duration::period::den == 1 ? 2 : 3 + dfs::width; - int tH = not_a_hour; - int tM = not_a_minute; - long double S; - read(is, ru{tH, 1, 2}, CharT{':'}, ru{tM, 1, 2}, CharT{':'}, rld{S, 1, w}); - checked_set(H, tH, not_a_hour, is); - checked_set(M, tM, not_a_minute, is); - checked_set(s, round(duration{S}), not_a_second, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'Y': - if (command) { -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#else - if (modified != CharT{'O'}) -#endif - { - int tY = not_a_year; - read(is, rs{tY, 1, width == -1 ? 4u : static_cast(width)}); - checked_set(Y, tY, not_a_year, is); - } -#if !ONLY_C_LOCALE - else if (modified == CharT{'E'}) { - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - if ((err & ios::failbit) == 0) checked_set(Y, tm.tm_year + 1900, not_a_year, is); - is.setstate(err); - } -#endif - else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'y': - if (command) { -#if !ONLY_C_LOCALE - if (modified == CharT{}) -#endif - { - int ty = not_a_2digit_year; - read(is, ru{ty, 1, width == -1 ? 2u : static_cast(width)}); - checked_set(y, ty, not_a_2digit_year, is); - } -#if !ONLY_C_LOCALE - else { - ios::iostate err = ios::goodbit; - f.get(is, nullptr, is, err, &tm, command, fmt + 1); - if ((err & ios::failbit) == 0) checked_set(Y, tm.tm_year + 1900, not_a_year, is); - is.setstate(err); - } -#endif - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'g': - if (command) { - if (modified == CharT{}) { - int tg = not_a_2digit_year; - read(is, ru{tg, 1, width == -1 ? 2u : static_cast(width)}); - checked_set(g, tg, not_a_2digit_year, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'G': - if (command) { - if (modified == CharT{}) { - int tG = not_a_year; - read(is, rs{tG, 1, width == -1 ? 4u : static_cast(width)}); - checked_set(G, tG, not_a_year, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'U': - if (command) { - if (modified == CharT{}) { - int tU = not_a_week_num; - read(is, ru{tU, 1, width == -1 ? 2u : static_cast(width)}); - checked_set(U, tU, not_a_week_num, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'V': - if (command) { - if (modified == CharT{}) { - int tV = not_a_week_num; - read(is, ru{tV, 1, width == -1 ? 2u : static_cast(width)}); - checked_set(V, tV, not_a_week_num, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'W': - if (command) { - if (modified == CharT{}) { - int tW = not_a_week_num; - read(is, ru{tW, 1, width == -1 ? 2u : static_cast(width)}); - checked_set(W, tW, not_a_week_num, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'E': - case 'O': - if (command) { - if (modified == CharT{}) { - modified = *fmt; - } else { - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } - } else - read(is, *fmt); - break; - case '%': - if (command) { - if (modified == CharT{}) - read(is, *fmt); - else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - command = fmt; - break; - case 'z': - if (command) { - int tH, tM; - minutes toff = not_a_offset; - bool neg = false; - auto ic = is.peek(); - if (!Traits::eq_int_type(ic, Traits::eof())) { - auto c = static_cast(Traits::to_char_type(ic)); - if (c == '-') neg = true; - } - if (modified == CharT{}) { - read(is, rs{tH, 2, 2}); - if (!is.fail()) toff = hours{std::abs(tH)}; - if (is.good()) { - ic = is.peek(); - if (!Traits::eq_int_type(ic, Traits::eof())) { - auto c = static_cast(Traits::to_char_type(ic)); - if ('0' <= c && c <= '9') { - read(is, ru{tM, 2, 2}); - if (!is.fail()) toff += minutes{tM}; - } - } - } - } else { - read(is, rs{tH, 1, 2}); - if (!is.fail()) toff = hours{std::abs(tH)}; - if (is.good()) { - ic = is.peek(); - if (!Traits::eq_int_type(ic, Traits::eof())) { - auto c = static_cast(Traits::to_char_type(ic)); - if (c == ':') { - (void)is.get(); - read(is, ru{tM, 2, 2}); - if (!is.fail()) toff += minutes{tM}; - } - } - } - } - if (neg) toff = -toff; - checked_set(temp_offset, toff, not_a_offset, is); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - case 'Z': - if (command) { - if (modified == CharT{}) { - std::basic_string buf; - while (is.rdstate() == std::ios::goodbit) { - auto i = is.rdbuf()->sgetc(); - if (Traits::eq_int_type(i, Traits::eof())) { - is.setstate(ios::eofbit); - break; - } - auto wc = Traits::to_char_type(i); - auto c = static_cast(wc); - // is c a valid time zone name or abbreviation character? - if (!(CharT{1} < wc && wc < CharT{127}) || !(isalnum(c) || c == '_' || c == '/' || c == '-' || c == '+')) break; - buf.push_back(c); - is.rdbuf()->sbumpc(); - } - if (buf.empty()) is.setstate(ios::failbit); - checked_set(temp_abbrev, buf, {}, is); - } else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } else - read(is, *fmt); - break; - default: - if (command) { - if (width == -1 && modified == CharT{} && '0' <= *fmt && *fmt <= '9') { - width = static_cast(*fmt) - '0'; - while ('0' <= fmt[1] && fmt[1] <= '9') width = 10 * width + static_cast(*++fmt) - '0'; - } else { - if (modified == CharT{}) - read(is, CharT{'%'}, width, *fmt); - else - read(is, CharT{'%'}, width, modified, *fmt); - command = nullptr; - width = -1; - modified = CharT{}; - } - } else // !command - { - if (isspace(static_cast(*fmt))) { - // space matches 0 or more white space characters - if (is.good()) ws(is); - } else - read(is, *fmt); - } - break; - } - } - // is.fail() || *fmt == CharT{} - if (is.rdstate() == ios::goodbit && command) { - if (modified == CharT{}) - read(is, CharT{'%'}, width); - else - read(is, CharT{'%'}, width, modified); - } - if (!is.fail()) { - if (y != not_a_2digit_year) { - // Convert y and an optional C to Y - if (!(0 <= y && y <= 99)) goto broken; - if (C == not_a_century) { - if (Y == not_a_year) { - if (y >= 69) - C = 19; - else - C = 20; - } else { - C = (Y >= 0 ? Y : Y - 100) / 100; - } - } - int tY; - if (C >= 0) - tY = 100 * C + y; - else - tY = 100 * (C + 1) - (y == 0 ? 100 : y); - if (Y != not_a_year && Y != tY) goto broken; - Y = tY; - } - if (g != not_a_2digit_year) { - // Convert g and an optional C to G - if (!(0 <= g && g <= 99)) goto broken; - if (C == not_a_century) { - if (G == not_a_year) { - if (g >= 69) - C = 19; - else - C = 20; - } else { - C = (G >= 0 ? G : G - 100) / 100; - } - } - int tG; - if (C >= 0) - tG = 100 * C + g; - else - tG = 100 * (C + 1) - (g == 0 ? 100 : g); - if (G != not_a_year && G != tG) goto broken; - G = tG; - } - if (Y < static_cast(year::min()) || Y > static_cast(year::max())) Y = not_a_year; - bool computed = false; - if (G != not_a_year && V != not_a_week_num && wd != not_a_weekday) { - year_month_day ymd_trial = - sys_days(year{G - 1} / December / Thursday[last]) + (Monday - Thursday) + weeks{V - 1} + (weekday{static_cast(wd)} - Monday); - if (Y == not_a_year) - Y = static_cast(ymd_trial.year()); - else if (year{Y} != ymd_trial.year()) - goto broken; - if (m == not_a_month) - m = static_cast(static_cast(ymd_trial.month())); - else if (month(static_cast(m)) != ymd_trial.month()) - goto broken; - if (d == not_a_day) - d = static_cast(static_cast(ymd_trial.day())); - else if (day(static_cast(d)) != ymd_trial.day()) - goto broken; - computed = true; - } - if (Y != not_a_year && U != not_a_week_num && wd != not_a_weekday) { - year_month_day ymd_trial = sys_days(year{Y} / January / Sunday[1]) + weeks{U - 1} + (weekday{static_cast(wd)} - Sunday); - if (Y == not_a_year) - Y = static_cast(ymd_trial.year()); - else if (year{Y} != ymd_trial.year()) - goto broken; - if (m == not_a_month) - m = static_cast(static_cast(ymd_trial.month())); - else if (month(static_cast(m)) != ymd_trial.month()) - goto broken; - if (d == not_a_day) - d = static_cast(static_cast(ymd_trial.day())); - else if (day(static_cast(d)) != ymd_trial.day()) - goto broken; - computed = true; - } - if (Y != not_a_year && W != not_a_week_num && wd != not_a_weekday) { - year_month_day ymd_trial = sys_days(year{Y} / January / Monday[1]) + weeks{W - 1} + (weekday{static_cast(wd)} - Monday); - if (Y == not_a_year) - Y = static_cast(ymd_trial.year()); - else if (year{Y} != ymd_trial.year()) - goto broken; - if (m == not_a_month) - m = static_cast(static_cast(ymd_trial.month())); - else if (month(static_cast(m)) != ymd_trial.month()) - goto broken; - if (d == not_a_day) - d = static_cast(static_cast(ymd_trial.day())); - else if (day(static_cast(d)) != ymd_trial.day()) - goto broken; - computed = true; - } - if (j != not_a_doy && Y != not_a_year) { - auto ymd_trial = year_month_day{local_days(year{Y} / 1 / 1) + days{j - 1}}; - if (m == 0) - m = static_cast(static_cast(ymd_trial.month())); - else if (month(static_cast(m)) != ymd_trial.month()) - goto broken; - if (d == 0) - d = static_cast(static_cast(ymd_trial.day())); - else if (day(static_cast(d)) != ymd_trial.day()) - goto broken; - j = not_a_doy; - } - auto ymd = year{Y} / m / d; - if (ymd.ok()) { - if (wd == not_a_weekday) - wd = static_cast((weekday(sys_days(ymd)) - Sunday).count()); - else if (wd != static_cast((weekday(sys_days(ymd)) - Sunday).count())) - goto broken; - if (!computed) { - if (G != not_a_year || V != not_a_week_num) { - sys_days sd = ymd; - auto G_trial = year_month_day{sd + days{3}}.year(); - auto start = sys_days((G_trial - years{1}) / December / Thursday[last]) + (Monday - Thursday); - if (sd < start) { - --G_trial; - if (V != not_a_week_num) start = sys_days((G_trial - years{1}) / December / Thursday[last]) + (Monday - Thursday); - } - if (G != not_a_year && G != static_cast(G_trial)) goto broken; - if (V != not_a_week_num) { - auto V_trial = duration_cast(sd - start).count() + 1; - if (V != V_trial) goto broken; - } - } - if (U != not_a_week_num) { - auto start = sys_days(Sunday[1] / January / ymd.year()); - auto U_trial = floor(sys_days(ymd) - start).count() + 1; - if (U != U_trial) goto broken; - } - if (W != not_a_week_num) { - auto start = sys_days(Monday[1] / January / ymd.year()); - auto W_trial = floor(sys_days(ymd) - start).count() + 1; - if (W != W_trial) goto broken; - } - } - } - fds.ymd = ymd; - if (I != not_a_hour_12_value) { - if (!(1 <= I && I <= 12)) goto broken; - if (p != not_a_ampm) { - // p is in [0, 1] == [AM, PM] - // Store trial H in I - if (I == 12) --p; - I += p * 12; - // Either set H from I or make sure H and I are consistent - if (H == not_a_hour) - H = I; - else if (I != H) - goto broken; - } else // p == not_a_ampm - { - // if H, make sure H and I could be consistent - if (H != not_a_hour) { - if (I == 12) { - if (H != 0 && H != 12) goto broken; - } else if (!(I == H || I == H + 12)) { - goto broken; - } - } - } - } - if (H != not_a_hour) { - fds.has_tod = true; - fds.tod = hh_mm_ss{hours{H}}; - } - if (M != not_a_minute) { - fds.has_tod = true; - fds.tod.m_ = minutes{M}; - } - if (s != not_a_second) { - fds.has_tod = true; - fds.tod.s_ = detail::decimal_format_seconds{s}; - } - if (j != not_a_doy) { - fds.has_tod = true; - fds.tod.h_ += hours{days{j}}; - } - if (wd != not_a_weekday) fds.wd = weekday{static_cast(wd)}; - if (abbrev != nullptr) *abbrev = std::move(temp_abbrev); - if (offset != nullptr && temp_offset != not_a_offset) *offset = temp_offset; - } - return is; - } -broken: - is.setstate(ios::failbit); - return is; -} - -template > -std::basic_istream& from_stream(std::basic_istream& is, const CharT* fmt, year& y, - std::basic_string* abbrev = nullptr, std::chrono::minutes* offset = nullptr) { - using CT = std::chrono::seconds; - fields fds{}; - from_stream(is, fmt, fds, abbrev, offset); - if (!fds.ymd.year().ok()) is.setstate(std::ios::failbit); - if (!is.fail()) y = fds.ymd.year(); - return is; -} - -template > -std::basic_istream& from_stream(std::basic_istream& is, const CharT* fmt, month& m, - std::basic_string* abbrev = nullptr, std::chrono::minutes* offset = nullptr) { - using CT = std::chrono::seconds; - fields fds{}; - from_stream(is, fmt, fds, abbrev, offset); - if (!fds.ymd.month().ok()) is.setstate(std::ios::failbit); - if (!is.fail()) m = fds.ymd.month(); - return is; -} - -template > -std::basic_istream& from_stream(std::basic_istream& is, const CharT* fmt, day& d, - std::basic_string* abbrev = nullptr, std::chrono::minutes* offset = nullptr) { - using CT = std::chrono::seconds; - fields fds{}; - from_stream(is, fmt, fds, abbrev, offset); - if (!fds.ymd.day().ok()) is.setstate(std::ios::failbit); - if (!is.fail()) d = fds.ymd.day(); - return is; -} - -template > -std::basic_istream& from_stream(std::basic_istream& is, const CharT* fmt, weekday& wd, - std::basic_string* abbrev = nullptr, std::chrono::minutes* offset = nullptr) { - using CT = std::chrono::seconds; - fields fds{}; - from_stream(is, fmt, fds, abbrev, offset); - if (!fds.wd.ok()) is.setstate(std::ios::failbit); - if (!is.fail()) wd = fds.wd; - return is; -} - -template > -std::basic_istream& from_stream(std::basic_istream& is, const CharT* fmt, year_month& ym, - std::basic_string* abbrev = nullptr, std::chrono::minutes* offset = nullptr) { - using CT = std::chrono::seconds; - fields fds{}; - from_stream(is, fmt, fds, abbrev, offset); - if (!fds.ymd.month().ok()) is.setstate(std::ios::failbit); - if (!is.fail()) ym = fds.ymd.year() / fds.ymd.month(); - return is; -} - -template > -std::basic_istream& from_stream(std::basic_istream& is, const CharT* fmt, month_day& md, - std::basic_string* abbrev = nullptr, std::chrono::minutes* offset = nullptr) { - using CT = std::chrono::seconds; - fields fds{}; - from_stream(is, fmt, fds, abbrev, offset); - if (!fds.ymd.month().ok() || !fds.ymd.day().ok()) is.setstate(std::ios::failbit); - if (!is.fail()) md = fds.ymd.month() / fds.ymd.day(); - return is; -} - -template > -std::basic_istream& from_stream(std::basic_istream& is, const CharT* fmt, year_month_day& ymd, - std::basic_string* abbrev = nullptr, std::chrono::minutes* offset = nullptr) { - using CT = std::chrono::seconds; - fields fds{}; - from_stream(is, fmt, fds, abbrev, offset); - if (!fds.ymd.ok()) is.setstate(std::ios::failbit); - if (!is.fail()) ymd = fds.ymd; - return is; -} - -template > -std::basic_istream& from_stream(std::basic_istream& is, const CharT* fmt, sys_time& tp, - std::basic_string* abbrev = nullptr, std::chrono::minutes* offset = nullptr) { - using CT = typename std::common_type::type; - std::chrono::minutes offset_local{}; - auto offptr = offset ? offset : &offset_local; - fields fds{}; - fds.has_tod = true; - from_stream(is, fmt, fds, abbrev, offptr); - if (!fds.ymd.ok() || !fds.tod.in_conventional_range()) is.setstate(std::ios::failbit); - if (!is.fail()) tp = round(sys_days(fds.ymd) - *offptr + fds.tod.to_duration()); - return is; -} - -template > -std::basic_istream& from_stream(std::basic_istream& is, const CharT* fmt, local_time& tp, - std::basic_string* abbrev = nullptr, std::chrono::minutes* offset = nullptr) { - using CT = typename std::common_type::type; - fields fds{}; - fds.has_tod = true; - from_stream(is, fmt, fds, abbrev, offset); - if (!fds.ymd.ok() || !fds.tod.in_conventional_range()) is.setstate(std::ios::failbit); - if (!is.fail()) tp = round(local_seconds{local_days(fds.ymd)} + fds.tod.to_duration()); - return is; -} - -template > -std::basic_istream& from_stream(std::basic_istream& is, const CharT* fmt, std::chrono::duration& d, - std::basic_string* abbrev = nullptr, std::chrono::minutes* offset = nullptr) { - using Duration = std::chrono::duration; - using CT = typename std::common_type::type; - fields fds{}; - from_stream(is, fmt, fds, abbrev, offset); - if (!fds.has_tod) is.setstate(std::ios::failbit); - if (!is.fail()) d = std::chrono::duration_cast(fds.tod.to_duration()); - return is; -} - -template , class Alloc = std::allocator> -struct parse_manip { - const std::basic_string format_; - Parsable& tp_; - std::basic_string* abbrev_; - std::chrono::minutes* offset_; - - public: - parse_manip(std::basic_string format, Parsable& tp, std::basic_string* abbrev = nullptr, - std::chrono::minutes* offset = nullptr) - : format_(std::move(format)), tp_(tp), abbrev_(abbrev), offset_(offset) {} -}; - -template -std::basic_istream& operator>>(std::basic_istream& is, const parse_manip& x) { - return from_stream(is, x.format_.c_str(), x.tp_, x.abbrev_, x.offset_); -} - -template -inline auto parse(const std::basic_string& format, Parsable& tp) - -> decltype(from_stream(std::declval&>(), format.c_str(), tp), parse_manip{format, tp}) { - return {format, tp}; -} - -template -inline auto parse(const std::basic_string& format, Parsable& tp, std::basic_string& abbrev) - -> decltype(from_stream(std::declval&>(), format.c_str(), tp, &abbrev), - parse_manip{format, tp, &abbrev}) { - return {format, tp, &abbrev}; -} - -template -inline auto parse(const std::basic_string& format, Parsable& tp, std::chrono::minutes& offset) - -> decltype(from_stream(std::declval&>(), format.c_str(), tp, std::declval*>(), - &offset), - parse_manip{format, tp, nullptr, &offset}) { - return {format, tp, nullptr, &offset}; -} - -template -inline auto parse(const std::basic_string& format, Parsable& tp, std::basic_string& abbrev, - std::chrono::minutes& offset) - -> decltype(from_stream(std::declval&>(), format.c_str(), tp, &abbrev, &offset), - parse_manip{format, tp, &abbrev, &offset}) { - return {format, tp, &abbrev, &offset}; -} - -// const CharT* formats - -template -inline auto parse(const CharT* format, Parsable& tp) - -> decltype(from_stream(std::declval&>(), format, tp), parse_manip{format, tp}) { - return {format, tp}; -} - -template -inline auto parse(const CharT* format, Parsable& tp, std::basic_string& abbrev) - -> decltype(from_stream(std::declval&>(), format, tp, &abbrev), - parse_manip{format, tp, &abbrev}) { - return {format, tp, &abbrev}; -} - -template -inline auto parse(const CharT* format, Parsable& tp, std::chrono::minutes& offset) - -> decltype(from_stream(std::declval&>(), format, tp, std::declval*>(), &offset), - parse_manip{format, tp, nullptr, &offset}) { - return {format, tp, nullptr, &offset}; -} - -template -inline auto parse(const CharT* format, Parsable& tp, std::basic_string& abbrev, std::chrono::minutes& offset) - -> decltype(from_stream(std::declval&>(), format, tp, &abbrev, &offset), - parse_manip{format, tp, &abbrev, &offset}) { - return {format, tp, &abbrev, &offset}; -} - -// duration streaming - -template -inline std::basic_ostream& operator<<(std::basic_ostream& os, const std::chrono::duration& d) { - return os << detail::make_string::from(d.count()) + detail::get_units(typename Period::type{}); -} - -} // namespace date - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif - -#endif diff --git a/linux/include/ccapi_cpp/ccapi_decimal.h b/linux/include/ccapi_cpp/ccapi_decimal.h index 4bd5e733a..a5f8fd60c 100644 --- a/linux/include/ccapi_cpp/ccapi_decimal.h +++ b/linux/include/ccapi_cpp/ccapi_decimal.h @@ -2,6 +2,7 @@ #define INCLUDE_CCAPI_CPP_CCAPI_DECIMAL_H_ #include +#include "ccapi_cpp/ccapi_logger.h" #include "ccapi_cpp/ccapi_util_private.h" namespace ccapi { /** diff --git a/linux/include/ccapi_cpp/ccapi_event_handler.h b/linux/include/ccapi_cpp/ccapi_event_handler.h index 5b81f9140..034c06bdc 100644 --- a/linux/include/ccapi_cpp/ccapi_event_handler.h +++ b/linux/include/ccapi_cpp/ccapi_event_handler.h @@ -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 diff --git a/linux/include/ccapi_cpp/ccapi_fix_connection.h b/linux/include/ccapi_cpp/ccapi_fix_connection.h index 32d10ae27..4fe4ee3ea 100644 --- a/linux/include/ccapi_cpp/ccapi_fix_connection.h +++ b/linux/include/ccapi_cpp/ccapi_fix_connection.h @@ -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 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 streamPtr) : host(host), port(port), subscription(subscription), streamPtr(streamPtr) { diff --git a/linux/include/ccapi_cpp/ccapi_http_connection.h b/linux/include/ccapi_cpp/ccapi_http_connection.h index c8dfde833..95f38623a 100644 --- a/linux/include/ccapi_cpp/ccapi_http_connection.h +++ b/linux/include/ccapi_cpp/ccapi_http_connection.h @@ -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 > streamPtr; + TimePoint lastReceiveDataTp{std::chrono::seconds{0}}; }; } /* namespace ccapi */ #endif // INCLUDE_CCAPI_CPP_CCAPI_HTTP_CONNECTION_H_ diff --git a/linux/include/ccapi_cpp/ccapi_logger.h b/linux/include/ccapi_cpp/ccapi_logger.h index 676ddde25..aad4748b8 100644 --- a/linux/include/ccapi_cpp/ccapi_logger.h +++ b/linux/include/ccapi_cpp/ccapi_logger.h @@ -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 +#include #include #include -#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 - static std::string getISOTimestamp(const TimePoint& tp, const std::string& fmt = "%FT%TZ") { - return date::format(fmt.c_str(), date::floor(tp)); + this->logMessage(severity, ss.str(), UtilTime::getISOTimestamp(time), fileName, lineNumber, message); } }; } /* namespace ccapi */ diff --git a/linux/include/ccapi_cpp/ccapi_macro.h b/linux/include/ccapi_cpp/ccapi_macro.h index 0f1655aab..fe1307b00 100644 --- a/linux/include/ccapi_cpp/ccapi_macro.h +++ b/linux/include/ccapi_cpp/ccapi_macro.h @@ -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_ diff --git a/linux/include/ccapi_cpp/ccapi_market_data_message.h b/linux/include/ccapi_cpp/ccapi_market_data_message.h index f9a8a12dd..721098ed9 100644 --- a/linux/include/ccapi_cpp/ccapi_market_data_message.h +++ b/linux/include/ccapi_cpp/ccapi_market_data_message.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); } diff --git a/linux/include/ccapi_cpp/ccapi_message.h b/linux/include/ccapi_cpp/ccapi_message.h index 4fb3c26dc..849ccd7fa 100644 --- a/linux/include/ccapi_cpp/ccapi_message.h +++ b/linux/include/ccapi_cpp/ccapi_message.h @@ -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; diff --git a/linux/include/ccapi_cpp/ccapi_queue.h b/linux/include/ccapi_cpp/ccapi_queue.h index bbcf5810e..f1657a825 100644 --- a/linux/include/ccapi_cpp/ccapi_queue.h +++ b/linux/include/ccapi_cpp/ccapi_queue.h @@ -6,15 +6,26 @@ #include "ccapi_cpp/ccapi_logger.h" namespace ccapi { -template /** * This class represents a generic FIFO queue. */ +template 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 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 lock(this->m); diff --git a/linux/include/ccapi_cpp/ccapi_request.h b/linux/include/ccapi_cpp/ccapi_request.h index 19905e96d..d2e4f14f3 100644 --- a/linux/include/ccapi_cpp/ccapi_request.h +++ b/linux/include/ccapi_cpp/ccapi_request.h @@ -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(operation) >= operationTypeExecutionManagement ? CCAPI_EXECUTION_MANAGEMENT : CCAPI_MARKET_DATA; + this->serviceName = static_cast(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 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& 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 > > 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_ diff --git a/linux/include/ccapi_cpp/ccapi_session.h b/linux/include/ccapi_cpp/ccapi_session.h index f280f7486..0bc7bd494 100644 --- a/linux/include/ccapi_cpp/ccapi_session.h +++ b/linux/include/ccapi_cpp/ccapi_session.h @@ -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(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(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); -#endif #ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX this->serviceByServiceNameExchangeMap[CCAPI_MARKET_DATA][CCAPI_EXCHANGE_NAME_ASCENDEX] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); @@ -537,10 +540,6 @@ class Session { this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_BYBIT] = std::make_shared(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(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); -#endif #ifdef CCAPI_ENABLE_EXCHANGE_ASCENDEX this->serviceByServiceNameExchangeMap[CCAPI_EXECUTION_MANAGEMENT][CCAPI_EXCHANGE_NAME_ASCENDEX] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); @@ -576,10 +575,10 @@ class Session { this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_COINBASE] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif -#ifdef CCAPI_ENABLE_EXCHANGE_GEMINI - this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_GEMINI] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); -#endif +// #ifdef CCAPI_ENABLE_EXCHANGE_GEMINI +// this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_GEMINI] = +// std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); +// #endif #ifdef CCAPI_ENABLE_EXCHANGE_FTX this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_FTX] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); @@ -588,10 +587,10 @@ class Session { this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_FTX_US] = std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); #endif -#ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT - this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_DERIBIT] = - std::make_shared(this->internalEventHandler, sessionOptions, sessionConfigs, this->serviceContextPtr); -#endif +// #ifdef CCAPI_ENABLE_EXCHANGE_DERIBIT +// this->serviceByServiceNameExchangeMap[CCAPI_FIX][CCAPI_EXCHANGE_NAME_DERIBIT] = +// std::make_shared(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& 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 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 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 > subscriptionListByServiceNameMap; for (const auto& subscription : subscriptionList) { auto serviceName = subscription.getServiceName(); @@ -637,19 +664,10 @@ class Session { return; } if (serviceName == CCAPI_MARKET_DATA) { - std::set correlationIdSet; - std::set duplicateCorrelationIdSet; std::unordered_set unsupportedExchangeFieldSet; - std::map > 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 > subscriptionListByExchangeMap; for (const auto& subscription : subscriptionList) { auto exchange = subscription.getExchange(); - if (exchange == CCAPI_EXCHANGE_NAME_BYBIT_DERIVATIVES) { - const auto& instrumentType = subscription.getInstrumentType(); - std::vector 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* eventQueuePtr = nullptr, long delayMilliSeconds = 0) { + virtual void sendRequest(Request& request, Queue* eventQueuePtr = nullptr, long delayMilliseconds = 0) { CCAPI_LOGGER_FUNCTION_ENTER; std::vector requestList({request}); - this->sendRequest(requestList, eventQueuePtr, delayMilliSeconds); + this->sendRequest(requestList, eventQueuePtr, delayMilliseconds); CCAPI_LOGGER_FUNCTION_EXIT; } - virtual void sendRequest(std::vector& requestList, Queue* eventQueuePtr = nullptr, long delayMilliSeconds = 0) { + virtual void sendRequest(std::vector& requestList, Queue* eventQueuePtr = nullptr, long delayMilliseconds = 0) { CCAPI_LOGGER_FUNCTION_ENTER; std::vector > > futurePtrList; // std::set 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 errorHandler, + virtual void setImmediate(std::function 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 errorHandler, std::function successHandler) { - boost::asio::post(*this->serviceContextPtr->ioContextPtr, [this, id, delayMilliSeconds, errorHandler, successHandler]() { - std::shared_ptr 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 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 serviceContextPtr; + ServiceContext* serviceContextPtr{nullptr}; std::map > > serviceByServiceNameExchangeMap; std::thread t; Queue eventQueue; diff --git a/linux/include/ccapi_cpp/ccapi_session_configs.h b/linux/include/ccapi_cpp/ccapi_session_configs.h index dc77aa6b5..ca66bd3f8 100644 --- a/linux/include/ccapi_cpp/ccapi_session_configs.h +++ b/linux/include/ccapi_cpp/ccapi_session_configs.h @@ -47,6 +47,7 @@ class SessionConfigs CCAPI_FINAL { std::map 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 fieldWebsocketChannelMapKrakenFutures = { {CCAPI_TRADE, CCAPI_WEBSOCKET_KRAKEN_FUTURES_CHANNEL_TRADE}, @@ -58,7 +59,8 @@ class SessionConfigs CCAPI_FINAL { }; std::map 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 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 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 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 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 fieldWebsocketChannelMapHuobi = { {CCAPI_TRADE, CCAPI_WEBSOCKET_HUOBI_CHANNEL_TRADE_DETAIL}, @@ -97,6 +103,7 @@ class SessionConfigs CCAPI_FINAL { std::map 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 fieldWebsocketChannelMapErisx = { {CCAPI_TRADE, CCAPI_WEBSOCKET_ERISX_CHANNEL_MARKET_DATA_SUBSCRIBE}, @@ -105,6 +112,7 @@ class SessionConfigs CCAPI_FINAL { std::map 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 fieldWebsocketChannelMapKucoinFutures = { {CCAPI_TRADE, CCAPI_WEBSOCKET_KUCOIN_FUTURES_CHANNEL_MARKET_MATCH}, @@ -125,10 +133,12 @@ class SessionConfigs CCAPI_FINAL { std::map 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 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 fieldWebsocketChannelMapCryptocom = { {CCAPI_TRADE, CCAPI_WEBSOCKET_CRYPTOCOM_CHANNEL_TRADE}, @@ -136,23 +146,23 @@ class SessionConfigs CCAPI_FINAL { }; std::map fieldWebsocketChannelMapBybit = { {CCAPI_TRADE, CCAPI_WEBSOCKET_BYBIT_CHANNEL_TRADE}, - {CCAPI_MARKET_DEPTH, CCAPI_WEBSOCKET_BYBIT_CHANNEL_DEPTH}, - }; - std::map 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 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 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 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 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}, diff --git a/linux/include/ccapi_cpp/ccapi_session_options.h b/linux/include/ccapi_cpp/ccapi_session_options.h index e4ab61342..1281a2f97 100644 --- a/linux/include/ccapi_cpp/ccapi_session_options.h +++ b/linux/include/ccapi_cpp/ccapi_session_options.h @@ -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 */ diff --git a/linux/include/ccapi_cpp/ccapi_subscription.h b/linux/include/ccapi_cpp/ccapi_subscription.h index 5f48519f0..e2c14d7c8 100644 --- a/linux/include/ccapi_cpp/ccapi_subscription.h +++ b/linux/include/ccapi_cpp/ccapi_subscription.h @@ -3,6 +3,7 @@ #include #include +#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 executionManagementSubscriptionFieldSet = {std::string(CCAPI_EM_ORDER_UPDATE), std::string(CCAPI_EM_PRIVATE_TRADE)}; + std::set 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); } diff --git a/linux/include/ccapi_cpp/ccapi_util.h b/linux/include/ccapi_cpp/ccapi_util.h index 6e7bbd752..0b0f4976f 100644 --- a/linux/include/ccapi_cpp/ccapi_util.h +++ b/linux/include/ccapi_cpp/ccapi_util.h @@ -1,6 +1,7 @@ #ifndef INCLUDE_CCAPI_CPP_CCAPI_UTIL_H_ #define INCLUDE_CCAPI_CPP_CCAPI_UTIL_H_ #include +#include namespace ccapi { typedef std::chrono::time_point TimePoint; } /* namespace ccapi */ diff --git a/linux/include/ccapi_cpp/ccapi_util_private.h b/linux/include/ccapi_cpp/ccapi_util_private.h index 85491b4e7..cc8e16653 100644 --- a/linux/include/ccapi_cpp/ccapi_util_private.h +++ b/linux/include/ccapi_cpp/ccapi_util_private.h @@ -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 #include @@ -9,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -21,8 +25,7 @@ #include #include -#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 + 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(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(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(std::chrono::seconds(day_sec)); + auto in_day_sec_original = std::chrono::time_point_cast(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(std::chrono::seconds(in_day_sec_original)); + fractionalSecond = std::chrono::time_point_cast(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& timePair) { auto tp = TimePoint(std::chrono::duration(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 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 - static std::string getISOTimestamp(const TimePoint& tp, const std::string& fmt = "%FT%TZ") { - return date::format(fmt.c_str(), date::floor(tp)); + static std::string getISOTimestamp(const TimePoint& tp) { + int year, month, day, hour, minute, second, fractionalSecond; + timePointToParts(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::value) { + output += "."; + auto fractionalSecondStr = std::to_string(fractionalSecond); + int padToLength; + if (std::is_same::value) { + padToLength = 9; + } else if (std::is_same::value) { + padToLength = 6; + } else if (std::is_same::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& 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; } diff --git a/linux/include/ccapi_cpp/ccapi_ws_connection.h b/linux/include/ccapi_cpp/ccapi_ws_connection.h index dddc6c8af..361ded9f6 100644 --- a/linux/include/ccapi_cpp/ccapi_ws_connection.h +++ b/linux/include/ccapi_cpp/ccapi_ws_connection.h @@ -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 #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 subscriptionList; std::vector correlationIdList; @@ -173,12 +189,16 @@ class WsConnection CCAPI_FINAL { std::map headers; std::map credential; std::shared_ptr > > 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 diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service.h index 0b1a9a908..308e261ca 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service.h @@ -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>> streamPtr(nullptr); try { - streamPtr = that->createStream>>(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(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 >& extractionFieldNameMap) { + virtual void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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& 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 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 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 correlationIdByConnectionIdMap; -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP std::map wsConnectionByCorrelationIdMap; #else - std::map > + std::map> wsConnectionByCorrelationIdMap; // TODO(cryptochassis): for consistency, to be renamed to wsConnectionPtrByCorrelationIdMap #endif std::map wsRequestIdByConnectionIdMap; diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ascendex.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ascendex.h index f72728474..dbce1f47f 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ascendex.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ascendex.h @@ -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& elementList, const rj::Value& value) { - const std::map >& extractionFieldNameMap = { + const std::map>& 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 >& extractionFieldNameMap) override { + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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>> streamPtr(nullptr); try { - streamPtr = that->createStream>>(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 >& extractionFieldNameMap = { + const std::map>& 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); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance.h index 217b926d9..5ecba791c 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance.h @@ -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}); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_base.h index 18849d208..deca33874 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_base.h @@ -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()](const http::response& 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(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 wsConnectionPtr) override { ExecutionManagementService::onOpen(wsConnectionPtr); @@ -265,7 +265,7 @@ class ExecutionManagementServiceBinanceBase : public ExecutionManagementService [wsConnectionPtr, that_2 = that->shared_from_base()](const http::response& 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 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 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 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; diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_coin_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_coin_futures.h index cf5ddfbd1..2cba2a425 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_coin_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_coin_futures.h @@ -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}); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_derivatives_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_derivatives_base.h index 611f47a39..7fba68b2b 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_derivatives_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_derivatives_base.h @@ -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; diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_us.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_us.h index 45979af98..662b93d35 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_us.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_us.h @@ -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}); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_usds_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_usds_futures.h index 895423088..be3a4f91d 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_usds_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_binance_usds_futures.h @@ -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}); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitfinex.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitfinex.h index 9ce4b452a..0ff55feae 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitfinex.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitfinex.h @@ -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 diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget.h index bd759f369..b83f331cf 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget.h @@ -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& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { - const std::map >& extractionFieldNameMap = { + const std::map>& 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 >& extractionFieldNameMap) override { + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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 >& extractionFieldNameMap = { + const std::map>& extractionFieldNameMap = { {CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)}, {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)}, {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_base.h index 5afaa00e8..8715e8991 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_base.h @@ -8,13 +8,15 @@ class ExecutionManagementServiceBitgetBase : public ExecutionManagementService { public: ExecutionManagementServiceBitgetBase(std::function*)> 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 wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); } diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_futures.h index cb525c728..c923bf6d3 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitget_futures.h @@ -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& param, const std::map 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& param, const std::map 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& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { - const std::map >& extractionFieldNameMap = { + const std::map>& 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& 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 >& extractionFieldNameMap) override { + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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 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 >& 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>& 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 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 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") { diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmart.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmart.h index 495115e9e..6b016356f 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmart.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmart.h @@ -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 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 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); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmex.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmex.h index 0b2081bed..4184ad81a 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmex.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitmex.h @@ -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& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { - const std::map >& extractionFieldNameMap = { + const std::map>& extractionFieldNameMap = { {CCAPI_EM_ORDER_ID, std::make_pair("orderID", JsonDataType::STRING)}, {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdID", JsonDataType::STRING)}, {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, @@ -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 >& extractionFieldNameMap) override { + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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 >& extractionFieldNameMap = { + const std::map>& extractionFieldNameMap = { {CCAPI_EM_ORDER_ID, std::make_pair("orderID", JsonDataType::STRING)}, {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdID", JsonDataType::STRING)}, {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, @@ -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 elementList; elementList.emplace_back(std::move(info)); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitstamp.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitstamp.h index 7f1628568..b01c891d1 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitstamp.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bitstamp.h @@ -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>& extractionFieldNameMap) override { + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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 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 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 diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit.h index 3b72af2c9..da79bb5e6 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit.h @@ -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*)> 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 wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); } + + void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, + std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, + const std::map& credential) override { + 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& req, const std::string aString, const TimePoint& now, + const std::map& 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& param, + const std::map 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& req, const TimePoint& now, const std::map& 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(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 createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, + const std::map& credential) override { + std::vector sendStringList; + rj::Document document; + document.SetObject(); + auto& allocator = document.GetAllocator(); + document.AddMember("op", rj::Value("auth").Move(), allocator); + auto apiKey = mapGetWithDefault(credential, this->apiKeyName); + auto expires = std::chrono::duration_cast( + (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 writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + return sendStringList; + } + + void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, + const TimePoint& timeReceived) override { + std::string textMessage(textMessageView); + rj::Document document; + document.Parse(textMessage.c_str()); + Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); + if (!event.getMessageList().empty()) { + this->eventHandler(event, nullptr); + } + } + void appendParam(rj::Value& rjValue, rj::Document::AllocatorType& allocator, const std::map& param, const std::map 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 writer(stringBuffer); document.Accept(writer); @@ -118,6 +206,9 @@ class ExecutionManagementServiceBybit : public ExecutionManagementServiceBybitBa std::string queryString; const std::map 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 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 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 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 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 messageList; - Message message; - message.setTimeReceived(timeReceived); - message.setCorrelationIdList({subscription.getCorrelationId()}); - const auto& fieldSet = subscription.getFieldSet(); - const auto& instrumentSet = subscription.getInstrumentSet(); - if (document.HasMember("topic")) { - std::string topic = document["topic"].GetString(); - if (topic == "order") { - event.setType(Event::Type::SUBSCRIPTION_DATA); - const rj::Value& data = document["data"]; - for (const auto& x : data.GetArray()) { - std::string instrument = x["s"].GetString(); - if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { - auto time = TimePoint(std::chrono::milliseconds(std::stoll(x["E"].GetString()))); - auto itTradeId = x.FindMember("t"); - if (itTradeId != x.MemberEnd() && !itTradeId->value.IsNull() && fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { - Message message; - message.setTimeReceived(timeReceived); - message.setCorrelationIdList({subscription.getCorrelationId()}); - message.setTime(time); - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); - std::vector elementList; - Element element; - element.insert(CCAPI_TRADE_ID, itTradeId->value.GetString()); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, std::string(x["L"].GetString())); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, std::string(x["l"].GetString())); - element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["S"].GetString()) == "BUY" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); - element.insert(CCAPI_IS_MAKER, x["m"].GetBool() ? "1" : "0"); - element.insert(CCAPI_EM_ORDER_ID, std::string(x["i"].GetString())); - element.insert(CCAPI_EM_CLIENT_ORDER_ID, std::string(x["c"].GetString())); - element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); - { - auto it = x.FindMember("n"); - if (it != x.MemberEnd() && !it->value.IsNull()) { - element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(it->value.GetString())); - } - } - { - auto it = x.FindMember("N"); - if (it != x.MemberEnd() && !it->value.IsNull()) { - element.insert(CCAPI_EM_ORDER_FEE_ASSET, std::string(it->value.GetString())); - } - } - 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 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 >& 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 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 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 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 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 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 diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h deleted file mode 100644 index ce6b69686..000000000 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit_base.h +++ /dev/null @@ -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*)> 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 wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); } -#endif - void signReqeustForRestGenericPrivateRequest(http::request& req, const Request& request, std::string& methodString, - std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, - const std::map& credential) override { - 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& req, const std::string aString, const TimePoint& now, - const std::map& 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& param, - const std::map 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& req, const TimePoint& now, const std::map& 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(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 createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, - const std::map& credential) override { - std::vector sendStringList; - rj::Document document; - document.SetObject(); - auto& allocator = document.GetAllocator(); - document.AddMember("op", rj::Value("auth").Move(), allocator); - auto apiKey = mapGetWithDefault(credential, this->apiKeyName); - auto expires = std::chrono::duration_cast( - (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 writer(stringBuffer); - document.Accept(writer); - std::string sendString = stringBuffer.GetString(); - sendStringList.push_back(sendString); - return sendStringList; - } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET - void onTextMessage(wspp::connection_hdl hdl, const std::string& textMessage, const TimePoint& timeReceived) override { - WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); - auto subscription = wsConnection.subscriptionList.at(0); - rj::Document document; - document.Parse(textMessage.c_str()); - Event event = this->createEvent(wsConnection, hdl, subscription, textMessage, document, timeReceived); - if (!event.getMessageList().empty()) { - this->eventHandler(event, nullptr); - } - } - virtual Event createEvent(const WsConnection& wsConnection, wspp::connection_hdl hdl, const Subscription& subscription, const std::string& textMessage, - const rj::Document& document, const TimePoint& timeReceived) { - return {}; - } -#else - void onTextMessage(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, - const TimePoint& timeReceived) override { - std::string textMessage(textMessageView); - rj::Document document; - document.Parse(textMessage.c_str()); - Event event = this->createEvent(wsConnectionPtr, subscription, textMessageView, document, timeReceived); - if (!event.getMessageList().empty()) { - this->eventHandler(event, nullptr); - } - } - virtual Event createEvent(std::shared_ptr wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, - const rj::Document& document, const TimePoint& timeReceived) { - return {}; - } -#endif -}; -} /* namespace ccapi */ -#endif -#endif -#endif // INCLUDE_CCAPI_CPP_SERVICE_CCAPI_EXECUTION_MANAGEMENT_SERVICE_BYBIT_BASE_H_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit_derivatives.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit_derivatives.h deleted file mode 100644 index 36ad753e8..000000000 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_bybit_derivatives.h +++ /dev/null @@ -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*)> 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& param, - const std::map 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& req, const Request& request, const TimePoint& now, const std::string& symbolId, - const std::map& 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 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 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 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 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 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 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 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 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 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& elementList, const Request& request, const Request::Operation operation, - const rj::Document& document) override { - std::map > 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& 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 wsConnectionPtr, const Subscription& subscription, boost::beast::string_view textMessageView, - const rj::Document& document, const TimePoint& timeReceived) override { - std::string textMessage(textMessageView); -#endif - Event event; - std::vector messageList; - Message message; - message.setTimeReceived(timeReceived); - message.setCorrelationIdList({subscription.getCorrelationId()}); - const auto& fieldSet = subscription.getFieldSet(); - const auto& instrumentSet = subscription.getInstrumentSet(); - if (document.HasMember("topic")) { - std::string topic = document["topic"].GetString(); - if (topic == "user.order.unifiedAccount") { - if (fieldSet.find(CCAPI_EM_ORDER_UPDATE) != fieldSet.end()) { - event.setType(Event::Type::SUBSCRIPTION_DATA); - const rj::Value& data = document["data"]["result"]; - for (const auto& x : data.GetArray()) { - std::string instrument = x["symbol"].GetString(); - if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { - Message message; - message.setTimeReceived(timeReceived); - message.setCorrelationIdList({subscription.getCorrelationId()}); - message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["updatedTime"].GetString())))); - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE); - const std::map >& extractionFieldNameMap = { - {CCAPI_EM_ORDER_ID, std::make_pair("orderId", JsonDataType::INTEGER)}, - {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("orderLinkId", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_LIMIT_PRICE, std::make_pair("price", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_QUANTITY, std::make_pair("qty", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_CUMULATIVE_FILLED_QUANTITY, std::make_pair("cumExecQty", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_CUMULATIVE_FILLED_PRICE_TIMES_QUANTITY, std::make_pair("cumExecValue", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_STATUS, std::make_pair("orderStatus", JsonDataType::STRING)}, - {CCAPI_EM_ORDER_INSTRUMENT, std::make_pair("symbol", JsonDataType::STRING)}, - }; - Element info; - this->extractOrderInfo(info, x, extractionFieldNameMap); - std::vector elementList; - elementList.emplace_back(std::move(info)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); - } - } - } - } else if (topic == "user.execution.unifiedAccount") { - if (fieldSet.find(CCAPI_EM_PRIVATE_TRADE) != fieldSet.end()) { - event.setType(Event::Type::SUBSCRIPTION_DATA); - const rj::Value& data = document["data"]["result"]; - for (const auto& x : data.GetArray()) { - std::string execType = x["execType"].GetString(); - if (execType == "TRADE") { - std::string instrument = x["symbol"].GetString(); - if (instrumentSet.empty() || instrumentSet.find(instrument) != instrumentSet.end()) { - Message message; - message.setTimeReceived(timeReceived); - message.setCorrelationIdList({subscription.getCorrelationId()}); - message.setTime(TimePoint(std::chrono::milliseconds(std::stoll(x["execTime"].GetString())))); - message.setType(Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE); - std::vector elementList; - Element element; - element.insert(CCAPI_TRADE_ID, x["execId"].GetString()); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_PRICE, x["execPrice"].GetString()); - element.insert(CCAPI_EM_ORDER_LAST_EXECUTED_SIZE, x["execQty"].GetString()); - element.insert(CCAPI_EM_ORDER_SIDE, std::string(x["side"].GetString()) == "Buy" ? CCAPI_EM_ORDER_SIDE_BUY : CCAPI_EM_ORDER_SIDE_SELL); - element.insert(CCAPI_IS_MAKER, std::string(x["lastLiquidityInd"].GetString()) == "MAKER" ? "1" : "0"); - element.insert(CCAPI_EM_ORDER_ID, x["orderId"].GetString()); - element.insert(CCAPI_EM_CLIENT_ORDER_ID, x["orderLinkId"].GetString()); - element.insert(CCAPI_EM_ORDER_INSTRUMENT, instrument); - { - auto it = x.FindMember("execFee"); - if (it != x.MemberEnd() && !it->value.IsNull()) { - element.insert(CCAPI_EM_ORDER_FEE_QUANTITY, std::string(it->value.GetString())); - } - } - elementList.emplace_back(std::move(element)); - message.setElementList(elementList); - messageList.emplace_back(std::move(message)); - } - } - } - } - } - } else if (document.HasMember("type")) { - std::string type = document["type"].GetString(); - if (type == "AUTH_RESP") { - bool success = document["success"].GetBool(); - if (success) { - rj::Document document; - document.SetObject(); - rj::Document::AllocatorType& allocator = document.GetAllocator(); - document.AddMember("op", rj::Value("subscribe").Move(), allocator); - rj::Value args(rj::kArrayType); - for (const auto& field : subscription.getFieldSet()) { - std::string channelId; - if (field == CCAPI_EM_ORDER_UPDATE) { - channelId = "user.order.unifiedAccount"; - } else if (field == CCAPI_EM_PRIVATE_TRADE) { - channelId = "user.execution.unifiedAccount"; - } - args.PushBack(rj::Value(channelId.c_str(), allocator).Move(), allocator); - } - document.AddMember("args", args, allocator); - rj::StringBuffer stringBuffer; - rj::Writer writer(stringBuffer); - document.Accept(writer); - std::string sendString = stringBuffer.GetString(); - ErrorCode ec; -#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_ diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_coinbase.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_coinbase.h index ea05d2f84..3d02c7b17 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_coinbase.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_coinbase.h @@ -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)); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_cryptocom.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_cryptocom.h index 54caa0c33..008bde904 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_cryptocom.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_cryptocom.h @@ -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); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_deribit.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_deribit.h index 682b793a4..5c90de682 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_deribit.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_deribit.h @@ -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>& extractionFieldNameMap) override { + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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 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); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_erisx.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_erisx.h index c50384802..4d06382ee 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_erisx.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_erisx.h @@ -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& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { - const std::map >& extractionFieldNameMap = { + const std::map>& extractionFieldNameMap = { {CCAPI_EM_ORDER_ID, std::make_pair("orderID", JsonDataType::STRING)}, {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdID", JsonDataType::STRING)}, {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, @@ -221,15 +221,15 @@ class ExecutionManagementServiceErisx : public ExecutionManagementService { } void extractAccountInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override {} - void extractOrderInfo(Element& element, const rj::Value& x, - const std::map >& extractionFieldNameMap) override { + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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()); } } } diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx.h index b9d225216..97b0f42af 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx.h @@ -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); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_base.h index 0087cf212..2d71943dd 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_base.h @@ -22,7 +22,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 wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); } @@ -213,7 +213,7 @@ class ExecutionManagementServiceFtxBase : public ExecutionManagementService { } void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { - const std::map >& extractionFieldNameMap = { + const std::map>& 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 >& extractionFieldNameMap) override { + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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 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 >& extractionFieldNameMap = { + const std::map>& 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)}, diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_us.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_us.h index 422bb5952..e6fd5358e 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_us.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_ftx_us.h @@ -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); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio.h index aebaae744..66cfe571c 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio.h @@ -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}); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_base.h index 0b5f866c8..600dfa422 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_base.h @@ -14,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 diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_perpetual_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_perpetual_futures.h index 319d68cef..475d048c3 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_perpetual_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gateio_perpetual_futures.h @@ -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>> streamPtr(nullptr); try { - streamPtr = that->createStream>>(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()}); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gemini.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gemini.h index 8ccc343bc..6e3b08f14 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gemini.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_gemini.h @@ -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& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { - const std::map >& extractionFieldNameMap = { + const std::map>& 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 >& extractionFieldNameMap) override { + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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({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(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 >& extractionFieldNameMap = { + const std::map>& 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()); } } { diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi.h index 8a318ba31..5cb8ede7e 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi.h @@ -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 createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, const std::map& credential) override { auto apiKey = mapGetWithDefault(credential, this->apiKeyName); - std::string timestamp = UtilTime::getISOTimestamp(now, "%FT%T"); + std::string timestamp = UtilTime::getISOTimestamp(now); + timestamp.pop_back(); std::string signature; std::string queryString; std::map 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); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_base.h index b0bd0a4ff..28c8242a2 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_base.h @@ -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(now, "%FT%T"); + std::string timestamp = UtilTime::getISOTimestamp(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(now, "%FT%T"); + std::string timestamp = UtilTime::getISOTimestamp(now); + timestamp.pop_back(); queryParamMap.insert(std::make_pair("Timestamp", Url::urlEncode(timestamp))); this->convertReqDetail(req, request, now, symbolId, credential, queryParamMap); } diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_coin_swap.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_coin_swap.h index 1efe0a654..2793db6e4 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_coin_swap.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_coin_swap.h @@ -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}); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_derivatives_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_derivatives_base.h index 742dcb7db..150256a99 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_derivatives_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_derivatives_base.h @@ -13,7 +13,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& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { - const std::map >& extractionFieldNameMap = { + const std::map>& 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 >& extractionFieldNameMap) override { + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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 createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, const std::map& credential) override { auto apiKey = mapGetWithDefault(credential, this->apiKeyName); - std::string timestamp = UtilTime::getISOTimestamp(now, "%FT%T"); + std::string timestamp = UtilTime::getISOTimestamp(now); + timestamp.pop_back(); std::string signature; std::string queryString; std::map 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 >& extractionFieldNameMap = { + const std::map>& 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()) { diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_usdt_swap.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_usdt_swap.h index a77805cb4..f2d33fdc8 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_usdt_swap.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_huobi_usdt_swap.h @@ -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}); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken.h index 4a1b80fd5..d495e2321 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken.h @@ -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 wsConnectionPtr) override { @@ -361,7 +361,7 @@ class ExecutionManagementServiceKraken : public ExecutionManagementService { document.Parse(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 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)); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken_futures.h index efcc226ad..1e655f9eb 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kraken_futures.h @@ -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); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin.h index bde4a635d..b19b42401 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin.h @@ -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); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_base.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_base.h index 094ac2ffe..77ba507b3 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_base.h @@ -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 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& 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& req, const std::string& body, const std::map& 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(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& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { - const std::map >& extractionFieldNameMap = { + const std::map>& 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 >& extractionFieldNameMap) override { + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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 > extractionFieldNameMap = { + std::map> 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); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_futures.h index 571ef4296..b1cfcc0f7 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_kucoin_futures.h @@ -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); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc.h index 2daad48d5..c72837a98 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc.h @@ -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 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()](const http::response& 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(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 wsConnectionPtr) override { ExecutionManagementService::onOpen(wsConnectionPtr); @@ -416,7 +416,7 @@ class ExecutionManagementServiceMexc : public ExecutionManagementService { [wsConnectionPtr, that_2 = that->shared_from_base()](const http::response& 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 diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc_futures.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc_futures.h index de5f17232..5064e943b 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_mexc_futures.h @@ -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 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 >& extractionFieldNameMap) override { + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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 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); diff --git a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_okx.h b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_okx.h index 5eaef313d..54d7ec97f 100644 --- a/linux/include/ccapi_cpp/service/ccapi_execution_management_service_okx.h +++ b/linux/include/ccapi_cpp/service/ccapi_execution_management_service_okx.h @@ -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 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& req, const Request& request, std::string& methodString, std::string& headerString, std::string& path, std::string& queryString, std::string& body, const TimePoint& now, const std::map& credential) override { @@ -68,6 +71,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService { } headerString += "OK-ACCESS-SIGN:" + signature; } + void signRequest(http::request& req, const std::string& body, const std::map& 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& param, const std::map 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& param, const std::map 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& req, const Request& request, const TimePoint& now, const std::string& symbolId, const std::map& 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(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& credential) override { @@ -269,12 +279,14 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService { this->convertRequestForWebsocketCustom(document, allocator, wsConnection, request, wsRequestId, now, symbolId, credential); } } + void extractOrderInfoFromRequest(std::vector& elementList, const Request& request, const Request::Operation operation, const rj::Document& document) override { this->extractOrderInfoFromRequest(elementList, document); } + void extractOrderInfoFromRequest(std::vector& elementList, const rj::Document& document) { - const std::map >& extractionFieldNameMap = { + const std::map>& extractionFieldNameMap = { {CCAPI_EM_ORDER_ID, std::make_pair("ordId", JsonDataType::STRING)}, {CCAPI_EM_CLIENT_ORDER_ID, std::make_pair("clOrdId", JsonDataType::STRING)}, {CCAPI_EM_ORDER_SIDE, std::make_pair("side", JsonDataType::STRING)}, @@ -296,6 +308,7 @@ class ExecutionManagementServiceOkx : public ExecutionManagementService { } } } + void extractAccountInfoFromRequest(std::vector& 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 >& extractionFieldNameMap) override { + + void extractOrderInfo(Element& element, const rj::Value& x, const std::map>& extractionFieldNameMap, + const std::map> 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 createSendStringListFromSubscription(const WsConnection& wsConnection, const Subscription& subscription, const TimePoint& now, const std::map& credential) override { std::vector 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 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 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 >& 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 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>& 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 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 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 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; }; diff --git a/linux/include/ccapi_cpp/service/ccapi_fix_service.h b/linux/include/ccapi_cpp/service/ccapi_fix_service.h index 3ddbde9fd..7fcdae900 100644 --- a/linux/include/ccapi_cpp/service/ccapi_fix_service.h +++ b/linux/include/ccapi_cpp/service/ccapi_fix_service.h @@ -11,11 +11,11 @@ #include "hffix.hpp" namespace hff = hffix; namespace ccapi { -template /** * 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 FixService : public Service { public: FixService(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, @@ -105,7 +105,7 @@ class FixService : public Service { }); this->connectRetryOnFailTimerByConnectionIdMap[fixConnectionPtr->id] = timerPtr; } - std::shared_ptr createStreamFix(std::shared_ptr iocPtr, std::shared_ptr ctxPtr, const std::string& host); + std::shared_ptr 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>)> 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::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(), 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(), 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(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> FixService>::createStreamFix( - std::shared_ptr iocPtr, std::shared_ptr ctxPtr, const std::string& host) { +inline std::shared_ptr> FixService>::createStreamFix(net::io_context* iocPtr, + net::ssl::context* ctxPtr, + const std::string& host) { std::shared_ptr> streamPtr(new beast::ssl_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> FixService -inline std::shared_ptr FixService::createStreamFix(std::shared_ptr iocPtr, - std::shared_ptr ctxPtr, const std::string& host) { +inline std::shared_ptr FixService::createStreamFix(net::io_context* iocPtr, net::ssl::context* ctxPtr, + const std::string& host) { std::shared_ptr streamPtr(new beast::tcp_stream(*iocPtr)); return streamPtr; } diff --git a/linux/include/ccapi_cpp/service/ccapi_fix_service_coinbase.h b/linux/include/ccapi_cpp/service/ccapi_fix_service_coinbase.h index 8058b61d2..31d1f9a3e 100644 --- a/linux/include/ccapi_cpp/service/ccapi_fix_service_coinbase.h +++ b/linux/include/ccapi_cpp/service/ccapi_fix_service_coinbase.h @@ -44,7 +44,7 @@ class FixServiceCoinbase : public FixServicesessionOptions.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}); diff --git a/linux/include/ccapi_cpp/service/ccapi_fix_service_gemini.h b/linux/include/ccapi_cpp/service/ccapi_fix_service_gemini.h index a6692edc3..6382a1372 100644 --- a/linux/include/ccapi_cpp/service/ccapi_fix_service_gemini.h +++ b/linux/include/ccapi_cpp/service/ccapi_fix_service_gemini.h @@ -41,7 +41,7 @@ class FixServiceGemini : public FixService { 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}); } diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service.h index 2ac851eaa..2eff1bfaa 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service.h @@ -17,12 +17,17 @@ namespace ccapi { class MarketDataService : public Service { public: MarketDataService(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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& subscriptionList) override { CCAPI_LOGGER_FUNCTION_ENTER; @@ -131,13 +136,12 @@ class MarketDataService : public Service { } std::shared_ptr>> streamPtr(nullptr); try { - streamPtr = that->createStream>>( - 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 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 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& 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(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(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(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 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 wsConnectionPtr) override { @@ -651,7 +680,7 @@ class MarketDataService : public Service { virtual void onClose(std::shared_ptr 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& snapshotBid, + const std::map& snapshotAsk, std::vector& 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 calculateMarketDepthUpdate(bool isBid, const std::map& c1, const std::map& 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& elementList) { + void updateElementListWithExchangeProvidedCandlestick(const std::string& field, MarketDataMessage::TypeForData& input, std::vector& 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& 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 messageList; std::vector 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& optionMap, const std::vector& correlationIdList, + bool isSolicited) { + std::vector messageList; + std::vector 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& correlationIdList, Message::Type messageType) { + std::vector messageList; + std::vector 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 availableMarketDepth) { + int calculateMarketDepthAllowedByExchange(int depthWanted, std::vector 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(), snapshotAsk, std::map(), 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& 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& correlationIdList, Message::Type messageType, int maxMarketDepth) { + std::vector messageList; + std::vector elementList; + std::map 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& req, const Request& request, const TimePoint& now, const std::string& symbolId, const std::map& credential) { const std::map 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 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()](const beast::error_code& ec) { - that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliSeconds); + [wsConnection, exchangeSubscriptionId, delayMilliseconds, that = shared_from_base()](const beast::error_code& ec) { + that->buildOrderBookInitialOnFail(wsConnection, exchangeSubscriptionId, delayMilliseconds); }, - [wsConnection, exchangeSubscriptionId, delayMilliSeconds, that = shared_from_base()](const http::response& res) { + [wsConnection, exchangeSubscriptionId, delayMilliseconds, that = shared_from_base()](const http::response& 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 createSendStringListFromSubscriptionList(const WsConnection& wsConnection, const std::vector& subscriptionList, const TimePoint& now, const std::map& 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& 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& marketDataMessageList) {} #else @@ -1785,10 +2000,14 @@ class MarketDataService : public Service { std::map>> lowByConnectionIdChannelIdSymbolIdMap; std::map>> closeByConnectionIdChannelIdSymbolIdMap; std::string getRecentTradesTarget; + std::string getHistoricalTradesTarget; + std::string getRecentCandlesticksTarget; + std::string getHistoricalCandlesticksTarget; + std::string getMarketDepthTarget; std::string getInstrumentTarget; std::string getInstrumentsTarget; std::map exchangeJsonPayloadIdByConnectionIdMap; - std::map>> exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap; + std::map>> exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap; // only needed for generic public subscription std::map correlationIdByConnectionIdMap; std::map>> diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ascendex.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ascendex.h index a314dc01b..1362bee29 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ascendex.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ascendex.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceAscendex : public MarketDataService { public: MarketDataServiceAscendex(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& 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); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance.h index 371f790c4..50da338c0 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance.h @@ -7,30 +7,35 @@ namespace ccapi { class MarketDataServiceBinance : public MarketDataServiceBinanceBase { public: MarketDataServiceBinance(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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"; } diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_base.h index 761f65cb3..2a556f3ce 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_base.h @@ -8,7 +8,7 @@ namespace ccapi { class MarketDataServiceBinanceBase : public MarketDataService { public: MarketDataServiceBinanceBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 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({5, 10, 20})); + marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector({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 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& 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 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 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()]( + const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }}, + {CCAPI_END_TIME_SECONDS, [that = shared_from_base()]( + 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 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()](const std::string& input) { + return that->convertCandlestickIntervalSecondsToInterval(std::stoi(input), "s", "m", "h", "d", "w"); + }}, + {CCAPI_START_TIME_SECONDS, [that = shared_from_base()]( + const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }}, + {CCAPI_END_TIME_SECONDS, [that = shared_from_base()]( + 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 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(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 diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_coin_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_coin_futures.h index e03e9e6f6..dacf03b0b 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_coin_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_coin_futures.h @@ -7,30 +7,35 @@ namespace ccapi { class MarketDataServiceBinanceCoinFutures : public MarketDataServiceBinanceDerivativesBase { public: MarketDataServiceBinanceCoinFutures(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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"; } diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_derivatives_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_derivatives_base.h index 053a4469a..7cc5bc6ba 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_derivatives_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_derivatives_base.h @@ -7,7 +7,7 @@ namespace ccapi { class MarketDataServiceBinanceDerivativesBase : public MarketDataServiceBinanceBase { public: MarketDataServiceBinanceDerivativesBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 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({1, 5, 10, 20})); + marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector({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& req, const Request& request, const TimePoint& now, const std::string& symbolId, + const std::map& 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 param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_MARKET_DEPTH_MAX, "limit"}, + }, + { + {CCAPI_MARKET_DEPTH_MAX, + [that = shared_from_base()](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& marketDataMessageList) override { switch (request.getOperation()) { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_us.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_us.h index 10de42af9..3ba268654 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_us.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_us.h @@ -7,30 +7,35 @@ namespace ccapi { class MarketDataServiceBinanceUs : public MarketDataServiceBinanceBase { public: MarketDataServiceBinanceUs(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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"; } diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_usds_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_usds_futures.h index 76e9559f9..e5d42476c 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_usds_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_binance_usds_futures.h @@ -7,30 +7,35 @@ namespace ccapi { class MarketDataServiceBinanceUsdsFutures : public MarketDataServiceBinanceDerivativesBase { public: MarketDataServiceBinanceUsdsFutures(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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"; } diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitfinex.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitfinex.h index 0c23bc435..23fc0dd7a 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitfinex.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitfinex.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceBitfinex : public MarketDataService { public: MarketDataServiceBitfinex(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"op":"ping"})", ec); } + void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, R"({"event":"ping"})", ec); } void onOpen(std::shared_ptr 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 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({1, 25, 100, 250})); + marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector({1, 25, 100, 250})); channelId += std::string("?") + CCAPI_MARKET_DEPTH_SUBSCRIBED_TO_EXCHANGE + "=" + std::to_string(marketDepthSubscribedToExchange); this->marketDepthSubscribedToExchangeByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = marketDepthSubscribedToExchange; + } 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 createSendStringList(const WsConnection& wsConnection) override { return std::vector(); } - void processTextMessage( -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET - WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage -#else - std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView -#endif - , - const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET -#else + void processTextMessage(std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); -#endif rj::Document document; document.Parse(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 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; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget.h index 0cc60f347..6426bbe16 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget.h @@ -7,29 +7,32 @@ namespace ccapi { class MarketDataServiceBitget : public MarketDataServiceBitgetBase { public: MarketDataServiceBitget(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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() {} }; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_base.h index 770b20383..90d3f1b12 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_base.h @@ -7,8 +7,10 @@ namespace ccapi { class MarketDataServiceBitgetBase : public MarketDataService { public: MarketDataServiceBitgetBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 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 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& 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 param = request.getFirstParamWithDefault(); - this->appendParam(queryString, param, - { - {CCAPI_INSTRUMENT_TYPE, "productType"}, - }); - } else { - target = this->getInstrumentTarget; - const std::map param = request.getFirstParamWithDefault(); - this->appendSymbolId(queryString, symbolId, "symbol"); - } + const std::map 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 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(), 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()]( + const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }}, + {CCAPI_END_TIME_SECONDS, [that = shared_from_base()]( + 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 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 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(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 diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_futures.h index 62f036979..c75f2577b 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitget_futures.h @@ -7,29 +7,32 @@ namespace ccapi { class MarketDataServiceBitgetFutures : public MarketDataServiceBitgetBase { public: MarketDataServiceBitgetFutures(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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() {} diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmart.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmart.h index 1cbb27242..c95f0eb72 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmart.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmart.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceBitmart : public MarketDataService { public: MarketDataServiceBitmart(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #else WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmex.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmex.h index 16231ac82..9c2079864 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmex.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitmex.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceBitmex : public MarketDataService { public: MarketDataServiceBitmex(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& 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: " + diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitstamp.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitstamp.h index 8c583779e..d7449b95d 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitstamp.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bitstamp.h @@ -7,7 +7,7 @@ namespace ccapi { class MarketDataServiceBitstamp : public MarketDataService { public: MarketDataServiceBitstamp(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #else WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit.h index 658f29273..a06859d14 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit.h @@ -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*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 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 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 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 wsConnectionPtr, boost::beast::string_view textMessageView -#endif - , - const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET -#else + void processTextMessage(std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView, const TimePoint& timeReceived, Event& event, + std::vector& marketDataMessageList) override { WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); -#endif rj::Document document; document.Parse(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 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()](const std::string& input) { + return that->convertCandlestickIntervalSecondsToInterval(std::stoi(input)); + }}, + {CCAPI_START_TIME_SECONDS, [that = shared_from_base()]( + const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }}, + {CCAPI_END_TIME_SECONDS, [that = shared_from_base()]( + 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 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 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 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& marketDataMessageList) override { rj::Document document; document.Parse(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 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); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit_base.h deleted file mode 100644 index 4982dc109..000000000 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit_base.h +++ /dev/null @@ -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*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 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_ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit_derivatives.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit_derivatives.h deleted file mode 100644 index 0f7792f94..000000000 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_bybit_derivatives.h +++ /dev/null @@ -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*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 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 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 createSendStringList(const WsConnection& wsConnection) override { - std::vector sendStringList; - std::vector 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 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 wsConnectionPtr, boost::beast::string_view textMessageView -#endif - , - const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET -#else - WsConnection& wsConnection = *wsConnectionPtr; - std::string textMessage(textMessageView); -#endif - rj::Document document; - document.Parse(textMessage.c_str()); - if (document.IsObject() && document.HasMember("op")) { - std::string op = document["op"].GetString(); - if (op == "subscribe") { - bool success = document["success"].GetBool(); - event.setType(Event::Type::SUBSCRIPTION_STATUS); - std::vector messageList; - Message message; - message.setTimeReceived(timeReceived); - std::vector 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 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& req, const Request& request, const TimePoint& now, const std::string& symbolId, - const std::map& 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 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 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 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& marketDataMessageList) override { - rj::Document document; - document.Parse(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 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_ diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_coinbase.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_coinbase.h index e7e409d99..cc02f0397 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_coinbase.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_coinbase.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceCoinbase : public MarketDataService { public: MarketDataServiceCoinbase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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//trades"; this->getInstrumentTarget = "/products/"; 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #else WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_cryptocom.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_cryptocom.h index e21c18e75..68b978acb 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_cryptocom.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_cryptocom.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceCryptocom : public MarketDataService { public: MarketDataServiceCryptocom(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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({10, 150})); + marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector({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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& 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); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_deribit.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_deribit.h index 7caa81743..5d829d76b 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_deribit.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_deribit.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceDeribit : public MarketDataService { public: MarketDataServiceDeribit(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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(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(now.time_since_epoch()).count(), "public/set_heartbeat", { - {"interval", toString(hbInterval)}, + {"interval", "10"}, }); - ////////////////////////////////////////////////// - // END - BTS Custom Code - ////////////////////////////////////////////////// - rj::StringBuffer stringBuffer; rj::Writer 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({10, 20})); + marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector({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 activeHeartbeatReqs; - std::unordered_set activeReqs; - - template - static std::pair readJson(rapidjson::Document &doc, const std::string &key); - - static bool isHeartbeatRequest(const std::string &textMessage) { - rj::Document doc; - doc.Parse(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(now.time_since_epoch()).count(); - appendParam(document, allocator, rpcId, "/public/test", {}); - rj::StringBuffer stringBuffer; - rj::Writer 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& 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> subscriptionJsonrpcIdSetByConnectionIdMap; std::string restTarget; }; - -////////////////////////////////////////////////// -// BEGIN - BTS Custom Code -////////////////////////////////////////////////// - -template <> -inline std::pair MarketDataServiceDeribit::readJson(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 MarketDataServiceDeribit::readJson(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(v.GetUint64()), true}; - } - if (v.IsUint()) { - return {static_cast(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(textMessage.c_str()); - const auto [rpcId, hasRpcId] = readJson(doc, "id"); - if (hasRpcId) { - if (activeHeartbeatReqs.erase(rpcId) != 0) { - return; - } - const auto [resStr, hasResStr] = readJson(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 diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_erisx.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_erisx.h index 2ecdd95d4..354c44073 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_erisx.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_erisx.h @@ -7,7 +7,7 @@ namespace ccapi { class MarketDataServiceErisx : public MarketDataService { public: MarketDataServiceErisx(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #else WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx.h index 236216716..c580eac6b 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx.h @@ -7,7 +7,7 @@ namespace ccapi { class MarketDataServiceFtx : public MarketDataServiceFtxBase { public: MarketDataServiceFtx(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_base.h index 3681545b2..dd5632f52 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_base.h @@ -7,7 +7,7 @@ namespace ccapi { class MarketDataServiceFtxBase : public MarketDataService { public: MarketDataServiceFtxBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #else WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_us.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_us.h index 31708a705..d2b7f1a82 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_us.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_ftx_us.h @@ -7,7 +7,7 @@ namespace ccapi { class MarketDataServiceFtxUs : public MarketDataServiceFtxBase { public: MarketDataServiceFtxUs(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio.h index 13786e57f..6327817ae 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceGateio : public MarketDataServiceGateioBase { public: MarketDataServiceGateio(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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() {} diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_base.h index 27e6ec352..bc3da42c7 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_base.h @@ -7,14 +7,14 @@ namespace ccapi { class MarketDataServiceGateioBase : public MarketDataService { public: MarketDataServiceGateioBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 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({5, 10, 20})); + marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector({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 createSendStringList(const WsConnection& wsConnection) override { @@ -62,20 +66,28 @@ class MarketDataServiceGateioBase : public MarketDataService { std::vector 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 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 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 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 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 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& 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 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 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 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 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 diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_perpetual_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_perpetual_futures.h index f7023214c..2a8d86311 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_perpetual_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gateio_perpetual_futures.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceGateioPerpetualFutures : public MarketDataServiceGateioBase { public: MarketDataServiceGateioPerpetualFutures(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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() {} diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gemini.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gemini.h index 035f76127..c099df57d 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_gemini.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_gemini.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceGemini : public MarketDataService { public: MarketDataServiceGemini(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 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 createSendStringList(const WsConnection& wsConnection) override { return std::vector(); } -#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 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& 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"); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi.h index 8e33a9ac6..ce595bc96 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceHuobi : public MarketDataServiceHuobiBase { public: MarketDataServiceHuobi(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 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({5, 10, 20})); + marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector({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 { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_base.h index b57417d62..108ce337f 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_base.h @@ -7,10 +7,10 @@ namespace ccapi { class MarketDataServiceHuobiBase : public MarketDataService { public: MarketDataServiceHuobiBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& 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); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_coin_swap.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_coin_swap.h index c0af9922d..46f5ef56e 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_coin_swap.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_coin_swap.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceHuobiCoinSwap : public MarketDataServiceHuobiDerivativesBase { public: MarketDataServiceHuobiCoinSwap(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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"; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_derivatives_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_derivatives_base.h index b6d5224b0..d8f02e9dc 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_derivatives_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_derivatives_base.h @@ -7,7 +7,7 @@ namespace ccapi { class MarketDataServiceHuobiDerivativesBase : public MarketDataServiceHuobiBase { public: MarketDataServiceHuobiDerivativesBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 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 { diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_usdt_swap.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_usdt_swap.h index 3b2820c34..114a3f72b 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_usdt_swap.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_huobi_usdt_swap.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceHuobiUsdtSwap : public MarketDataServiceHuobiDerivativesBase { public: MarketDataServiceHuobiUsdtSwap(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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"; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken.h index 52467e21a..569093da0 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceKraken : public MarketDataService { public: MarketDataServiceKraken(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 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({10, 25, 100, 500, 1000})); + marketDepthSubscribedToExchange = this->calculateMarketDepthAllowedByExchange(marketDepthRequested, std::vector({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 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 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& 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(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; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken_futures.h index e0c1e0970..8dccc1e1a 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kraken_futures.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceKrakenFutures : public MarketDataService { public: MarketDataServiceKrakenFutures(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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 wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #else WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin.h index 2bd38612d..194745237 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin.h @@ -7,19 +7,19 @@ namespace ccapi { class MarketDataServiceKucoin : public MarketDataServiceKucoinBase { public: MarketDataServiceKucoin(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr 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"; } diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_base.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_base.h index cc1826042..58d4c2c42 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_base.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_base.h @@ -7,7 +7,7 @@ namespace ccapi { class MarketDataServiceKucoinBase : public MarketDataService { public: MarketDataServiceKucoinBase(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr serviceContextPtr) + ServiceContext* serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) {} virtual ~MarketDataServiceKucoinBase() {} #ifndef CCAPI_EXPOSE_INTERNAL @@ -18,7 +18,7 @@ class MarketDataServiceKucoinBase : public MarketDataService { void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); - auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); + auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); if (field == CCAPI_MARKET_DEPTH) { if (this->isDerivatives) { if (marketDepthRequested == 1) { @@ -29,7 +29,7 @@ class MarketDataServiceKucoinBase : public MarketDataService { channelId = this->channelMarketLevel2Depth50; } } else { - // if (conflateIntervalMilliSeconds < 100) { + // if (conflateIntervalMilliseconds < 100) { // channelId = this->channelMarketLevel2; // }else{ if (marketDepthRequested == 1) { @@ -41,9 +41,13 @@ class MarketDataServiceKucoinBase : public MarketDataService { } // } } + } else if (field == CCAPI_CANDLESTICK) { + std::string interval = + this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), "", "min", "hour", "day", "week"); + channelId += interval; } } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { auto now = UtilTime::now(); this->send(hdl, "{\"id\":\"" + std::to_string(UtilTime::getUnixTimestamp(now)) + "\",\"type\":\"ping\"}", wspp::frame::opcode::text, ec); @@ -95,7 +99,7 @@ class MarketDataServiceKucoinBase : public MarketDataService { } that->onFail_(thisWsConnection); }, - this->sessionOptions.httpRequestTimeoutMilliSeconds); + this->sessionOptions.httpRequestTimeoutMilliseconds); } #else void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { @@ -124,7 +128,7 @@ class MarketDataServiceKucoinBase : public MarketDataService { urlWebsocketBase += std::string(instanceServer["endpoint"].GetString()); urlWebsocketBase += "?token="; urlWebsocketBase += std::string(document["data"]["token"].GetString()); - wsConnectionPtr->url = urlWebsocketBase; + wsConnectionPtr->setUrl(urlWebsocketBase); that->connect(wsConnectionPtr); for (const auto& subscription : wsConnectionPtr->subscriptionList) { auto instrument = subscription.getInstrument(); @@ -141,7 +145,7 @@ class MarketDataServiceKucoinBase : public MarketDataService { } that->onFail_(wsConnectionPtr); }, - this->sessionOptions.httpRequestTimeoutMilliSeconds); + this->sessionOptions.httpRequestTimeoutMilliseconds); } #endif std::vector createSendStringList(const WsConnection& wsConnection) override { @@ -155,6 +159,9 @@ class MarketDataServiceKucoinBase : public MarketDataService { if (channelId == this->channelMarketTicker || channelId == this->channelMarketLevel2Depth5 || channelId == this->channelMarketLevel2Depth50) { this->l2UpdateIsReplaceByConnectionIdChannelIdSymbolIdMap[wsConnection.id][channelId][symbolId] = true; } + if (!this->channelMarketKlines.empty() && channelId.rfind(this->channelMarketKlines, 0) == 0) { + exchangeSubscriptionId = this->channelMarketKlines + ":" + symbolId + "_" + channelId.substr(this->channelMarketKlines.length()); + } symbolListByTopicMap[channelId].push_back(symbolId); this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId; this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId; @@ -163,28 +170,56 @@ class MarketDataServiceKucoinBase : public MarketDataService { for (const auto& x : symbolListByTopicMap) { auto topic = x.first; auto symbolList = x.second; - rj::Document document; - document.SetObject(); - rj::Document::AllocatorType& allocator = document.GetAllocator(); - document.AddMember("type", rj::Value("subscribe").Move(), allocator); - document.AddMember("privateChannel", false, allocator); - document.AddMember("response", true, allocator); - document.AddMember("topic", rj::Value((topic + ":" + UtilString::join(symbolList, ",")).c_str(), allocator).Move(), allocator); - int nextRequestId = this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]; - std::string requestId = std::to_string(nextRequestId); - std::vector exchangeSubscriptionIdList; - for (const auto& symbol : symbolList) { - exchangeSubscriptionIdList.push_back(topic + ":" + symbol); + if (!this->channelMarketKlines.empty() && topic.rfind(this->channelMarketKlines, 0) == 0) { + for (const auto& symbol : symbolList) { + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("type", rj::Value("subscribe").Move(), allocator); + document.AddMember("privateChannel", false, allocator); + document.AddMember("response", true, allocator); + std::string exchangeSubscriptionId = + std::string(this->channelMarketKlines) + ":" + symbol + "_" + topic.substr(std::string(this->channelMarketKlines).length()); + document.AddMember("topic", rj::Value(exchangeSubscriptionId.c_str(), allocator).Move(), allocator); + int nextRequestId = this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]; + std::string requestId = std::to_string(nextRequestId); + std::vector exchangeSubscriptionIdList; + exchangeSubscriptionIdList.push_back(exchangeSubscriptionId); + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id] + [this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = + exchangeSubscriptionIdList; + this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; + document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); + } + } else { + rj::Document document; + document.SetObject(); + rj::Document::AllocatorType& allocator = document.GetAllocator(); + document.AddMember("type", rj::Value("subscribe").Move(), allocator); + document.AddMember("privateChannel", false, allocator); + document.AddMember("response", true, allocator); + document.AddMember("topic", rj::Value((topic + ":" + UtilString::join(symbolList, ",")).c_str(), allocator).Move(), allocator); + int nextRequestId = this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]; + std::string requestId = std::to_string(nextRequestId); + std::vector exchangeSubscriptionIdList; + for (const auto& symbol : symbolList) { + exchangeSubscriptionIdList.push_back(topic + ":" + symbol); + } + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = + exchangeSubscriptionIdList; + this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; + document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator); + rj::StringBuffer stringBuffer; + rj::Writer writer(stringBuffer); + document.Accept(writer); + std::string sendString = stringBuffer.GetString(); + sendStringList.push_back(sendString); } - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = - exchangeSubscriptionIdList; - this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; - document.AddMember("id", rj::Value(requestId.c_str(), allocator).Move(), allocator); - rj::StringBuffer stringBuffer; - rj::Writer writer(stringBuffer); - document.Accept(writer); - std::string sendString = stringBuffer.GetString(); - sendStringList.push_back(sendString); } return sendStringList; } @@ -238,14 +273,14 @@ class MarketDataServiceKucoinBase : public MarketDataService { } } void processTextMessage( -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage #else std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #else WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); @@ -257,7 +292,8 @@ class MarketDataServiceKucoinBase : public MarketDataService { if (it != document.MemberEnd()) { std::string type = it->value.GetString(); if (type == "message") { - if (std::string(document["subject"].GetString()) == "trade.l2update") { + std::string subject = document["subject"].GetString(); + if (subject == "trade.l2update") { MarketDataMessage marketDataMessage; marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; std::string exchangeSubscriptionId = document["topic"].GetString(); @@ -292,7 +328,7 @@ class MarketDataServiceKucoinBase : public MarketDataService { int64_t versionId = std::stoll(data["sequenceEnd"].GetString()); this->processOrderBookWithVersionId(versionId, wsConnection, channelId, symbolId, exchangeSubscriptionId, optionMap, marketDataMessageList, marketDataMessage); - } else if (std::string(document["subject"].GetString()) == this->tickerSubject) { + } else if (subject == this->tickerSubject) { MarketDataMessage marketDataMessage; std::string exchangeSubscriptionId = document["topic"].GetString(); std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; @@ -320,7 +356,7 @@ class MarketDataServiceKucoinBase : public MarketDataService { marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); } marketDataMessageList.emplace_back(std::move(marketDataMessage)); - } else if (std::string(document["subject"].GetString()) == this->level2Subject) { + } else if (subject == this->level2Subject) { MarketDataMessage marketDataMessage; std::string exchangeSubscriptionId = document["topic"].GetString(); std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; @@ -353,7 +389,7 @@ class MarketDataServiceKucoinBase : public MarketDataService { } } marketDataMessageList.emplace_back(std::move(marketDataMessage)); - } else if (std::string(document["subject"].GetString()) == this->matchSubject) { + } else if (subject == this->matchSubject) { const rj::Value& data = document["data"]; MarketDataMessage marketDataMessage; marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; @@ -369,18 +405,35 @@ class MarketDataServiceKucoinBase : public MarketDataService { dataPoint.insert({MarketDataMessage::DataFieldType::IS_BUYER_MAKER, std::string(data["side"].GetString()) == "sell" ? "1" : "0"}); marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } else if (subject == this->klineSubject) { + const rj::Value& x = document["data"]["candles"].GetArray(); + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK; + std::string exchangeSubscriptionId = document["topic"].GetString(); + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + marketDataMessage.tp = UtilTime::makeTimePoint(std::make_pair(std::stoll(x[0].GetString()), 0)); + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[1].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[3].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[4].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[2].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[5].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, x[6].GetString()}); + marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); } } else if (type == "welcome") { - this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = + this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingInterval")); - this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = + this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = std::stol(this->extraPropertyByConnectionIdMap.at(wsConnection.id).at("pingTimeout")); - if (this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <= - this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) { - this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = - this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1; + if (this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] <= + this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL]) { + this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = + this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] - 1; } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP Service::onOpen(hdl); WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); this->startSubscribe(wsConnection); @@ -400,11 +453,11 @@ class MarketDataServiceKucoinBase : public MarketDataService { if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { int id = std::stoi(document["id"].GetString()); - if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) != - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() && - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) != - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) { - auto exchangeSubscriptionIdList = this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id); + if (this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.find(wsConnection.id) != + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.end() && + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).find(id) != + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).end()) { + auto exchangeSubscriptionIdList = this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).at(id); for (const auto& exchangeSubscriptionId : exchangeSubscriptionIdList) { auto splitted = UtilString::split(exchangeSubscriptionId, ":"); auto channelId = splitted.at(0); @@ -449,7 +502,8 @@ class MarketDataServiceKucoinBase : public MarketDataService { case Request::Operation::GENERIC_PUBLIC_REQUEST: { MarketDataService::convertRequestForRestGenericPublicRequest(req, request, now, symbolId, credential); } break; - case Request::Operation::GET_RECENT_TRADES: { + case Request::Operation::GET_RECENT_TRADES: + case Request::Operation::GET_HISTORICAL_TRADES: { req.method(http::verb::get); auto target = this->getRecentTradesTarget; std::string queryString; @@ -457,6 +511,63 @@ class MarketDataServiceKucoinBase : public MarketDataService { this->appendSymbolId(queryString, symbolId, "symbol"); req.target(target + "?" + queryString); } break; + case Request::Operation::GET_RECENT_CANDLESTICKS: + case Request::Operation::GET_HISTORICAL_CANDLESTICKS: { + req.method(http::verb::get); + auto target = this->getRecentCandlesticksTarget; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + if (this->isDerivatives) { + this->appendParam(queryString, param, + { + {CCAPI_CANDLESTICK_INTERVAL_SECONDS, "granularity"}, + {CCAPI_START_TIME_SECONDS, "from"}, + {CCAPI_END_TIME_SECONDS, "to"}, + }, + { + {CCAPI_CANDLESTICK_INTERVAL_SECONDS, [that = shared_from_base()]( + const std::string& input) { return std::to_string(std::stoi(input) / 60); }}, + {CCAPI_START_TIME_SECONDS, [that = shared_from_base()]( + const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }}, + {CCAPI_END_TIME_SECONDS, [that = shared_from_base()]( + const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }}, + }); + } else { + this->appendParam(queryString, param, + { + {CCAPI_CANDLESTICK_INTERVAL_SECONDS, "type"}, + {CCAPI_START_TIME_SECONDS, "startAt"}, + {CCAPI_END_TIME_SECONDS, "endAt"}, + }, + { + {CCAPI_CANDLESTICK_INTERVAL_SECONDS, + [that = shared_from_base()](const std::string& input) { + return that->convertCandlestickIntervalSecondsToInterval(std::stoi(input), "", "min", "hour", "day", "week"); + }}, + }); + } + this->appendSymbolId(queryString, symbolId, "symbol"); + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_MARKET_DEPTH: { + req.method(http::verb::get); + auto target = this->getMarketDepthTarget; + ; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendSymbolId(queryString, symbolId, "symbol"); + std::string maxMarketDepthStr = mapGetWithDefault(param, std::string(CCAPI_MARKET_DEPTH_MAX)); + if (maxMarketDepthStr.empty()) { + if (this->isDerivatives) { + std::string toReplace = "depth"; + target.replace(target.find(toReplace), toReplace.length(), "snapshot"); + } + } else { + target = this->getMarketDepthTarget + (this->isDerivatives ? "" : "_") + + std::to_string(this->calculateMarketDepthAllowedByExchange(std::stoi(maxMarketDepthStr), std::vector({20, 100}))); + } + req.target(target + "?" + queryString); + } break; case Request::Operation::GET_INSTRUMENT: { req.method(http::verb::get); auto target = this->getInstrumentTarget; @@ -476,7 +587,8 @@ class MarketDataServiceKucoinBase : public MarketDataService { rj::Document document; document.Parse(textMessage.c_str()); switch (request.getOperation()) { - case Request::Operation::GET_RECENT_TRADES: { + case Request::Operation::GET_RECENT_TRADES: + case Request::Operation::GET_HISTORICAL_TRADES: { for (const auto& x : document["data"].GetArray()) { MarketDataMessage marketDataMessage; marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; @@ -490,6 +602,52 @@ class MarketDataServiceKucoinBase : public MarketDataService { marketDataMessageList.emplace_back(std::move(marketDataMessage)); } } break; + case Request::Operation::GET_RECENT_CANDLESTICKS: + case Request::Operation::GET_HISTORICAL_CANDLESTICKS: { + for (const auto& x : document["data"].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK; + marketDataMessage.tp = this->isDerivatives ? TimePoint(std::chrono::milliseconds(std::stoll(x[0].GetString()))) + : TimePoint(std::chrono::seconds(std::stoll(x[0].GetString()))); + MarketDataMessage::TypeForDataPoint dataPoint; + if (this->isDerivatives) { + dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, std::string(x[1].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, std::string(x[2].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, std::string(x[3].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, std::string(x[4].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, std::string(x[5].GetString())}); + } else { + dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, std::string(x[1].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, std::string(x[3].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, std::string(x[4].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, std::string(x[2].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, std::string(x[5].GetString())}); + dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, std::string(x[6].GetString())}); + } + marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } break; + case Request::Operation::GET_MARKET_DEPTH: { + const rj::Value& data = document["data"]; + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; + marketDataMessage.tp = this->isDerivatives ? TimePoint(std::chrono::nanoseconds(std::stoll(data["ts"].GetString()))) + : TimePoint(std::chrono::milliseconds(std::stoll(data["time"].GetString()))); + for (const auto& x : data["bids"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()}); + marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + for (const auto& x : data["asks"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()}); + marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } break; case Request::Operation::GET_INSTRUMENT: { Message message; message.setTimeReceived(timeReceived); @@ -529,10 +687,12 @@ class MarketDataServiceKucoinBase : public MarketDataService { std::string channelMarketLevel2Depth5; std::string channelMarketLevel2Depth50; std::string channelMarketLevel2; + std::string channelMarketKlines; std::string tickerSubject; std::string tickerBestBidPriceKey; std::string tickerBestAskPriceKey; std::string matchSubject; + std::string klineSubject; std::string recentTradesTimeKey; std::string level2Subject; std::string apiPassphraseName; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_futures.h index ba743fd03..f4764f5d5 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_kucoin_futures.h @@ -7,19 +7,19 @@ namespace ccapi { class MarketDataServiceKucoinFutures : public MarketDataServiceKucoinBase { public: MarketDataServiceKucoinFutures(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr serviceContextPtr) + ServiceContext* serviceContextPtr) : MarketDataServiceKucoinBase(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_KUCOIN_FUTURES; this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName); this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); // this->setHostWsFromUrlWs(this->baseUrlWs); - try { - this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); - } catch (const std::exception& e) { - CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); - } - // #ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + // try { + // this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + // } catch (const std::exception& e) { + // CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + // } + // #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP // #else // try { // this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); @@ -28,6 +28,10 @@ class MarketDataServiceKucoinFutures : public MarketDataServiceKucoinBase { // } // #endif this->getRecentTradesTarget = "/api/v1/trade/history"; + this->getHistoricalTradesTarget = "/api/v1/trade/history"; + this->getRecentCandlesticksTarget = "/api/v1/kline/query"; + this->getHistoricalCandlesticksTarget = "/api/v1/kline/query"; + this->getMarketDepthTarget = "/api/v1/level2/depth"; this->getInstrumentTarget = "/api/v1/contracts/active"; this->getInstrumentsTarget = "/api/v1/contracts/active"; this->isDerivatives = true; diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc.h index b45c24439..224d4fd12 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceMexc : public MarketDataService { public: MarketDataServiceMexc(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr serviceContextPtr) + ServiceContext* serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_MEXC; this->baseUrlWs = std::string(CCAPI_MEXC_URL_WS_BASE) + "/ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); this->setHostWsFromUrlWs(this->baseUrlWs); - try { - this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); - } catch (const std::exception& e) { - CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); - } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET -#else - try { - this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); - } catch (const std::exception& e) { - CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); - } -#endif + // try { + // this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + // } catch (const std::exception& e) { + // CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + // } + // #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP + // #else + // try { + // this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + // } catch (const std::exception& e) { + // CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + // } + // #endif this->getRecentTradesTarget = "/api/v3/trades"; this->getRecentAggTradesTarget = "/api/v3/aggTrades"; this->getInstrumentsTarget = "/api/v3/exchangeInfo"; @@ -37,7 +37,7 @@ class MarketDataServiceMexc : public MarketDataService { protected: #endif // bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); this->send(hdl, R"({"id":)" + std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]) + R"(,"method":"PING"})", @@ -71,7 +71,7 @@ class MarketDataServiceMexc : public MarketDataService { } document.AddMember("params", params, allocator); document.AddMember("id", rj::Value(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]).Move(), allocator); - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = exchangeSubscriptionIdList; this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; rj::StringBuffer stringBuffer; @@ -105,14 +105,14 @@ class MarketDataServiceMexc : public MarketDataService { } } void processTextMessage( -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage #else std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #else WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); @@ -126,11 +126,11 @@ class MarketDataServiceMexc : public MarketDataService { std::string msg = document["msg"].GetString(); if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { int id = std::stoi(document["id"].GetString()); - if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) != - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() && - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) != - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) { - for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) { + if (this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.find(wsConnection.id) != + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.end() && + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).find(id) != + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).end()) { + for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).at(id)) { std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.at(wsConnection.id).find(channelId) != diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc_futures.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc_futures.h index 09ed8fafd..929d48f8c 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc_futures.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_mexc_futures.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceMexcFutures : public MarketDataService { public: MarketDataServiceMexcFutures(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr serviceContextPtr) + ServiceContext* serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_MEXC_FUTURES; this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); this->setHostWsFromUrlWs(this->baseUrlWs); - try { - this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); - } catch (const std::exception& e) { - CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); - } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET -#else - try { - this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); - } catch (const std::exception& e) { - CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); - } -#endif + // try { + // this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + // } catch (const std::exception& e) { + // CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + // } + // #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP + // #else + // try { + // this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + // } catch (const std::exception& e) { + // CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + // } + // #endif this->getRecentTradesTarget = "/api/v1/contract/deals/{symbol}"; this->getInstrumentsTarget = "/api/v1/contract/detail"; } @@ -36,7 +36,7 @@ class MarketDataServiceMexcFutures : public MarketDataService { protected: #endif bool doesHttpBodyContainError(const std::string& body) override { return body.find(R"("code":0)") == std::string::npos; } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, R"({"method":"ping"})", wspp::frame::opcode::text, ec); } #else void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { @@ -92,14 +92,14 @@ class MarketDataServiceMexcFutures : public MarketDataService { } } void processTextMessage( -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage #else std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #else WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_okx.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_okx.h index 5d3be02af..16ed7f4ed 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_okx.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_okx.h @@ -7,31 +7,36 @@ namespace ccapi { class MarketDataServiceOkx : public MarketDataService { public: MarketDataServiceOkx(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr serviceContextPtr) + ServiceContext* serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_OKX; this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + CCAPI_OKX_PUBLIC_WS_PATH; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); this->setHostWsFromUrlWs(this->baseUrlWs); - try { - this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); - } catch (const std::exception& e) { - CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); - } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET -#else - try { - this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); - } catch (const std::exception& e) { - CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); - } -#endif + // try { + // this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + // } catch (const std::exception& e) { + // CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + // } + // #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP + // #else + // try { + // this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + // } catch (const std::exception& e) { + // CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + // } + // #endif this->apiKeyName = CCAPI_OKX_API_KEY; this->apiSecretName = CCAPI_OKX_API_SECRET; this->apiPassphraseName = CCAPI_OKX_API_PASSPHRASE; this->setupCredential({this->apiKeyName, this->apiSecretName, this->apiPassphraseName}); this->getRecentTradesTarget = "/api/v5/market/trades"; + this->getHistoricalTradesTarget = "/api/v5/market/history-trades"; + this->getRecentCandlesticksTarget = "/api/v5/market/candles"; + this->getHistoricalCandlesticksTarget = "/api/v5/market/history-candles"; + this->getMarketDepthTarget = "/api/v5/market/books"; + this->getRecentTradesTarget = "/api/v5/market/trades"; this->getInstrumentTarget = "/api/v5/public/instruments"; this->getInstrumentsTarget = "/api/v5/public/instruments"; } @@ -40,13 +45,21 @@ class MarketDataServiceOkx : public MarketDataService { private: #endif + std::string getInstrumentGroup(const Subscription& subscription) override { + std::string baseUrlWsGivenSubscription(this->baseUrlWs); + if (subscription.getField() == CCAPI_CANDLESTICK) { + baseUrlWsGivenSubscription = this->sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + CCAPI_OKX_BUSINESS_WS_PATH; + } + return baseUrlWsGivenSubscription + "|" + subscription.getField() + "|" + subscription.getSerializedOptions() + "|" + + subscription.getSerializedCredential(); + } bool doesHttpBodyContainError(const std::string& body) override { return !std::regex_search(body, std::regex("\"code\":\\s*\"0\"")); } void prepareSubscriptionDetail(std::string& channelId, std::string& symbolId, const std::string& field, const WsConnection& wsConnection, const Subscription& subscription, const std::map optionMap) override { auto marketDepthRequested = std::stoi(optionMap.at(CCAPI_MARKET_DEPTH_MAX)); - auto conflateIntervalMilliSeconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); + auto conflateIntervalMilliseconds = std::stoi(optionMap.at(CCAPI_CONFLATE_INTERVAL_MILLISECONDS)); if (field == CCAPI_MARKET_DEPTH) { - if (conflateIntervalMilliSeconds < 100) { + if (conflateIntervalMilliseconds < 100) { if (marketDepthRequested == 1) { channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH1_L2_TBT; } else if (marketDepthRequested <= 50) { @@ -61,9 +74,13 @@ class MarketDataServiceOkx : public MarketDataService { channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_PUBLIC_DEPTH400; } } + } else if (field == CCAPI_CANDLESTICK) { + std::string interval = + this->convertCandlestickIntervalSecondsToInterval(std::stoi(optionMap.at(CCAPI_CANDLESTICK_INTERVAL_SECONDS)), "s", "m", "H", "D", "W"); + channelId = CCAPI_WEBSOCKET_OKX_CHANNEL_CANDLESTICK + interval; } } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { this->send(hdl, "ping", wspp::frame::opcode::text, ec); } #else void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) override { this->send(wsConnectionPtr, "ping", ec); } @@ -122,14 +139,14 @@ class MarketDataServiceOkx : public MarketDataService { return intToHex(csCalc); } void processTextMessage( -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage #else std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #else WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); @@ -140,7 +157,7 @@ class MarketDataServiceOkx : public MarketDataService { auto it = document.FindMember("event"); std::string eventStr = it != document.MemberEnd() ? it->value.GetString() : ""; if (eventStr == "login") { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP this->startSubscribe(wsConnection); #else this->startSubscribe(wsConnectionPtr); @@ -249,6 +266,23 @@ class MarketDataServiceOkx : public MarketDataService { marketDataMessage.data[MarketDataMessage::DataType::TRADE].emplace_back(std::move(dataPoint)); marketDataMessageList.emplace_back(std::move(marketDataMessage)); } + } else if (channelId.rfind(CCAPI_WEBSOCKET_OKX_CHANNEL_CANDLESTICK, 0) == 0) { + for (const auto& datum : document["data"].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK; + marketDataMessage.recapType = MarketDataMessage::RecapType::NONE; + marketDataMessage.tp = TimePoint(std::chrono::milliseconds(std::stoll(datum[0].GetString()))); + marketDataMessage.exchangeSubscriptionId = exchangeSubscriptionId; + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, datum[1].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, datum[2].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, datum[3].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, datum[4].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, datum[5].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, datum[7].GetString()}); + marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } } } } @@ -273,6 +307,66 @@ class MarketDataServiceOkx : public MarketDataService { this->appendSymbolId(queryString, symbolId, "instId"); req.target(target + "?" + queryString); } break; + case Request::Operation::GET_HISTORICAL_TRADES: { + req.method(http::verb::get); + auto target = this->getHistoricalTradesTarget; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_LIMIT, "limit"}, + {CCAPI_START_TRADE_ID, "before"}, + {CCAPI_END_TRADE_ID, "after"}, + {CCAPI_START_TIME_SECONDS, "before"}, + {CCAPI_END_TIME_SECONDS, "after"}, + }, + { + {CCAPI_START_TIME_SECONDS, [that = shared_from_base()]( + const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }}, + {CCAPI_END_TIME_SECONDS, [that = shared_from_base()]( + const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }}, + }); + this->appendSymbolId(queryString, symbolId, "instId"); + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_RECENT_CANDLESTICKS: + case Request::Operation::GET_HISTORICAL_CANDLESTICKS: { + req.method(http::verb::get); + auto target = this->getRecentCandlesticksTarget; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_CANDLESTICK_INTERVAL_SECONDS, "bar"}, + {CCAPI_LIMIT, "limit"}, + {CCAPI_START_TIME_SECONDS, "before"}, + {CCAPI_END_TIME_SECONDS, "after"}, + }, + { + {CCAPI_CANDLESTICK_INTERVAL_SECONDS, + [that = shared_from_base()](const std::string& input) { + return that->convertCandlestickIntervalSecondsToInterval(std::stoi(input), "s", "m", "H", "D", "W"); + }}, + {CCAPI_START_TIME_SECONDS, [that = shared_from_base()]( + const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }}, + {CCAPI_END_TIME_SECONDS, [that = shared_from_base()]( + const std::string& input) { return that->convertParamTimeSecondsToTimeMilliseconds(input); }}, + }); + this->appendSymbolId(queryString, symbolId, "instId"); + req.target(target + "?" + queryString); + } break; + case Request::Operation::GET_MARKET_DEPTH: { + req.method(http::verb::get); + auto target = this->getMarketDepthTarget; + std::string queryString; + const std::map param = request.getFirstParamWithDefault(); + this->appendParam(queryString, param, + { + {CCAPI_MARKET_DEPTH_MAX, "sz"}, + }); + this->appendSymbolId(queryString, symbolId, "instId"); + req.target(target + "?" + queryString); + } break; case Request::Operation::GET_INSTRUMENT: { req.method(http::verb::get); auto target = this->getInstrumentTarget; @@ -317,7 +411,8 @@ class MarketDataServiceOkx : public MarketDataService { rj::Document document; document.Parse(textMessage.c_str()); switch (request.getOperation()) { - case Request::Operation::GET_RECENT_TRADES: { + case Request::Operation::GET_RECENT_TRADES: + case Request::Operation::GET_HISTORICAL_TRADES: { for (const auto& datum : document["data"].GetArray()) { MarketDataMessage marketDataMessage; marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_TRADE; @@ -331,6 +426,42 @@ class MarketDataServiceOkx : public MarketDataService { marketDataMessageList.emplace_back(std::move(marketDataMessage)); } } break; + case Request::Operation::GET_RECENT_CANDLESTICKS: + case Request::Operation::GET_HISTORICAL_CANDLESTICKS: { + for (const auto& x : document["data"].GetArray()) { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_CANDLESTICK; + marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(x[0].GetString())); + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::OPEN_PRICE, x[1].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::HIGH_PRICE, x[2].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::LOW_PRICE, x[3].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::CLOSE_PRICE, x[4].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::VOLUME, x[5].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::QUOTE_VOLUME, x[7].GetString()}); + marketDataMessage.data[MarketDataMessage::DataType::CANDLESTICK].emplace_back(std::move(dataPoint)); + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } + } break; + case Request::Operation::GET_MARKET_DEPTH: { + MarketDataMessage marketDataMessage; + marketDataMessage.type = MarketDataMessage::Type::MARKET_DATA_EVENTS_MARKET_DEPTH; + const rj::Value& data = document["data"][0]; + marketDataMessage.tp = UtilTime::makeTimePointFromMilliseconds(std::stoll(data["ts"].GetString())); + for (const auto& x : data["bids"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()}); + marketDataMessage.data[MarketDataMessage::DataType::BID].emplace_back(std::move(dataPoint)); + } + for (const auto& x : data["asks"].GetArray()) { + MarketDataMessage::TypeForDataPoint dataPoint; + dataPoint.insert({MarketDataMessage::DataFieldType::PRICE, x[0].GetString()}); + dataPoint.insert({MarketDataMessage::DataFieldType::SIZE, x[1].GetString()}); + marketDataMessage.data[MarketDataMessage::DataType::ASK].emplace_back(std::move(dataPoint)); + } + marketDataMessageList.emplace_back(std::move(marketDataMessage)); + } break; case Request::Operation::GET_INSTRUMENT: { Message message; message.setTimeReceived(timeReceived); diff --git a/linux/include/ccapi_cpp/service/ccapi_market_data_service_whitebit.h b/linux/include/ccapi_cpp/service/ccapi_market_data_service_whitebit.h index 3a1362d25..7aaa07925 100644 --- a/linux/include/ccapi_cpp/service/ccapi_market_data_service_whitebit.h +++ b/linux/include/ccapi_cpp/service/ccapi_market_data_service_whitebit.h @@ -7,26 +7,26 @@ namespace ccapi { class MarketDataServiceWhitebit : public MarketDataService { public: MarketDataServiceWhitebit(std::function*)> eventHandler, SessionOptions sessionOptions, SessionConfigs sessionConfigs, - std::shared_ptr serviceContextPtr) + ServiceContext* serviceContextPtr) : MarketDataService(eventHandler, sessionOptions, sessionConfigs, serviceContextPtr) { this->exchangeName = CCAPI_EXCHANGE_NAME_WHITEBIT; this->baseUrlWs = sessionConfigs.getUrlWebsocketBase().at(this->exchangeName) + "/ws"; this->baseUrlRest = sessionConfigs.getUrlRestBase().at(this->exchangeName); this->setHostRestFromUrlRest(this->baseUrlRest); this->setHostWsFromUrlWs(this->baseUrlWs); - try { - this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); - } catch (const std::exception& e) { - CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); - } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET -#else - try { - this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); - } catch (const std::exception& e) { - CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); - } -#endif + // try { + // this->tcpResolverResultsRest = this->resolver.resolve(this->hostRest, this->portRest); + // } catch (const std::exception& e) { + // CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + // } + // #ifdef CCAPI_LEGACY_USE_WEBSOCKETPP + // #else + // try { + // this->tcpResolverResultsWs = this->resolverWs.resolve(this->hostWs, this->portWs); + // } catch (const std::exception& e) { + // CCAPI_LOGGER_FATAL(std::string("e.what() = ") + e.what()); + // } + // #endif this->getRecentTradesTarget = "/api/v4/public/trades/{market}"; this->getInstrumentsTarget = "/api/v4/public/markets"; this->methodDepthSubscribe = std::string(CCAPI_WEBSOCKET_WHITEBIT_CHANNEL_MARKET_DEPTH) + "_subscribe"; @@ -40,7 +40,7 @@ class MarketDataServiceWhitebit : public MarketDataService { private: #endif -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP void pingOnApplicationLevel(wspp::connection_hdl hdl, ErrorCode& ec) override { WsConnection& wsConnection = this->getWsConnectionFromConnectionPtr(this->serviceContextPtr->tlsClientPtr->get_con_from_hdl(hdl)); this->send(hdl, R"({"id":)" + std::to_string(this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]) + R"(,"method":"ping","params":[]})", @@ -91,8 +91,8 @@ class MarketDataServiceWhitebit : public MarketDataService { sendStringList.push_back(sendString); this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID] = channelId; this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID] = symbolId; - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] - [this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = { + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id] + [this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = { exchangeSubscriptionId}; this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; } @@ -118,8 +118,7 @@ class MarketDataServiceWhitebit : public MarketDataService { document.Accept(writer); std::string sendString = stringBuffer.GetString(); sendStringList.push_back(sendString); - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] - [this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap[wsConnection.id][this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id]] = exchangeSubscriptionIdList; this->exchangeJsonPayloadIdByConnectionIdMap[wsConnection.id] += 1; } @@ -127,14 +126,14 @@ class MarketDataServiceWhitebit : public MarketDataService { return sendStringList; } void processTextMessage( -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP WsConnection& wsConnection, wspp::connection_hdl hdl, const std::string& textMessage #else std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessageView #endif , const TimePoint& timeReceived, Event& event, std::vector& marketDataMessageList) override { -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #else WsConnection& wsConnection = *wsConnectionPtr; std::string textMessage(textMessageView); @@ -216,11 +215,11 @@ class MarketDataServiceWhitebit : public MarketDataService { std::vector correlationIdList; if (this->correlationIdListByConnectionIdChannelIdSymbolIdMap.find(wsConnection.id) != this->correlationIdListByConnectionIdChannelIdSymbolIdMap.end()) { - if (this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.find(wsConnection.id) != - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.end() && - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).find(id) != - this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).end()) { - for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByExchangeJsonPayloadIdByConnectionIdMap.at(wsConnection.id).at(id)) { + if (this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.find(wsConnection.id) != + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.end() && + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).find(id) != + this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).end()) { + for (const auto& exchangeSubscriptionId : this->exchangeSubscriptionIdListByConnectionIdExchangeJsonPayloadIdMap.at(wsConnection.id).at(id)) { std::string channelId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_CHANNEL_ID]; std::string symbolId = this->channelIdSymbolIdByConnectionIdExchangeSubscriptionIdMap[wsConnection.id][exchangeSubscriptionId][CCAPI_SYMBOL_ID]; diff --git a/linux/include/ccapi_cpp/service/ccapi_service.h b/linux/include/ccapi_cpp/service/ccapi_service.h index 7ce93e312..1fe2cec0b 100644 --- a/linux/include/ccapi_cpp/service/ccapi_service.h +++ b/linux/include/ccapi_cpp/service/ccapi_service.h @@ -31,7 +31,7 @@ #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" // clang-format off -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #include "websocketpp/config/boost_config.hpp" #include "websocketpp/client.hpp" #include "websocketpp/common/connection_hdl.hpp" @@ -41,7 +41,7 @@ #endif // clang-format on -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #if defined(CCAPI_ENABLE_SERVICE_MARKET_DATA) && \ (defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) || \ defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && \ @@ -69,9 +69,9 @@ namespace beast = boost::beast; namespace http = beast::http; namespace net = boost::asio; -namespace ssl = boost::asio::ssl; -using tcp = boost::asio::ip::tcp; -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +namespace ssl = net::ssl; +using tcp = net::ip::tcp; +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP namespace wspp = websocketpp; #endif namespace rj = rapidjson; @@ -82,8 +82,8 @@ namespace ccapi { */ class Service : public std::enable_shared_from_this { public: - typedef std::shared_ptr ServiceContextPtr; -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET + typedef ServiceContext* ServiceContextPtr; +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP typedef wspp::lib::error_code ErrorCode; #else typedef boost::system::error_code ErrorCode; // a.k.a. beast::error_code @@ -117,16 +117,15 @@ class Service : public std::enable_shared_from_this { sessionConfigs(sessionConfigs), serviceContextPtr(serviceContextPtr), resolver(*serviceContextPtr->ioContextPtr), - resolverWs(*serviceContextPtr->ioContextPtr), - httpConnectionPool(sessionOptions.httpConnectionPoolMaxSize) { + resolverWs(*serviceContextPtr->ioContextPtr) { this->enableCheckPingPongWebsocketProtocolLevel = this->sessionOptions.enableCheckPingPongWebsocketProtocolLevel; this->enableCheckPingPongWebsocketApplicationLevel = this->sessionOptions.enableCheckPingPongWebsocketApplicationLevel; - // this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pingWebsocketProtocolLevelIntervalMilliSeconds; - // this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pongWebsocketProtocolLevelTimeoutMilliSeconds; - this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pingWebsocketApplicationLevelIntervalMilliSeconds; - this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pongWebsocketApplicationLevelTimeoutMilliSeconds; - this->pingIntervalMilliSecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixIntervalMilliSeconds; - this->pongTimeoutMilliSecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixTimeoutMilliSeconds; + // this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pingWebsocketProtocolLevelIntervalMilliseconds; + // this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = sessionOptions.pongWebsocketProtocolLevelTimeoutMilliseconds; + this->pingIntervalMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pingWebsocketApplicationLevelIntervalMilliseconds; + this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::WEBSOCKET_APPLICATION_LEVEL] = sessionOptions.pongWebsocketApplicationLevelTimeoutMilliseconds; + this->pingIntervalMillisecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixIntervalMilliseconds; + this->pongTimeoutMillisecondsByMethodMap[PingPongMethod::FIX_PROTOCOL_LEVEL] = sessionOptions.heartbeatFixTimeoutMilliseconds; } virtual ~Service() { for (const auto& x : this->pingTimerByMethodByConnectionIdMap) { @@ -142,11 +141,20 @@ class Service : public std::enable_shared_from_this { for (const auto& x : this->connectRetryOnFailTimerByConnectionIdMap) { x.second->cancel(); } - if (this->httpConnectionPoolPurgeTimer) { - this->httpConnectionPoolPurgeTimer->cancel(); + } + void purgeHttpConnectionPool() { this->httpConnectionPool.clear(); } + void purgeHttpConnectionPool(const std::string& localIpAddress) { this->httpConnectionPool.erase(localIpAddress); } + void purgeHttpConnectionPool(const std::string& localIpAddress, const std::string& baseUrl) { this->httpConnectionPool[localIpAddress].erase(baseUrl); } + void forceCloseWebsocketConnections() { + for (const auto& x : this->wsConnectionByIdMap) { + ErrorCode ec; + auto wsConnectionPtr = x.second; + this->close(wsConnectionPtr, beast::websocket::close_code::normal, beast::websocket::close_reason("force close"), ec); + if (ec) { + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown"); + } } } - void purgeHttpConnectionPool() { this->httpConnectionPool.purge(); } void stop() { for (const auto& x : this->sendRequestDelayTimerByCorrelationIdMap) { x.second->cancel(); @@ -155,21 +163,12 @@ class Service : public std::enable_shared_from_this { this->shouldContinue = false; for (const auto& x : this->wsConnectionByIdMap) { ErrorCode ec; -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET - auto wsConnection = x.second; - this->close(wsConnection, wsConnection.hdl, websocketpp::close::status::normal, "stop", ec); -#else auto wsConnectionPtr = x.second; this->close(wsConnectionPtr, beast::websocket::close_code::normal, beast::websocket::close_reason("stop"), ec); -#endif if (ec) { this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "shutdown"); } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET - this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnection.id] = false; -#else this->shouldProcessRemainingMessageOnClosingByConnectionIdMap[wsConnectionPtr->id] = false; -#endif } } virtual void convertRequestForRestCustom(http::request& req, const Request& request, const TimePoint& now, const std::string& symbolId, @@ -182,14 +181,14 @@ class Service : public std::enable_shared_from_this { const std::map& credential) {} virtual void processSuccessfulTextMessageRest(int statusCode, const Request& request, const std::string& textMessage, const TimePoint& timeReceived, Queue* eventQueuePtr) {} - std::shared_ptr> sendRequest(Request& request, const bool useFuture, const TimePoint& now, long delayMilliSeconds, + std::shared_ptr> sendRequest(Request& request, const bool useFuture, const TimePoint& now, long delayMilliseconds, Queue* eventQueuePtr) { CCAPI_LOGGER_FUNCTION_ENTER; CCAPI_LOGGER_DEBUG("request = " + toString(request)); CCAPI_LOGGER_DEBUG("useFuture = " + toString(useFuture)); TimePoint then; - if (delayMilliSeconds > 0) { - then = now + std::chrono::milliseconds(delayMilliSeconds); + if (delayMilliseconds > 0) { + then = now + std::chrono::milliseconds(delayMilliseconds); } else { then = now; } @@ -217,24 +216,24 @@ class Service : public std::enable_shared_from_this { } std::shared_ptr> promisePtr(promisePtrRaw); HttpRetry retry(0, 0, "", promisePtr); - if (delayMilliSeconds > 0) { - TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliSeconds))); + if (delayMilliseconds > 0) { + TimerPtr timerPtr(new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(delayMilliseconds))); timerPtr->async_wait([that = shared_from_this(), request, req, retry, eventQueuePtr](ErrorCode const& ec) mutable { if (ec) { CCAPI_LOGGER_ERROR("request = " + toString(request) + ", sendRequest timer error: " + ec.message()); that->onError(Event::Type::REQUEST_STATUS, Message::Type::GENERIC_ERROR, ec, "timer", {request.getCorrelationId()}, eventQueuePtr); } else { - auto thatReq = req; auto now = UtilTime::now(); request.setTimeSent(now); - that->tryRequest(request, thatReq, retry, eventQueuePtr); + that->tryRequest(request, req, retry, eventQueuePtr); } that->sendRequestDelayTimerByCorrelationIdMap.erase(request.getCorrelationId()); }); this->sendRequestDelayTimerByCorrelationIdMap[request.getCorrelationId()] = timerPtr; } else { request.setTimeSent(now); - this->tryRequest(request, req, retry, eventQueuePtr); + net::post(*this->serviceContextPtr->ioContextPtr, + [that = shared_from_this(), request, req, retry, eventQueuePtr]() mutable { that->tryRequest(request, req, retry, eventQueuePtr); }); } std::shared_ptr> futurePtr(nullptr); if (useFuture) { @@ -303,10 +302,10 @@ class Service : public std::enable_shared_from_this { // return output; // } typedef ServiceContext::SslContextPtr SslContextPtr; -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP typedef ServiceContext::TlsClient TlsClient; #endif - typedef std::shared_ptr TimerPtr; + typedef std::shared_ptr TimerPtr; void setHostRestFromUrlRest(std::string baseUrlRest) { auto hostPort = this->extractHostFromUrl(baseUrlRest); this->hostRest = hostPort.first; @@ -341,7 +340,7 @@ class Service : public std::enable_shared_from_this { return std::static_pointer_cast(shared_from_this()); } void sendRequest(const http::request& req, std::function errorHandler, - std::function&)> responseHandler, long timeoutMilliSeconds) { + std::function&)> responseHandler, long timeoutMilliseconds) { #if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) std::ostringstream oss; oss << req; @@ -358,11 +357,17 @@ class Service : public std::enable_shared_from_this { } std::shared_ptr httpConnectionPtr(new HttpConnection(this->hostRest, this->portRest, streamPtr)); CCAPI_LOGGER_DEBUG("httpConnection = " + toString(*httpConnectionPtr)); - this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliSeconds, this->tcpResolverResultsRest); + std::shared_ptr newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr)); + CCAPI_LOGGER_TRACE("this->hostRest = " + this->hostRest); + CCAPI_LOGGER_TRACE("this->portRest = " + this->portRest); + newResolverPtr->async_resolve(this->hostRest, this->portRest, + beast::bind_front_handler(&Service::onResolve, shared_from_this(), httpConnectionPtr, newResolverPtr, req, errorHandler, + responseHandler, timeoutMilliseconds)); + // this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliseconds, this->tcpResolverResultsRest); } void sendRequest(const std::string& host, const std::string& port, const http::request& req, std::function errorHandler, std::function&)> responseHandler, - long timeoutMilliSeconds) { + long timeoutMilliseconds) { #if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) std::ostringstream oss; oss << req; @@ -379,26 +384,28 @@ class Service : public std::enable_shared_from_this { std::shared_ptr httpConnectionPtr(new HttpConnection(host, port, streamPtr)); CCAPI_LOGGER_DEBUG("httpConnection = " + toString(*httpConnectionPtr)); std::shared_ptr newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr)); + CCAPI_LOGGER_TRACE("host = " + host); + CCAPI_LOGGER_TRACE("port = " + port); newResolverPtr->async_resolve(host, port, beast::bind_front_handler(&Service::onResolve, shared_from_this(), httpConnectionPtr, newResolverPtr, req, errorHandler, - responseHandler, timeoutMilliSeconds)); + responseHandler, timeoutMilliseconds)); } void onResolve(std::shared_ptr httpConnectionPtr, std::shared_ptr newResolverPtr, http::request req, std::function errorHandler, std::function&)> responseHandler, - long timeoutMilliSeconds, beast::error_code ec, tcp::resolver::results_type tcpNewResolverResults) { + long timeoutMilliseconds, beast::error_code ec, tcp::resolver::results_type tcpNewResolverResults) { if (ec) { CCAPI_LOGGER_TRACE("fail"); errorHandler(ec); return; } - this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliSeconds, tcpNewResolverResults); + this->startConnect(httpConnectionPtr, req, errorHandler, responseHandler, timeoutMilliseconds, tcpNewResolverResults); } void startConnect(std::shared_ptr httpConnectionPtr, http::request req, std::function errorHandler, std::function&)> responseHandler, - long timeoutMilliSeconds, tcp::resolver::results_type tcpNewResolverResults) { + long timeoutMilliseconds, tcp::resolver::results_type tcpNewResolverResults) { beast::ssl_stream& stream = *httpConnectionPtr->streamPtr; - if (timeoutMilliSeconds > 0) { - beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(timeoutMilliSeconds)); + if (timeoutMilliseconds > 0) { + beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(timeoutMilliseconds)); } CCAPI_LOGGER_TRACE("before async_connect"); beast::get_lowest_layer(stream).async_connect( @@ -488,7 +495,7 @@ class Service : public std::enable_shared_from_this { responseHandler(*resPtr); } template - std::shared_ptr createStream(std::shared_ptr iocPtr, std::shared_ptr ctxPtr, const std::string& host) { + std::shared_ptr createStream(net::io_context* iocPtr, net::ssl::context* ctxPtr, const std::string& host) { std::shared_ptr streamPtr(new T(*iocPtr, *ctxPtr)); // Set SNI Hostname (many hosts need this to handshake successfully) if (!SSL_set_tlsext_host_name(streamPtr->native_handle(), host.c_str())) { @@ -498,25 +505,15 @@ class Service : public std::enable_shared_from_this { } return streamPtr; } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #else - template <> - std::shared_ptr>> createStream(std::shared_ptr iocPtr, - std::shared_ptr ctxPtr, - const std::string& host) { - CCAPI_LOGGER_TRACE("host = " + host) + std::shared_ptr>> createWsStream(net::io_context* iocPtr, net::ssl::context* ctxPtr) { std::shared_ptr>> streamPtr( new beast::websocket::stream>(*iocPtr, *ctxPtr)); - // Set SNI Hostname (many hosts need this to handshake successfully) - if (!SSL_set_tlsext_host_name(streamPtr->next_layer().native_handle(), host.c_str())) { - beast::error_code ec{static_cast(::ERR_get_error()), net::error::get_ssl_category()}; - CCAPI_LOGGER_DEBUG("error SSL_set_tlsext_host_name: " + ec.message()); - throw ec; - } return streamPtr; } #endif - // std::shared_ptr> createStream(std::shared_ptr iocPtr, std::shared_ptr ctxPtr, + // std::shared_ptr> createStream(net::io_context* iocPtr, net::ssl::context* ctxPtr, // const std::string& host) { // std::shared_ptr> streamPtr(new beast::ssl_stream(*iocPtr, *ctxPtr)); // // Set SNI Hostname (many hosts need this to handshake successfully) @@ -527,31 +524,120 @@ class Service : public std::enable_shared_from_this { // } // return streamPtr; // } - void performRequest(std::shared_ptr httpConnectionPtr, const Request& request, http::request& req, const HttpRetry& retry, - Queue* eventQueuePtr) { + void performRequestWithNewHttpConnection(std::shared_ptr httpConnectionPtr, const Request& request, http::request& req, + const HttpRetry& retry, Queue* eventQueuePtr) { CCAPI_LOGGER_FUNCTION_ENTER; CCAPI_LOGGER_DEBUG("httpConnection = " + toString(*httpConnectionPtr)); + CCAPI_LOGGER_DEBUG("request = " + toString(request)); CCAPI_LOGGER_DEBUG("retry = " + toString(retry)); beast::ssl_stream& stream = *httpConnectionPtr->streamPtr; - CCAPI_LOGGER_DEBUG("this->sessionOptions.httpRequestTimeoutMilliSeconds = " + toString(this->sessionOptions.httpRequestTimeoutMilliSeconds)); - if (this->sessionOptions.httpRequestTimeoutMilliSeconds > 0) { - beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliSeconds)); + CCAPI_LOGGER_DEBUG("this->sessionOptions.httpRequestTimeoutMilliseconds = " + toString(this->sessionOptions.httpRequestTimeoutMilliseconds)); + if (this->sessionOptions.httpRequestTimeoutMilliseconds > 0) { + beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliseconds)); } - CCAPI_LOGGER_TRACE("before async_connect"); - beast::get_lowest_layer(stream).async_connect( - this->tcpResolverResultsRest, - beast::bind_front_handler(&Service::onConnect_2, shared_from_this(), httpConnectionPtr, request, req, retry, eventQueuePtr)); - CCAPI_LOGGER_TRACE("after async_connect"); + const auto& localIpAddress = request.getLocalIpAddress(); + CCAPI_LOGGER_TRACE("localIpAddress = " + localIpAddress); + if (!localIpAddress.empty()) { + if (!beast::get_lowest_layer(stream).socket().is_open()) { + ErrorCode ec; + CCAPI_LOGGER_TRACE("before socket open"); + beast::get_lowest_layer(stream).socket().open(net::ip::tcp::v4(), ec); + if (ec) { + CCAPI_LOGGER_TRACE("fail"); + this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "socket open", {request.getCorrelationId()}, eventQueuePtr); + return; + } + } + ErrorCode ec; + tcp::endpoint existingLocalEndpoint = beast::get_lowest_layer(stream).socket().local_endpoint(ec); + if (ec) { + CCAPI_LOGGER_TRACE("fail"); + this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "socket get local endpoint", {request.getCorrelationId()}, + eventQueuePtr); + return; + } + tcp::endpoint localEndpoint(net::ip::address::from_string(localIpAddress), + 0); // Note: Setting the port to 0 means the OS will select a free port for you + if (localEndpoint != existingLocalEndpoint) { + ErrorCode ec; + CCAPI_LOGGER_TRACE("before socket bind"); + beast::get_lowest_layer(stream).socket().bind(localEndpoint, ec); + if (ec) { + CCAPI_LOGGER_TRACE("fail"); + this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "socket bind", {request.getCorrelationId()}, eventQueuePtr); + return; + } + } + } + std::shared_ptr newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr)); + CCAPI_LOGGER_TRACE("httpConnectionPtr->host = " + httpConnectionPtr->host); + CCAPI_LOGGER_TRACE("httpConnectionPtr->port = " + httpConnectionPtr->port); + newResolverPtr->async_resolve( + httpConnectionPtr->host, httpConnectionPtr->port, + beast::bind_front_handler(&Service::onResolveWorkaround, shared_from_this(), httpConnectionPtr, newResolverPtr, request, req, retry, eventQueuePtr)); CCAPI_LOGGER_FUNCTION_EXIT; } - void onConnect_2(std::shared_ptr httpConnectionPtr, Request request, http::request req, HttpRetry retry, - Queue* eventQueuePtr, beast::error_code ec, tcp::resolver::results_type::endpoint_type) { - CCAPI_LOGGER_TRACE("async_connect callback start"); + void onResolveWorkaround(std::shared_ptr httpConnectionPtr, std::shared_ptr newResolverPtr, Request request, + http::request req, HttpRetry retry, Queue* eventQueuePtr, beast::error_code ec, + tcp::resolver::results_type tcpNewResolverResults) { if (ec) { CCAPI_LOGGER_TRACE("fail"); + this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "DNS resolve", {request.getCorrelationId()}, eventQueuePtr); + return; + } + CCAPI_LOGGER_TRACE("before asyncConnectWorkaround"); + TimerPtr timerPtr{nullptr}; + if (this->sessionOptions.httpRequestTimeoutMilliseconds > 0) { + timerPtr = std::make_shared(*this->serviceContextPtr->ioContextPtr, + std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliseconds)); + timerPtr->async_wait([httpConnectionPtr](ErrorCode const& ec) { + if (ec) { + if (ec != net::error::make_error_code(net::error::basic_errors::operation_aborted)) { + CCAPI_LOGGER_ERROR("httpConnectionPtr = " + toString(*httpConnectionPtr) + ", connect timeout timer error: " + ec.message()); + } + } else { + CCAPI_LOGGER_TRACE("httpConnectionPtr = " + toString(*httpConnectionPtr) + ", connect timeout timer triggered"); + beast::ssl_stream& stream = *httpConnectionPtr->streamPtr; + beast::get_lowest_layer(stream).socket().cancel(); + } + }); + } + this->asyncConnectWorkaround(httpConnectionPtr, timerPtr, request, req, retry, eventQueuePtr, tcpNewResolverResults, 0); + CCAPI_LOGGER_TRACE("after asyncConnectWorkaround"); + } + // used to avoid asio close and reopen the socket and therefore losing the bound local ip address + void asyncConnectWorkaround(std::shared_ptr httpConnectionPtr, TimerPtr timerPtr, Request request, http::request req, + HttpRetry retry, Queue* eventQueuePtr, tcp::resolver::results_type tcpNewResolverResults, + size_t tcpNewResolverResultsIndex) { + auto it = tcpNewResolverResults.begin(); + std::advance(it, tcpNewResolverResultsIndex); + if (it == tcpNewResolverResults.end()) { + ErrorCode ec = net::error::make_error_code(net::error::misc_errors::not_found); this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "connect", {request.getCorrelationId()}, eventQueuePtr); return; } + CCAPI_LOGGER_TRACE("before async_connect"); + beast::ssl_stream& stream = *httpConnectionPtr->streamPtr; + beast::get_lowest_layer(stream).socket().async_connect( + *it, beast::bind_front_handler(&Service::onConnect_2, shared_from_this(), httpConnectionPtr, timerPtr, request, req, retry, eventQueuePtr, + tcpNewResolverResults, tcpNewResolverResultsIndex)); + CCAPI_LOGGER_TRACE("after async_connect"); + } + void onConnect_2(std::shared_ptr httpConnectionPtr, TimerPtr timerPtr, Request request, http::request req, HttpRetry retry, + Queue* eventQueuePtr, tcp::resolver::results_type tcpNewResolverResults, size_t tcpNewResolverResultsIndex, beast::error_code ec) { + CCAPI_LOGGER_TRACE("async_connect callback start"); + CCAPI_LOGGER_TRACE("local endpoint has address " + beast::get_lowest_layer(*httpConnectionPtr->streamPtr).socket().local_endpoint().address().to_string()); + if (ec) { + CCAPI_LOGGER_TRACE("fail"); + if (ec == net::error::make_error_code(net::error::basic_errors::operation_aborted)) { + CCAPI_LOGGER_TRACE("fail"); + this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "connect attempt timeout", {request.getCorrelationId()}, eventQueuePtr); + return; + } + this->asyncConnectWorkaround(httpConnectionPtr, timerPtr, request, req, retry, eventQueuePtr, tcpNewResolverResults, tcpNewResolverResultsIndex + 1); + return; + } + timerPtr->cancel(); CCAPI_LOGGER_TRACE("connected"); beast::ssl_stream& stream = *httpConnectionPtr->streamPtr; // #ifdef CCAPI_DISABLE_NAGLE_ALGORITHM @@ -576,8 +662,8 @@ class Service : public std::enable_shared_from_this { void startWrite_2(std::shared_ptr httpConnectionPtr, Request request, http::request req, HttpRetry retry, Queue* eventQueuePtr) { beast::ssl_stream& stream = *httpConnectionPtr->streamPtr; - if (this->sessionOptions.httpRequestTimeoutMilliSeconds > 0) { - beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliSeconds)); + if (this->sessionOptions.httpRequestTimeoutMilliseconds > 0) { + beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(this->sessionOptions.httpRequestTimeoutMilliseconds)); } std::shared_ptr> reqPtr(new http::request(std::move(req))); CCAPI_LOGGER_TRACE("before async_write"); @@ -592,7 +678,7 @@ class Service : public std::enable_shared_from_this { if (ec) { CCAPI_LOGGER_TRACE("fail"); this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "write", {request.getCorrelationId()}, eventQueuePtr); - this->httpConnectionPool.purge(); + this->httpConnectionPool[request.getLocalIpAddress()][request.getBaseUrl()].clear(); auto now = UtilTime::now(); auto req = this->convertRequest(request, now); retry.numRetry += 1; @@ -609,32 +695,17 @@ class Service : public std::enable_shared_from_this { beast::bind_front_handler(&Service::onRead_2, shared_from_this(), httpConnectionPtr, request, reqPtr, retry, bufferPtr, resPtr, eventQueuePtr)); CCAPI_LOGGER_TRACE("after async_read"); } - void setHttpConnectionPoolPurgeTimer() { - TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(5000))); - timerPtr->async_wait([that = shared_from_this()](ErrorCode const& ec) { - auto now = UtilTime::now(); - if (ec) { - that->onError(Event::Type::SESSION_STATUS, Message::Type::GENERIC_ERROR, ec, "timer"); - } else { - if (std::chrono::duration_cast(now - that->lastHttpConnectionPoolPushBackTp).count() > - that->sessionOptions.httpConnectionPoolIdleTimeoutMilliSeconds) { - that->httpConnectionPool.purge(); - } - that->setHttpConnectionPoolPurgeTimer(); - } - }); - this->httpConnectionPoolPurgeTimer = timerPtr; - } void onRead_2(std::shared_ptr httpConnectionPtr, Request request, std::shared_ptr> reqPtr, HttpRetry retry, std::shared_ptr bufferPtr, std::shared_ptr> resPtr, Queue* eventQueuePtr, beast::error_code ec, std::size_t bytes_transferred) { CCAPI_LOGGER_TRACE("async_read callback start"); + CCAPI_LOGGER_TRACE("local endpoint has address " + beast::get_lowest_layer(*httpConnectionPtr->streamPtr).socket().local_endpoint().address().to_string()); auto now = UtilTime::now(); boost::ignore_unused(bytes_transferred); if (ec) { CCAPI_LOGGER_TRACE("fail"); this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "read", {request.getCorrelationId()}, eventQueuePtr); - this->httpConnectionPool.purge(); + this->httpConnectionPool[request.getLocalIpAddress()][request.getBaseUrl()].clear(); auto now = UtilTime::now(); auto req = this->convertRequest(request, now); retry.numRetry += 1; @@ -642,19 +713,17 @@ class Service : public std::enable_shared_from_this { return; } if (!this->sessionOptions.enableOneHttpConnectionPerRequest) { - try { - if (std::chrono::duration_cast(this->lastHttpConnectionPoolPushBackTp.time_since_epoch()).count() == 0 && - this->sessionOptions.httpConnectionPoolIdleTimeoutMilliSeconds > 0) { - this->setHttpConnectionPoolPurgeTimer(); - } - this->httpConnectionPool.pushBack(std::move(httpConnectionPtr)); - this->lastHttpConnectionPoolPushBackTp = now; - CCAPI_LOGGER_TRACE("pushed back httpConnectionPtr " + toString(*httpConnectionPtr) + " to pool"); - } catch (const std::runtime_error& e) { - if (e.what() != this->httpConnectionPool.EXCEPTION_QUEUE_FULL) { - CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); - } + httpConnectionPtr->lastReceiveDataTp = now; + const auto& localIpAddress = request.getLocalIpAddress(); + const auto& requestBaseUrl = request.getBaseUrl(); + if (this->sessionOptions.httpConnectionPoolMaxSize > 0 && + this->httpConnectionPool[localIpAddress][requestBaseUrl].size() >= this->sessionOptions.httpConnectionPoolMaxSize) { + CCAPI_LOGGER_TRACE("httpConnectionPool is full for localIpAddress = " + localIpAddress + ", requestBaseUrl = " + toString(requestBaseUrl)); + this->httpConnectionPool[localIpAddress][requestBaseUrl].pop_front(); } + this->httpConnectionPool[localIpAddress][requestBaseUrl].push_back(httpConnectionPtr); + CCAPI_LOGGER_TRACE("pushed back httpConnectionPtr " + toString(*httpConnectionPtr) + " to httpConnectionPool for localIpAddress = " + localIpAddress + + ", requestBaseUrl = " + toString(requestBaseUrl)); } #if defined(CCAPI_ENABLE_LOG_DEBUG) || defined(CCAPI_ENABLE_LOG_TRACE) { @@ -737,7 +806,13 @@ class Service : public std::enable_shared_from_this { CCAPI_LOGGER_TRACE("retry = " + toString(retry)); if (retry.numRetry <= this->sessionOptions.httpMaxNumRetry && retry.numRedirect <= this->sessionOptions.httpMaxNumRedirect) { try { - if (this->sessionOptions.enableOneHttpConnectionPerRequest || this->httpConnectionPool.empty()) { + const auto& localIpAddress = request.getLocalIpAddress(); + const auto& requestBaseUrl = request.getBaseUrl(); + if (this->sessionOptions.enableOneHttpConnectionPerRequest || this->httpConnectionPool[localIpAddress][requestBaseUrl].empty() || + std::chrono::duration_cast(request.getTimeSent() - + this->httpConnectionPool[localIpAddress][requestBaseUrl].back()->lastReceiveDataTp) + .count() >= this->sessionOptions.httpConnectionKeepAliveTimeoutSeconds) { + this->httpConnectionPool[localIpAddress][requestBaseUrl].clear(); std::shared_ptr> streamPtr(nullptr); try { streamPtr = this->createStream>(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr, @@ -747,32 +822,24 @@ class Service : public std::enable_shared_from_this { this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "create stream", {request.getCorrelationId()}, eventQueuePtr); return; } - std::shared_ptr httpConnectionPtr(new HttpConnection(this->hostRest, this->portRest, streamPtr)); - CCAPI_LOGGER_WARN("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr)); - this->performRequest(httpConnectionPtr, request, req, retry, eventQueuePtr); - } else { - std::shared_ptr httpConnectionPtr(nullptr); - try { - httpConnectionPtr = std::move(this->httpConnectionPool.popBack()); - CCAPI_LOGGER_TRACE("about to perform request with existing httpConnectionPtr " + toString(*httpConnectionPtr)); - this->startWrite_2(httpConnectionPtr, request, req, retry, eventQueuePtr); - } catch (const std::runtime_error& e) { - if (e.what() != this->httpConnectionPool.EXCEPTION_QUEUE_EMPTY) { - CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); - } - std::shared_ptr> streamPtr(nullptr); - try { - streamPtr = this->createStream>(this->serviceContextPtr->ioContextPtr, - this->serviceContextPtr->sslContextPtr, this->hostRest); - } catch (const beast::error_code& ec) { - CCAPI_LOGGER_TRACE("fail"); - this->onError(Event::Type::REQUEST_STATUS, Message::Type::REQUEST_FAILURE, ec, "create stream", {request.getCorrelationId()}, eventQueuePtr); - return; - } - httpConnectionPtr = std::make_shared(this->hostRest, this->portRest, streamPtr); - CCAPI_LOGGER_WARN("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr)); - this->performRequest(httpConnectionPtr, request, req, retry, eventQueuePtr); + std::string host, port; + if (requestBaseUrl.empty()) { + host = this->hostRest; + port = this->portRest; + } else { + host = request.getHost(); + port = request.getPort(); } + std::shared_ptr httpConnectionPtr(new HttpConnection(host, port, streamPtr)); + CCAPI_LOGGER_WARN("about to perform request with new httpConnectionPtr " + toString(*httpConnectionPtr) + " for localIpAddress = " + localIpAddress + + ", requestBaseUrl = " + toString(requestBaseUrl)); + this->performRequestWithNewHttpConnection(httpConnectionPtr, request, req, retry, eventQueuePtr); + } else { + std::shared_ptr httpConnectionPtr = this->httpConnectionPool[localIpAddress][requestBaseUrl].back(); + this->httpConnectionPool[localIpAddress][requestBaseUrl].pop_back(); + CCAPI_LOGGER_TRACE("about to perform request with existing httpConnectionPtr " + toString(*httpConnectionPtr) + + " for localIpAddress = " + localIpAddress + ", requestBaseUrl = " + toString(requestBaseUrl)); + this->startWrite_2(httpConnectionPtr, request, req, retry, eventQueuePtr); } } catch (const std::exception& e) { CCAPI_LOGGER_ERROR(std::string("e.what() = ") + e.what()); @@ -805,7 +872,7 @@ class Service : public std::enable_shared_from_this { } else { req.keep_alive(true); } - req.set(http::field::host, this->hostRest); + req.set(http::field::host, request.getBaseUrl().empty() ? this->hostRest : request.getHost()); req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); this->convertRequestForRest(req, request, now, symbolId, credential); CCAPI_LOGGER_FUNCTION_EXIT; @@ -821,14 +888,15 @@ class Service : public std::enable_shared_from_this { } } } - void appendParam(std::string& queryString, const std::map& param, - const std::map standardizationMap = {}) { + void appendParam(std::string& queryString, const std::map& param, const std::map standardizationMap = {}, + const std::map> conversionMap = {}) { int i = 0; for (const auto& kv : param) { std::string key = standardizationMap.find(kv.first) != standardizationMap.end() ? standardizationMap.at(kv.first) : kv.first; queryString += key; queryString += "="; - queryString += Url::urlEncode(kv.second); + std::string value = conversionMap.find(kv.first) != conversionMap.end() ? conversionMap.at(kv.first)(kv.second) : kv.second; + queryString += Url::urlEncode(value); queryString += "&"; ++i; } @@ -857,7 +925,7 @@ class Service : public std::enable_shared_from_this { std::string methodStringUpper = UtilString::toUpper(methodString); return http::string_to_verb(methodStringUpper); } -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP SslContextPtr onTlsInit(wspp::connection_hdl hdl) { return this->serviceContextPtr->sslContextPtr; } WsConnection& getWsConnectionFromConnectionPtr(TlsClient::connection_ptr connectionPtr) { return this->wsConnectionByIdMap.at(this->connectionAddressToString(connectionPtr)); @@ -954,7 +1022,7 @@ class Service : public std::enable_shared_from_this { if (this->connectRetryOnFailTimerByConnectionIdMap.find(thisWsConnection.id) != this->connectRetryOnFailTimerByConnectionIdMap.end()) { this->connectRetryOnFailTimerByConnectionIdMap.at(thisWsConnection.id)->cancel(); } - TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000))); + TimerPtr timerPtr(new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000))); timerPtr->async_wait([thisWsConnection, that = shared_from_this(), urlBase](ErrorCode const& ec) { if (that->wsConnectionByIdMap.find(thisWsConnection.id) == that->wsConnectionByIdMap.end()) { if (ec) { @@ -1120,11 +1188,11 @@ class Service : public std::enable_shared_from_this { std::function pingMethod) { CCAPI_LOGGER_FUNCTION_ENTER; CCAPI_LOGGER_TRACE("method = " + pingPongMethodToString(method)); - auto pingIntervalMilliSeconds = this->pingIntervalMilliSecondsByMethodMap[method]; - auto pongTimeoutMilliSeconds = this->pongTimeoutMilliSecondsByMethodMap[method]; - CCAPI_LOGGER_TRACE("pingIntervalMilliSeconds = " + toString(pingIntervalMilliSeconds)); - CCAPI_LOGGER_TRACE("pongTimeoutMilliSeconds = " + toString(pongTimeoutMilliSeconds)); - if (pingIntervalMilliSeconds <= pongTimeoutMilliSeconds) { + auto pingIntervalMilliseconds = this->pingIntervalMillisecondsByMethodMap[method]; + auto pongTimeoutMilliseconds = this->pongTimeoutMillisecondsByMethodMap[method]; + CCAPI_LOGGER_TRACE("pingIntervalMilliseconds = " + toString(pingIntervalMilliseconds)); + CCAPI_LOGGER_TRACE("pongTimeoutMilliseconds = " + toString(pongTimeoutMilliseconds)); + if (pingIntervalMilliseconds <= pongTimeoutMilliseconds) { return; } if (wsConnection.status == WsConnection::Status::OPEN) { @@ -1133,8 +1201,8 @@ class Service : public std::enable_shared_from_this { this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel(); } TimerPtr timerPtr( - new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliSeconds - pongTimeoutMilliSeconds))); - timerPtr->async_wait([wsConnection, that = shared_from_this(), hdl, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { + new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliseconds - pongTimeoutMilliseconds))); + timerPtr->async_wait([wsConnection, that = shared_from_this(), hdl, pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) { if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) { if (ec) { CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", ping timer error: " + ec.message()); @@ -1146,7 +1214,7 @@ class Service : public std::enable_shared_from_this { if (ec) { that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping"); } - if (pongTimeoutMilliSeconds <= 0) { + if (pongTimeoutMilliseconds <= 0) { return; } if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(wsConnection.id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() && @@ -1154,8 +1222,8 @@ class Service : public std::enable_shared_from_this { that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).end()) { that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel(); } - TimerPtr timerPtr(new boost::asio::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliSeconds))); - timerPtr->async_wait([wsConnection, that, hdl, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { + TimerPtr timerPtr(new net::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliseconds))); + timerPtr->async_wait([wsConnection, that, hdl, pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) { if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) { if (ec) { CCAPI_LOGGER_ERROR("wsConnection = " + toString(wsConnection) + ", pong time out timer error: " + ec.message()); @@ -1167,7 +1235,7 @@ class Service : public std::enable_shared_from_this { that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).find(method) != that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).end() && std::chrono::duration_cast(now - that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).at(method)) - .count() >= pongTimeoutMilliSeconds) { + .count() >= pongTimeoutMilliseconds) { auto thisWsConnection = wsConnection; ErrorCode ec; that->close(thisWsConnection, hdl, websocketpp::close::status::normal, "pong timeout", ec); @@ -1213,29 +1281,40 @@ class Service : public std::enable_shared_from_this { WsConnection& wsConnection = *wsConnectionPtr; wsConnection.status = WsConnection::Status::CONNECTING; CCAPI_LOGGER_DEBUG("connection initialization on id " + wsConnection.id); - std::string url = wsConnection.url; + std::string url = wsConnection.getUrl(); CCAPI_LOGGER_DEBUG("url = " + url); this->startResolveWs(wsConnectionPtr); CCAPI_LOGGER_FUNCTION_EXIT; } void startResolveWs(std::shared_ptr wsConnectionPtr) { std::shared_ptr newResolverPtr(new tcp::resolver(*this->serviceContextPtr->ioContextPtr)); + CCAPI_LOGGER_TRACE("wsConnectionPtr = " + wsConnectionPtr->toString()); + CCAPI_LOGGER_TRACE("wsConnectionPtr->host = " + wsConnectionPtr->host); + CCAPI_LOGGER_TRACE("wsConnectionPtr->port = " + wsConnectionPtr->port); newResolverPtr->async_resolve(wsConnectionPtr->host, wsConnectionPtr->port, beast::bind_front_handler(&Service::onResolveWs, shared_from_this(), wsConnectionPtr, newResolverPtr)); } void onResolveWs(std::shared_ptr wsConnectionPtr, std::shared_ptr newResolverPtr, beast::error_code ec, tcp::resolver::results_type tcpNewResolverResultsWs) { if (ec) { - CCAPI_LOGGER_TRACE("fail"); - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "dns resolve", wsConnectionPtr->correlationIdList); + CCAPI_LOGGER_TRACE("dns resolve fail"); + this->onFail(wsConnectionPtr); return; } - this->startConnectWs(wsConnectionPtr, this->sessionOptions.websocketConnectTimeoutMilliSeconds, tcpNewResolverResultsWs); + this->startConnectWs(wsConnectionPtr, this->sessionOptions.websocketConnectTimeoutMilliseconds, tcpNewResolverResultsWs); } - void startConnectWs(std::shared_ptr wsConnectionPtr, long timeoutMilliSeconds, tcp::resolver::results_type tcpResolverResults) { + void startConnectWs(std::shared_ptr wsConnectionPtr, long timeoutMilliseconds, tcp::resolver::results_type tcpResolverResults) { beast::websocket::stream>& stream = *wsConnectionPtr->streamPtr; - if (timeoutMilliSeconds > 0) { - beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(timeoutMilliSeconds)); + if (timeoutMilliseconds > 0) { + beast::get_lowest_layer(stream).expires_after(std::chrono::milliseconds(timeoutMilliseconds)); + } + // Set SNI Hostname (many hosts need this to handshake successfully) + CCAPI_LOGGER_TRACE("wsConnectionPtr->host = " + wsConnectionPtr->host) + if (!SSL_set_tlsext_host_name(stream.next_layer().native_handle(), wsConnectionPtr->host.c_str())) { + beast::error_code ec{static_cast(::ERR_get_error()), net::error::get_ssl_category()}; + CCAPI_LOGGER_DEBUG("error SSL_set_tlsext_host_name: " + ec.message()); + this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "set SNI Hostname", wsConnectionPtr->correlationIdList); + return; } CCAPI_LOGGER_TRACE("before async_connect"); beast::get_lowest_layer(stream).async_connect(tcpResolverResults, beast::bind_front_handler(&Service::onConnectWs, shared_from_this(), wsConnectionPtr)); @@ -1250,7 +1329,9 @@ class Service : public std::enable_shared_from_this { } CCAPI_LOGGER_TRACE("connected"); CCAPI_LOGGER_TRACE("ep.port() = " + std::to_string(ep.port())); - wsConnectionPtr->hostHttpHeaderValue = this->hostWs + ':' + std::to_string(ep.port()); + wsConnectionPtr->hostHttpHeaderValue = + this->hostHttpHeaderValueIgnorePort ? wsConnectionPtr->host : wsConnectionPtr->host + ':' + std::to_string(ep.port()); + CCAPI_LOGGER_TRACE("wsConnectionPtr->hostHttpHeaderValue = " + wsConnectionPtr->hostHttpHeaderValue); beast::websocket::stream>& stream = *wsConnectionPtr->streamPtr; beast::get_lowest_layer(stream).socket().set_option(tcp::no_delay(true)); CCAPI_LOGGER_TRACE("before ssl async_handshake"); @@ -1260,15 +1341,15 @@ class Service : public std::enable_shared_from_this { void onSslHandshakeWs(std::shared_ptr wsConnectionPtr, beast::error_code ec) { CCAPI_LOGGER_TRACE("ssl async_handshake callback start"); if (ec) { - CCAPI_LOGGER_TRACE("fail"); - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "ssl handshake", wsConnectionPtr->correlationIdList); + CCAPI_LOGGER_TRACE("ssl handshake fail"); + this->onFail(wsConnectionPtr); return; } CCAPI_LOGGER_TRACE("ssl handshaked"); beast::websocket::stream>& stream = *wsConnectionPtr->streamPtr; beast::get_lowest_layer(stream).expires_never(); - beast::websocket::stream_base::timeout opt{std::chrono::milliseconds(this->sessionOptions.websocketConnectTimeoutMilliSeconds), - std::chrono::milliseconds(this->sessionOptions.pongWebsocketProtocolLevelTimeoutMilliSeconds), true}; + beast::websocket::stream_base::timeout opt{std::chrono::milliseconds(this->sessionOptions.websocketConnectTimeoutMilliseconds), + std::chrono::milliseconds(this->sessionOptions.pongWebsocketProtocolLevelTimeoutMilliseconds), true}; stream.set_option(opt); stream.set_option(beast::websocket::stream_base::decorator([wsConnectionPtr](beast::websocket::request_type& req) { @@ -1285,8 +1366,8 @@ class Service : public std::enable_shared_from_this { void onWsHandshakeWs(std::shared_ptr wsConnectionPtr, beast::error_code ec) { CCAPI_LOGGER_TRACE("ws async_handshake callback start"); if (ec) { - CCAPI_LOGGER_TRACE("fail"); - this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, ec, "ws handshake", wsConnectionPtr->correlationIdList); + CCAPI_LOGGER_TRACE("ws handshake fail"); + this->onFail(wsConnectionPtr); return; } CCAPI_LOGGER_TRACE("ws handshaked"); @@ -1295,7 +1376,9 @@ class Service : public std::enable_shared_from_this { CCAPI_LOGGER_TRACE("about to start read"); this->startReadWs(wsConnectionPtr); auto& stream = *wsConnectionPtr->streamPtr; - stream.control_callback(beast::bind_front_handler(&Service::onControlCallback, shared_from_this(), wsConnectionPtr)); + stream.control_callback([wsConnectionPtr, that = shared_from_this()](boost::beast::websocket::frame_type kind, boost::beast::string_view payload) { + that->onControlCallback(wsConnectionPtr, kind, payload); + }); } void startReadWs(std::shared_ptr wsConnectionPtr) { auto& stream = *wsConnectionPtr->streamPtr; @@ -1305,7 +1388,7 @@ class Service : public std::enable_shared_from_this { stream.async_read(readMessageBuffer, beast::bind_front_handler(&Service::onReadWs, shared_from_this(), wsConnectionPtr)); CCAPI_LOGGER_TRACE("after async_read"); } - void onReadWs(std::shared_ptr wsConnectionPtr, const boost::system::error_code& ec, std::size_t n) { + void onReadWs(std::shared_ptr wsConnectionPtr, const ErrorCode& ec, std::size_t n) { CCAPI_LOGGER_FUNCTION_ENTER; CCAPI_LOGGER_TRACE("n = " + toString(n)); auto now = UtilTime::now(); @@ -1339,7 +1422,7 @@ class Service : public std::enable_shared_from_this { this->onMessage(wsConnectionPtr, (const char*)readMessageBuffer.data().data(), readMessageBuffer.size()); readMessageBuffer.consume(readMessageBuffer.size()); this->startReadWs(wsConnectionPtr); - this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now); + this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now, false); CCAPI_LOGGER_FUNCTION_EXIT; } virtual void onOpen(std::shared_ptr wsConnectionPtr) { @@ -1348,7 +1431,7 @@ class Service : public std::enable_shared_from_this { WsConnection& wsConnection = *wsConnectionPtr; wsConnection.status = WsConnection::Status::OPEN; CCAPI_LOGGER_INFO("connection " + toString(wsConnection) + " established"); - auto urlBase = UtilString::split(wsConnection.url, "?").at(0); + auto urlBase = UtilString::split(wsConnection.getUrl(), "?").at(0); this->connectNumRetryOnFailByConnectionUrlMap[urlBase] = 0; Event event; event.setType(Event::Type::SESSION_STATUS); @@ -1360,7 +1443,7 @@ class Service : public std::enable_shared_from_this { message.setCorrelationIdList(correlationIdList); Element element; element.insert(CCAPI_CONNECTION_ID, wsConnection.id); - element.insert(CCAPI_CONNECTION_URL, wsConnection.url); + element.insert(CCAPI_CONNECTION_URL, wsConnection.getUrl()); message.setElementList({element}); event.setMessageList({message}); this->eventHandler(event, nullptr); @@ -1386,6 +1469,7 @@ class Service : public std::enable_shared_from_this { memcpy(writeMessageBuffer.data() + n, data, dataSize); writeMessageBufferBoundary.push_back(dataSize); n += dataSize; + CCAPI_LOGGER_TRACE("connectionId = " + connectionId); CCAPI_LOGGER_DEBUG("about to send " + std::string(data, dataSize)); CCAPI_LOGGER_TRACE("writeMessageBufferWrittenLength = " + toString(writeMessageBufferWrittenLength)); if (writeMessageBufferWrittenLength == 0) { @@ -1401,10 +1485,10 @@ class Service : public std::enable_shared_from_this { CCAPI_LOGGER_TRACE("before async_write"); CCAPI_LOGGER_TRACE("numBytesToWrite = " + toString(numBytesToWrite)); stream.binary(false); - stream.async_write(boost::asio::buffer(data, numBytesToWrite), beast::bind_front_handler(&Service::onWriteWs, shared_from_this(), wsConnectionPtr)); + stream.async_write(net::buffer(data, numBytesToWrite), beast::bind_front_handler(&Service::onWriteWs, shared_from_this(), wsConnectionPtr)); CCAPI_LOGGER_TRACE("after async_write"); } - void onWriteWs(std::shared_ptr wsConnectionPtr, const boost::system::error_code& ec, std::size_t n) { + void onWriteWs(std::shared_ptr wsConnectionPtr, const ErrorCode& ec, std::size_t n) { CCAPI_LOGGER_FUNCTION_ENTER; auto& connectionId = wsConnectionPtr->id; auto& writeMessageBuffer = this->writeMessageBufferByConnectionIdMap[connectionId]; @@ -1427,13 +1511,13 @@ class Service : public std::enable_shared_from_this { this->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::SUBSCRIPTION_FAILURE, "connection " + toString(wsConnection) + " has failed before opening"); WsConnection thisWsConnection = wsConnection; this->wsConnectionByIdMap.erase(thisWsConnection.id); - auto urlBase = UtilString::split(thisWsConnection.url, "?").at(0); + auto urlBase = UtilString::split(thisWsConnection.getUrl(), "?").at(0); long seconds = std::round(UtilAlgorithm::exponentialBackoff(1, 1, 2, std::min(this->connectNumRetryOnFailByConnectionUrlMap[urlBase], 6))); CCAPI_LOGGER_INFO("about to set timer for " + toString(seconds) + " seconds"); if (this->connectRetryOnFailTimerByConnectionIdMap.find(thisWsConnection.id) != this->connectRetryOnFailTimerByConnectionIdMap.end()) { this->connectRetryOnFailTimerByConnectionIdMap.at(thisWsConnection.id)->cancel(); } - TimerPtr timerPtr(new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000))); + TimerPtr timerPtr(new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(seconds * 1000))); timerPtr->async_wait([wsConnectionPtr, that = shared_from_this(), urlBase](ErrorCode const& ec) { WsConnection& thisWsConnection = *wsConnectionPtr; if (that->wsConnectionByIdMap.find(thisWsConnection.id) == that->wsConnectionByIdMap.end()) { @@ -1460,8 +1544,7 @@ class Service : public std::enable_shared_from_this { std::shared_ptr thatWsConnectionPtr = wsConnectionPtr; std::shared_ptr>> streamPtr(nullptr); try { - streamPtr = this->createStream>>(this->serviceContextPtr->ioContextPtr, - this->serviceContextPtr->sslContextPtr, this->hostWs); + streamPtr = this->createWsStream(this->serviceContextPtr->ioContextPtr, this->serviceContextPtr->sslContextPtr); } catch (const beast::error_code& ec) { throw ec; } @@ -1520,7 +1603,7 @@ class Service : public std::enable_shared_from_this { message.setType(Message::Type::SESSION_CONNECTION_DOWN); Element element; element.insert(CCAPI_CONNECTION_ID, wsConnection.id); - element.insert(CCAPI_CONNECTION_URL, wsConnection.url); + element.insert(CCAPI_CONNECTION_URL, wsConnection.getUrl()); element.insert(CCAPI_REASON, reason); message.setElementList({element}); std::vector correlationIdList; @@ -1602,38 +1685,42 @@ class Service : public std::enable_shared_from_this { } void onPong(std::shared_ptr wsConnectionPtr, boost::beast::string_view payload) { auto now = UtilTime::now(); - this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now); + this->onPongByMethod(PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL, wsConnectionPtr, now, true); } - void onPongByMethod(PingPongMethod method, std::shared_ptr wsConnectionPtr, const TimePoint& timeReceived) { + void onPongByMethod(PingPongMethod method, std::shared_ptr wsConnectionPtr, const TimePoint& timeReceived, bool truePong) { CCAPI_LOGGER_FUNCTION_ENTER; - CCAPI_LOGGER_TRACE(pingPongMethodToString(method) + ": received a pong from " + toString(*wsConnectionPtr)); + CCAPI_LOGGER_TRACE(pingPongMethodToString(method) + ": received a " + (truePong ? "websocket protocol pong" : "data message") + " from " + + toString(*wsConnectionPtr)); this->lastPongTpByMethodByConnectionIdMap[wsConnectionPtr->id][method] = timeReceived; CCAPI_LOGGER_FUNCTION_EXIT; } void onPing(std::shared_ptr wsConnectionPtr, boost::beast::string_view payload) { CCAPI_LOGGER_FUNCTION_ENTER; + auto now = UtilTime::now(); CCAPI_LOGGER_TRACE("received a ping from " + toString(*wsConnectionPtr)); + this->lastPongTpByMethodByConnectionIdMap[wsConnectionPtr->id][PingPongMethod::WEBSOCKET_PROTOCOL_LEVEL] = now; CCAPI_LOGGER_FUNCTION_EXIT; } void send(std::shared_ptr wsConnectionPtr, boost::beast::string_view payload, ErrorCode& ec) { this->writeMessage(wsConnectionPtr, payload.data(), payload.length()); } void ping(std::shared_ptr wsConnectionPtr, boost::beast::string_view payload, ErrorCode& ec) { - if (!this->wsConnectionPendingPingingByIdMap[wsConnectionPtr->id]) { + if (!this->wsConnectionPendingPingingByConnectionIdMap[wsConnectionPtr->id]) { auto& stream = *wsConnectionPtr->streamPtr; - stream.async_ping("", [that = this, wsConnectionPtr](ErrorCode const& ec) { that->wsConnectionPendingPingingByIdMap[wsConnectionPtr->id] = false; }); - this->wsConnectionPendingPingingByIdMap[wsConnectionPtr->id] = true; + stream.async_ping( + "", [that = this, wsConnectionPtr](ErrorCode const& ec) { that->wsConnectionPendingPingingByConnectionIdMap[wsConnectionPtr->id] = false; }); + this->wsConnectionPendingPingingByConnectionIdMap[wsConnectionPtr->id] = true; } } virtual void pingOnApplicationLevel(std::shared_ptr wsConnectionPtr, ErrorCode& ec) {} void setPingPongTimer(PingPongMethod method, std::shared_ptr wsConnectionPtr, std::function pingMethod) { CCAPI_LOGGER_FUNCTION_ENTER; CCAPI_LOGGER_TRACE("method = " + pingPongMethodToString(method)); - auto pingIntervalMilliSeconds = this->pingIntervalMilliSecondsByMethodMap[method]; - auto pongTimeoutMilliSeconds = this->pongTimeoutMilliSecondsByMethodMap[method]; - CCAPI_LOGGER_TRACE("pingIntervalMilliSeconds = " + toString(pingIntervalMilliSeconds)); - CCAPI_LOGGER_TRACE("pongTimeoutMilliSeconds = " + toString(pongTimeoutMilliSeconds)); - if (pingIntervalMilliSeconds <= pongTimeoutMilliSeconds) { + auto pingIntervalMilliseconds = this->pingIntervalMillisecondsByMethodMap[method]; + auto pongTimeoutMilliseconds = this->pongTimeoutMillisecondsByMethodMap[method]; + CCAPI_LOGGER_TRACE("pingIntervalMilliseconds = " + toString(pingIntervalMilliseconds)); + CCAPI_LOGGER_TRACE("pongTimeoutMilliseconds = " + toString(pongTimeoutMilliseconds)); + if (pingIntervalMilliseconds <= pongTimeoutMilliseconds) { return; } WsConnection& wsConnection = *wsConnectionPtr; @@ -1643,8 +1730,8 @@ class Service : public std::enable_shared_from_this { this->pingTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel(); } TimerPtr timerPtr( - new boost::asio::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliSeconds - pongTimeoutMilliSeconds))); - timerPtr->async_wait([wsConnectionPtr, that = shared_from_this(), pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { + new net::steady_timer(*this->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pingIntervalMilliseconds - pongTimeoutMilliseconds))); + timerPtr->async_wait([wsConnectionPtr, that = shared_from_this(), pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) { WsConnection& wsConnection = *wsConnectionPtr; if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) { if (ec) { @@ -1657,7 +1744,7 @@ class Service : public std::enable_shared_from_this { if (ec) { that->onError(Event::Type::SUBSCRIPTION_STATUS, Message::Type::GENERIC_ERROR, ec, "ping"); } - if (pongTimeoutMilliSeconds <= 0) { + if (pongTimeoutMilliseconds <= 0) { return; } if (that->pongTimeOutTimerByMethodByConnectionIdMap.find(wsConnection.id) != that->pongTimeOutTimerByMethodByConnectionIdMap.end() && @@ -1665,8 +1752,8 @@ class Service : public std::enable_shared_from_this { that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).end()) { that->pongTimeOutTimerByMethodByConnectionIdMap.at(wsConnection.id).at(method)->cancel(); } - TimerPtr timerPtr(new boost::asio::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliSeconds))); - timerPtr->async_wait([wsConnectionPtr, that, pingMethod, pongTimeoutMilliSeconds, method](ErrorCode const& ec) { + TimerPtr timerPtr(new net::steady_timer(*that->serviceContextPtr->ioContextPtr, std::chrono::milliseconds(pongTimeoutMilliseconds))); + timerPtr->async_wait([wsConnectionPtr, that, pingMethod, pongTimeoutMilliseconds, method](ErrorCode const& ec) { WsConnection& wsConnection = *wsConnectionPtr; if (that->wsConnectionByIdMap.find(wsConnection.id) != that->wsConnectionByIdMap.end()) { if (ec) { @@ -1679,7 +1766,7 @@ class Service : public std::enable_shared_from_this { that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).find(method) != that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).end() && std::chrono::duration_cast(now - that->lastPongTpByMethodByConnectionIdMap.at(wsConnection.id).at(method)) - .count() >= pongTimeoutMilliSeconds) { + .count() >= pongTimeoutMilliseconds) { auto thisWsConnectionPtr = wsConnectionPtr; ErrorCode ec; that->close(thisWsConnectionPtr, beast::websocket::close_code::normal, @@ -1705,8 +1792,17 @@ class Service : public std::enable_shared_from_this { } CCAPI_LOGGER_FUNCTION_EXIT; } + std::string convertParamTimeSecondsToTimeMilliseconds(const std::string& input) { + auto dotPosition = input.find('.'); + if (dotPosition == std::string::npos) { + return std::to_string(std::stoll(input) * 1000); + } else { + } + return std::to_string(std::stoll(input.substr(0, dotPosition)) * 1000 + std::stoll(UtilString::rightPadTo(input.substr(dotPosition + 1, 3), 3, '0'))); + } virtual void onTextMessage(std::shared_ptr wsConnectionPtr, boost::beast::string_view textMessage, const TimePoint& timeReceived) {} #endif + bool hostHttpHeaderValueIgnorePort{}; std::string apiKeyName; std::string apiSecretName; std::string exchangeName; @@ -1721,13 +1817,11 @@ class Service : public std::enable_shared_from_this { std::string portRest; std::string hostWs; std::string portWs; - tcp::resolver::results_type tcpResolverResultsRest, tcpResolverResultsWs; - Queue> httpConnectionPool; - TimePoint lastHttpConnectionPoolPushBackTp{std::chrono::seconds{0}}; - TimerPtr httpConnectionPoolPurgeTimer; + // tcp::resolver::results_type tcpResolverResultsRest, tcpResolverResultsWs; + std::map>>> httpConnectionPool; std::map credentialDefault; std::map sendRequestDelayTimerByCorrelationIdMap; -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP std::map wsConnectionByIdMap; #else std::map> wsConnectionByIdMap; // TODO(cryptochassis): for consistency, to be renamed to wsConnectionPtrByIdMap @@ -1736,15 +1830,15 @@ class Service : public std::enable_shared_from_this { std::map writeMessageBufferWrittenLengthByConnectionIdMap; std::map> writeMessageBufferBoundaryByConnectionIdMap; #endif - std::map wsConnectionPendingPingingByIdMap; + std::map wsConnectionPendingPingingByConnectionIdMap; std::map shouldProcessRemainingMessageOnClosingByConnectionIdMap; std::map connectNumRetryOnFailByConnectionUrlMap; std::map connectRetryOnFailTimerByConnectionIdMap; std::map> lastPongTpByMethodByConnectionIdMap; std::map> pingTimerByMethodByConnectionIdMap; std::map> pongTimeOutTimerByMethodByConnectionIdMap; - std::map pingIntervalMilliSecondsByMethodMap; - std::map pongTimeoutMilliSecondsByMethodMap; + std::map pingIntervalMillisecondsByMethodMap; + std::map pongTimeoutMillisecondsByMethodMap; std::atomic shouldContinue{true}; std::map> extraPropertyByConnectionIdMap; bool enableCheckPingPongWebsocketProtocolLevel{}; @@ -1757,7 +1851,7 @@ class Service : public std::enable_shared_from_this { (defined(CCAPI_ENABLE_EXCHANGE_HUOBI) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP)) || \ defined(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT) && \ (defined(CCAPI_ENABLE_EXCHANGE_HUOBI_USDT_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_HUOBI_COIN_SWAP) || defined(CCAPI_ENABLE_EXCHANGE_BITMART)) -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP struct monostate {}; websocketpp::extensions_workaround::permessage_deflate::enabled inflater; #else diff --git a/linux/include/ccapi_cpp/service/ccapi_service_context.h b/linux/include/ccapi_cpp/service/ccapi_service_context.h index 60618c6f2..589e68882 100644 --- a/linux/include/ccapi_cpp/service/ccapi_service_context.h +++ b/linux/include/ccapi_cpp/service/ccapi_service_context.h @@ -1,6 +1,6 @@ #ifndef INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_ #define INCLUDE_CCAPI_CPP_SERVICE_CCAPI_SERVICE_CONTEXT_H_ -#ifndef CCAPI_USE_BOOST_BEAST_WEBSOCKET +#ifdef CCAPI_LEGACY_USE_WEBSOCKETPP #include "ccapi_cpp/ccapi_logger.h" #include "websocketpp/client.hpp" #include "websocketpp/common/connection_hdl.hpp" @@ -77,23 +77,46 @@ namespace ccapi { class ServiceContext CCAPI_FINAL { public: typedef boost::asio::io_context IoContext; - typedef std::shared_ptr IoContextPtr; + typedef boost::asio::io_context* IoContextPtr; typedef boost::asio::executor_work_guard ExecutorWorkGuard; - typedef std::shared_ptr ExecutorWorkGuardPtr; + typedef ExecutorWorkGuard* ExecutorWorkGuardPtr; typedef boost::asio::ssl::context SslContext; - typedef std::shared_ptr SslContextPtr; + typedef SslContext* SslContextPtr; ServiceContext() { + this->ioContextPtr = new boost::asio::io_context(); + this->executorWorkGuardPtr = new ExecutorWorkGuard(this->ioContextPtr->get_executor()); + this->sslContextPtr = new SslContext(SslContext::tls_client); // this->sslContextPtr->set_options(SslContext::default_workarounds | SslContext::no_sslv2 | SslContext::no_sslv3 | SslContext::single_dh_use); this->sslContextPtr->set_verify_mode(boost::asio::ssl::verify_none); // TODO(cryptochassis): verify ssl certificate to strengthen security // https://github.com/boostorg/asio/blob/develop/example/cpp03/ssl/client.cpp } +#ifndef SWIG + ServiceContext(IoContextPtr ioContextPtr) { + this->ioContextPtr = ioContextPtr; + this->executorWorkGuardPtr = new ExecutorWorkGuard(this->ioContextPtr->get_executor()); + this->sslContextPtr = new SslContext(SslContext::tls_client); + this->sslContextPtr->set_verify_mode(boost::asio::ssl::verify_none); + } + ServiceContext(SslContextPtr sslContextPtr) { + this->ioContextPtr = new boost::asio::io_context(); + this->executorWorkGuardPtr = new ExecutorWorkGuard(this->ioContextPtr->get_executor()); + this->sslContextPtr = sslContextPtr; + this->sslContextPtr->set_verify_mode(boost::asio::ssl::verify_none); + } + ServiceContext(IoContextPtr ioContextPtr, SslContextPtr sslContextPtr) { + this->ioContextPtr = ioContextPtr; + this->executorWorkGuardPtr = new ExecutorWorkGuard(this->ioContextPtr->get_executor()); + this->sslContextPtr = sslContextPtr; + this->sslContextPtr->set_verify_mode(boost::asio::ssl::verify_none); + } +#endif ServiceContext(const ServiceContext&) = delete; ServiceContext& operator=(const ServiceContext&) = delete; virtual ~ServiceContext() { - // delete this->ExecutorWorkGuardPtr; - // delete this->ioContextPtr; - // delete this->sslContextPtr; + delete this->executorWorkGuardPtr; + delete this->ioContextPtr; + delete this->sslContextPtr; } void start() { CCAPI_LOGGER_INFO("about to start client asio io_context run loop"); @@ -104,9 +127,12 @@ class ServiceContext CCAPI_FINAL { this->executorWorkGuardPtr->reset(); this->ioContextPtr->stop(); } - IoContextPtr ioContextPtr{new IoContext()}; - ExecutorWorkGuardPtr executorWorkGuardPtr{new ExecutorWorkGuard(ioContextPtr->get_executor())}; - SslContextPtr sslContextPtr{new SslContext(SslContext::tls_client)}; + IoContextPtr ioContextPtr{nullptr}; + ExecutorWorkGuardPtr executorWorkGuardPtr{nullptr}; + SslContextPtr sslContextPtr{nullptr}; + // IoContextPtr ioContextPtr{new IoContext()}; + // ExecutorWorkGuardPtr executorWorkGuardPtr{new ExecutorWorkGuard(ioContextPtr->get_executor())}; + // SslContextPtr sslContextPtr{new SslContext(SslContext::tls_client)}; }; } /* namespace ccapi */ diff --git a/src/ccapi/install_ccapi.sh b/src/ccapi/install_ccapi.sh index 9dbe0ae2c..c4ef7ce4e 100755 --- a/src/ccapi/install_ccapi.sh +++ b/src/ccapi/install_ccapi.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -ccapi_version="5.45.2" +ccapi_version="6.12.0" if [[ "$#" -gt 0 ]]; then ccapi_version="$1" fi