From 0ebf44b62caefd2f21f6fd0b8fa7445c1025bd43 Mon Sep 17 00:00:00 2001 From: Stephane Janel Date: Sat, 20 Jan 2024 20:11:57 +0100 Subject: [PATCH] Make some default trade options configurable in exchangeconfig file --- CONFIG.md | 30 ++++++---- src/api-objects/CMakeLists.txt | 8 +++ src/api-objects/include/ordersconstraints.hpp | 2 +- src/api-objects/include/tradeoptions.hpp | 26 ++++---- .../withdrawsordepositsconstraints.hpp | 7 ++- src/api-objects/src/ordersconstraints.cpp | 6 +- src/api-objects/src/tradeoptions.cpp | 34 +++++++---- .../src/withdrawsordepositsconstraints.cpp | 6 +- src/api-objects/test/tradeoptions_test.cpp | 12 ++++ src/api/common/include/exchangeprivateapi.hpp | 4 +- src/api/common/include/exchangepublicapi.hpp | 6 +- src/api/common/src/exchangeprivateapi.cpp | 31 ++++++---- src/api/common/src/exchangepublicapi.cpp | 10 ++-- .../common/test/exchangeprivateapi_test.cpp | 60 ++++++++++--------- .../common/test/exchangepublicapi_test.cpp | 14 ++--- src/api/common/test/fiatconverter_test.cpp | 2 +- .../exchanges/include/binanceprivateapi.hpp | 2 +- .../exchanges/include/binancepublicapi.hpp | 14 ++--- .../exchanges/include/bithumbpublicapi.hpp | 6 +- src/api/exchanges/include/huobiprivateapi.hpp | 2 +- src/api/exchanges/include/huobipublicapi.hpp | 10 ++-- src/api/exchanges/include/krakenpublicapi.hpp | 6 +- .../exchanges/include/kucoinprivateapi.hpp | 2 +- src/api/exchanges/include/kucoinpublicapi.hpp | 8 +-- src/api/exchanges/include/upbitprivateapi.hpp | 2 +- src/api/exchanges/include/upbitpublicapi.hpp | 8 +-- src/api/exchanges/src/binanceprivateapi.cpp | 20 +++---- src/api/exchanges/src/binancepublicapi.cpp | 55 ++++++++--------- src/api/exchanges/src/bithumbprivateapi.cpp | 25 ++++---- src/api/exchanges/src/bithumbpublicapi.cpp | 38 ++++++------ src/api/exchanges/src/huobiprivateapi.cpp | 14 ++--- src/api/exchanges/src/huobipublicapi.cpp | 33 +++++----- src/api/exchanges/src/krakenprivateapi.cpp | 16 ++--- src/api/exchanges/src/krakenpublicapi.cpp | 38 ++++++------ src/api/exchanges/src/kucoinprivateapi.cpp | 16 ++--- src/api/exchanges/src/kucoinpublicapi.cpp | 28 ++++----- src/api/exchanges/src/upbitprivateapi.cpp | 33 +++++----- src/api/exchanges/src/upbitpublicapi.cpp | 30 +++++----- src/api/interface/include/exchange.hpp | 10 ++-- src/api/interface/src/exchange.cpp | 12 ++-- src/api/interface/src/exchangepool.cpp | 8 +-- src/engine/include/coincenteroptions.hpp | 11 ++-- src/engine/include/coincenteroptionsdef.hpp | 54 +++++++++-------- src/engine/src/coincenteroptions.cpp | 19 +++++- src/engine/src/exchangesorchestrator.cpp | 12 ++-- src/engine/src/queryresultprinter.cpp | 2 +- src/engine/test/coincenteroptions_test.cpp | 10 +++- src/engine/test/exchangedata_test.hpp | 16 ++--- .../test/exchangesorchestrator_trade_test.cpp | 14 ++--- .../test/queryresultprinter_base_test.hpp | 4 +- .../test/queryresultprinter_private_test.cpp | 34 +++++------ src/http-request/include/curlhandle.hpp | 7 ++- src/http-request/include/curloptions.hpp | 1 - src/http-request/src/curlhandle.cpp | 20 +++++-- src/http-request/test/curlhandle_test.cpp | 24 +++++--- src/objects/CMakeLists.txt | 4 +- src/objects/include/coincenterinfo.hpp | 8 +-- .../{exchangeinfo.hpp => exchangeconfig.hpp} | 21 ++++--- ...hangeinfomap.hpp => exchangeconfigmap.hpp} | 10 ++-- ...nfoparser.hpp => exchangeconfigparser.hpp} | 0 src/objects/include/priceoptions.hpp | 12 +++- src/objects/include/priceoptionsdef.hpp | 5 ++ src/objects/include/tradeconfig.hpp | 31 ++++++++++ .../include/tradedefinitions.hpp | 7 ++- src/objects/src/coincenterinfo.cpp | 16 ++--- .../{exchangeinfo.cpp => exchangeconfig.cpp} | 25 ++++---- ...odefault.hpp => exchangeconfigdefault.hpp} | 14 ++++- ...hangeinfomap.cpp => exchangeconfigmap.cpp} | 40 ++++++++----- ...nfoparser.cpp => exchangeconfigparser.cpp} | 8 +-- src/objects/src/priceoptions.cpp | 49 +++------------ src/objects/src/priceoptionsdef.cpp | 45 ++++++++++++++ ...einfo_test.cpp => exchangeconfig_test.cpp} | 30 +++++----- src/tech/include/timedef.hpp | 2 + src/tech/src/durationstring.cpp | 22 ++++--- src/tech/test/durationstring_test.cpp | 3 + 75 files changed, 732 insertions(+), 542 deletions(-) create mode 100644 src/api-objects/test/tradeoptions_test.cpp rename src/objects/include/{exchangeinfo.hpp => exchangeconfig.hpp} (83%) rename src/objects/include/{exchangeinfomap.hpp => exchangeconfigmap.hpp} (53%) rename src/objects/include/{exchangeinfoparser.hpp => exchangeconfigparser.hpp} (100%) create mode 100644 src/objects/include/tradeconfig.hpp rename src/{api-objects => objects}/include/tradedefinitions.hpp (84%) rename src/objects/src/{exchangeinfo.cpp => exchangeconfig.cpp} (82%) rename src/objects/src/{exchangeinfodefault.hpp => exchangeconfigdefault.hpp} (92%) rename src/objects/src/{exchangeinfomap.cpp => exchangeconfigmap.cpp} (70%) rename src/objects/src/{exchangeinfoparser.cpp => exchangeconfigparser.cpp} (97%) create mode 100644 src/objects/src/priceoptionsdef.cpp rename src/objects/test/{exchangeinfo_test.cpp => exchangeconfig_test.cpp} (65%) diff --git a/CONFIG.md b/CONFIG.md index 4e341dd9..efba43e0 100644 --- a/CONFIG.md +++ b/CONFIG.md @@ -52,7 +52,7 @@ Configures the logging, tracking activity of relevant commands, and console outp | Name | Value | Description | | ---------------------------------------------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **apiOutputType** | String among {`off`, `table`, `json`} | Configure the default output type of coincenter (can be overridden by command line)queries | -| **fiatConversion.rate** | Duration string (ex: `8h`) | Minimum time between two consecutive requests of the same fiat conversion | +| **fiatConversion.rate** | Duration string (ex: `8h`) | Minimum duration between two consecutive requests of the same fiat conversion | | **log.activityTracking.commandTypes** | Array of strings (ex: `["Buy", "Sell"]`) | Array of command types whose output will be stored to activity history files. | | **log.activityTracking.dateFileNameFormat** | String (ex: `%Y-%m` for month split) | Defines the date string format suffix used by activity history files. The string should be compatible with [std::strftime](https://en.cppreference.com/w/cpp/chrono/c/strftime). Old data will never be clean-up by `coincenter` (as it may contain important data). User should manage the clean-up / storage. | | **log.consoleLevel** | String | Defines the log level for standard output. Can be {'off', 'critical', 'error', 'warning', 'info', 'debug', 'trace'} | @@ -134,17 +134,21 @@ Refer to the hardcoded default json example as a model in case of doubt. | *query* | **logLevels.requestsCall** | String log level for requests call ("off", "critical", "warning", "info", etc) | Specifies the log level for this exchange requests call. It prints the full public URL and the HTTP request type (GET, POST, etc) | | *query* | **logLevels.requestsAnswer** | String log level for requests call ("off", "critical", "warning", "info", etc) | Specifies the log level for this exchange requests replies. It prints the full answer if it is in *json* type, otherwise it will be truncated to a maximum of around 10 Ki to avoid logging too much data. | | *query* | **dustSweeperMaxNbTrades** | Positive integer | Maximum number of trades performed by the automatic dust sweeper process. A high value may have a higher chance of successfully sell to 0 the wanted currency, at the cost of more trades (and fees) paid to the exchange. | -| *query* | **privateAPIRate** | Duration string (ex: `500ms`) | Minimum time between two consecutive requests of private account | -| *query* | **publicAPIRate** | Duration string (ex: `250ms`) | Minimum time between two consecutive requests of public account | -| *query* | **updateFrequency.currencies** | Duration string (ex: `4h`) | Minimum time between two consecutive requests of currencies | -| *query* | **updateFrequency.markets** | Duration string (ex: `4h`) | Minimum time between two consecutive requests of markets | -| *query* | **updateFrequency.withdrawalFees** | Duration string (ex: `12h`) | Minimum time between two consecutive requests of withdrawal fees | -| *query* | **updateFrequency.allOrderbooks** | Duration string (ex: `2s`) | Minimum time between two consecutive requests of all order books (or ticker) | -| *query* | **updateFrequency.orderbook** | Duration string (ex: `1s`) | Minimum time between two consecutive requests of a single orderbook | -| *query* | **updateFrequency.tradedVolume** | Duration string (ex: `4h`) | Minimum time between two consecutive requests of last traded volume | -| *query* | **updateFrequency.lastPrice** | Duration string (ex: `1s500ms`) | Minimum time between two consecutive requests of price | -| *query* | **updateFrequency.depositWallet** | Duration string (ex: `1min`) | Minimum time between two consecutive requests of deposit information (including wallet) | -| *query* | **updateFrequency.currencyInfo** | Duration string (ex: `4h`) | Minimum time between two consecutive requests of dynamic currency info retrieval on Bithumb only (used for place order) | +| *query* | **privateAPIRate** | Duration string (ex: `500ms`) | Minimum duration between two consecutive requests of private account | +| *query* | **publicAPIRate** | Duration string (ex: `250ms`) | Minimum duration between two consecutive requests of public account | +| *query* | **trade.minPriceUpdateDuration** | Duration string (ex: `30s`) | Minimum duration between two consecutive price changes during trade | +| *query* | **trade.strategy** | <`maker`, `nibble`, `taker`> | Trade strategy for the exchange. It will be the default for the exchange if not manually specified. | +| *query* | **trade.timeout** | Duration string (ex: `1m`) | Trade timeout duration for a single trade. It will be the default for the exchange if not manually specified. | +| *query* | **trade.timeoutMatch** | Boolean (`true` or `false`) | If `false`, the remaining unmatched order is cancelled for the trade when it reaches timeout duration specified above. If `true`, trade will be placed as a taker order when the timeout is reached. | +| *query* | **updateFrequency.currencies** | Duration string (ex: `4h`) | Minimum duration between two consecutive requests of currencies | +| *query* | **updateFrequency.markets** | Duration string (ex: `4h`) | Minimum duration between two consecutive requests of markets | +| *query* | **updateFrequency.withdrawalFees** | Duration string (ex: `12h`) | Minimum duration between two consecutive requests of withdrawal fees | +| *query* | **updateFrequency.allOrderbooks** | Duration string (ex: `2s`) | Minimum duration between two consecutive requests of all order books (or ticker) | +| *query* | **updateFrequency.orderbook** | Duration string (ex: `1s`) | Minimum duration between two consecutive requests of a single orderbook | +| *query* | **updateFrequency.tradedVolume** | Duration string (ex: `4h`) | Minimum duration between two consecutive requests of last traded volume | +| *query* | **updateFrequency.lastPrice** | Duration string (ex: `1s500ms`) | Minimum duration between two consecutive requests of price | +| *query* | **updateFrequency.depositWallet** | Duration string (ex: `1min`) | Minimum duration between two consecutive requests of deposit information (including wallet) | +| *query* | **updateFrequency.currencyInfo** | Duration string (ex: `4h`) | Minimum duration between two consecutive requests of dynamic currency info retrieval on Bithumb only (used for place order) | | *query* | **placeSimulateRealOrder** | Boolean (`true` or `false`) | If `true`, in trade simulation mode (with `--sim`) exchanges which do not support simulated mode in place order will actually place a real order, with the following characteristics: This will allow place of a 'real' order that cannot be matched in practice (if it is, lucky you!) | | *query* | **multiTradeAllowedByDefault** | Boolean (`true` or `false`) | If `true`, [multi-trade](README.md#multi-trade) will be allowed by default for `trade`, `buy` and `sell`. It can be overridden at command line level with `--no-multi-trade` and `--multi-trade`. | | *query* | **validateApiKey** | Boolean (`true` or `false`) | If `true`, each loaded private key will be tested at start of the program. In case of a failure, it will be removed from the list of private accounts loaded by `coincenter`, so that later queries do not consider it instead of raising a runtime exception. The downside is that it will make an additional check that will make startup slower. | | @@ -154,7 +158,7 @@ Refer to the hardcoded default json example as a model in case of doubt. #### Notes - `updateFrequency` is itself a json document containing all duration values as query frequencies. - See [ExchangeInfo default file](src/objects/src/exchangeinfodefault.hpp) as an example for the syntax. + See [ExchangeConfig default file](src/objects/src/exchangeconfigdefault.hpp) as an example for the syntax. - Unused and not explicitly set values (so, when loaded from default values) from your personal `exchangeconfig.json` file will be logged for information about what will actually be used by `coincenter`. diff --git a/src/api-objects/CMakeLists.txt b/src/api-objects/CMakeLists.txt index 3939ea65..3b63a4df 100644 --- a/src/api-objects/CMakeLists.txt +++ b/src/api-objects/CMakeLists.txt @@ -46,6 +46,14 @@ add_unit_test( coincenter_objects ) +add_unit_test( + tradeoptions_test + src/tradeoptions.cpp + test/tradeoptions_test.cpp + LIBRARIES + coincenter_objects +) + add_unit_test( withdraw_test test/withdraw_test.cpp diff --git a/src/api-objects/include/ordersconstraints.hpp b/src/api-objects/include/ordersconstraints.hpp index 4109db31..666d1a2f 100644 --- a/src/api-objects/include/ordersconstraints.hpp +++ b/src/api-objects/include/ordersconstraints.hpp @@ -52,7 +52,7 @@ class OrdersConstraints { /// Build OrdersConstraints based on given filtering information explicit OrdersConstraints(CurrencyCode cur1 = CurrencyCode(), CurrencyCode cur2 = CurrencyCode(), - Duration minAge = Duration(), Duration maxAge = Duration(), + Duration minAge = kUndefinedDuration, Duration maxAge = kUndefinedDuration, OrderIdSet &&ordersIdSet = OrderIdSet()); TimePoint placedBefore() const { return _placedBefore; } diff --git a/src/api-objects/include/tradeoptions.hpp b/src/api-objects/include/tradeoptions.hpp index 6dc7e4b6..cbc1aaf5 100644 --- a/src/api-objects/include/tradeoptions.hpp +++ b/src/api-objects/include/tradeoptions.hpp @@ -9,27 +9,27 @@ #include "tradedefinitions.hpp" namespace cct { +class ExchangeConfig; class TradeOptions { public: - static constexpr Duration kDefaultTradeDuration = std::chrono::seconds(30); static constexpr Duration kDefaultMinTimeBetweenPriceUpdates = std::chrono::seconds(5); constexpr TradeOptions() noexcept = default; constexpr explicit TradeOptions(const PriceOptions &priceOptions) : _priceOptions(priceOptions) {} - constexpr explicit TradeOptions(TradeMode tradeMode) : _mode(tradeMode) {} - - TradeOptions(TradeTimeoutAction timeoutAction, TradeMode tradeMode, Duration dur, Duration minTimeBetweenPriceUpdates, - TradeTypePolicy tradeTypePolicy, TradeSyncPolicy tradeSyncPolicy = TradeSyncPolicy::kSynchronous); + constexpr explicit TradeOptions(TradeMode tradeMode) : _tradeMode(tradeMode) {} /// Constructs a TradeOptions based on a continuously updated price from given string representation of trade /// strategy TradeOptions(const PriceOptions &priceOptions, TradeTimeoutAction timeoutAction, TradeMode tradeMode, Duration dur, - Duration minTimeBetweenPriceUpdates = kDefaultMinTimeBetweenPriceUpdates, + Duration minTimeBetweenPriceUpdates = kUndefinedDuration, TradeTypePolicy tradeTypePolicy = TradeTypePolicy::kDefault, TradeSyncPolicy tradeSyncPolicy = TradeSyncPolicy::kSynchronous); + /// Constructs a new TradeOptions based on 'rhs' with unspecified options overriden from exchange config values + TradeOptions(const TradeOptions &rhs, const ExchangeConfig &exchangeConfig); + constexpr Duration maxTradeTime() const { return _maxTradeTime; } constexpr Duration minTimeBetweenPriceUpdates() const { return _minTimeBetweenPriceUpdates; } @@ -42,7 +42,7 @@ class TradeOptions { constexpr int relativePrice() const { return _priceOptions.relativePrice(); } - constexpr TradeMode tradeMode() const { return _mode; } + constexpr TradeMode tradeMode() const { return _tradeMode; } constexpr TradeSyncPolicy tradeSyncPolicy() const { return _tradeSyncPolicy; } @@ -52,13 +52,13 @@ class TradeOptions { return _priceOptions.isTakerStrategy() && (!isSimulation() || !placeRealOrderInSimulationMode); } - constexpr bool isSimulation() const { return _mode == TradeMode::kSimulation; } + constexpr bool isSimulation() const { return _tradeMode == TradeMode::kSimulation; } constexpr bool isFixedPrice() const { return _priceOptions.isFixedPrice(); } constexpr bool isRelativePrice() const { return _priceOptions.isRelativePrice(); } - constexpr bool placeMarketOrderAtTimeout() const { return _timeoutAction == TradeTimeoutAction::kForceMatch; } + constexpr bool placeMarketOrderAtTimeout() const { return _timeoutAction == TradeTimeoutAction::kMatch; } constexpr void switchToTakerStrategy() { _priceOptions.switchToTakerStrategy(); } @@ -71,11 +71,11 @@ class TradeOptions { bool operator==(const TradeOptions &) const noexcept = default; private: - Duration _maxTradeTime = kDefaultTradeDuration; - Duration _minTimeBetweenPriceUpdates = kDefaultMinTimeBetweenPriceUpdates; + Duration _maxTradeTime = kUndefinedDuration; + Duration _minTimeBetweenPriceUpdates = kUndefinedDuration; PriceOptions _priceOptions; - TradeTimeoutAction _timeoutAction = TradeTimeoutAction::kCancel; - TradeMode _mode = TradeMode::kReal; + TradeTimeoutAction _timeoutAction = TradeTimeoutAction::kDefault; + TradeMode _tradeMode = TradeMode::kReal; TradeTypePolicy _tradeTypePolicy = TradeTypePolicy::kDefault; TradeSyncPolicy _tradeSyncPolicy = TradeSyncPolicy::kSynchronous; }; diff --git a/src/api-objects/include/withdrawsordepositsconstraints.hpp b/src/api-objects/include/withdrawsordepositsconstraints.hpp index 032fce52..46602211 100644 --- a/src/api-objects/include/withdrawsordepositsconstraints.hpp +++ b/src/api-objects/include/withdrawsordepositsconstraints.hpp @@ -14,8 +14,9 @@ class WithdrawsOrDepositsConstraints { public: using IdSet = FlatSet>; - explicit WithdrawsOrDepositsConstraints(CurrencyCode currencyCode = CurrencyCode(), Duration minAge = Duration(), - Duration maxAge = Duration(), IdSet &&idSet = IdSet()); + explicit WithdrawsOrDepositsConstraints(CurrencyCode currencyCode = CurrencyCode(), + Duration minAge = kUndefinedDuration, Duration maxAge = kUndefinedDuration, + IdSet &&idSet = IdSet()); // Creates a WithdrawsOrDepositsConstraints based on a single transaction id and currency code. // Useful for retrieval of a specific Deposit / Withdraw. @@ -33,7 +34,7 @@ class WithdrawsOrDepositsConstraints { bool validateCur(CurrencyCode cur) const { return _currencyCode.isNeutral() || cur == _currencyCode; } - bool validateTime(TimePoint t) const { return t >= _timeAfter && t <= _timeBefore; } + bool validateTime(TimePoint tp) const { return tp >= _timeAfter && tp <= _timeBefore; } bool validateId(std::string_view id) const { return !isIdDefined() || _idSet.contains(id); } diff --git a/src/api-objects/src/ordersconstraints.cpp b/src/api-objects/src/ordersconstraints.cpp index ff6745d4..e238d771 100644 --- a/src/api-objects/src/ordersconstraints.cpp +++ b/src/api-objects/src/ordersconstraints.cpp @@ -17,12 +17,12 @@ OrdersConstraints::OrdersConstraints(CurrencyCode cur1, CurrencyCode cur2, Durat if (!_ordersIdSet.empty()) { _orderConstraintsBitmap.set(OrderConstraintsBitmap::ConstraintType::kId); } - auto now = Clock::now(); - if (minAge != Duration()) { + const auto now = Clock::now(); + if (minAge != kUndefinedDuration) { _placedBefore = now - minAge; _orderConstraintsBitmap.set(OrderConstraintsBitmap::ConstraintType::kPlacedBefore); } - if (maxAge != Duration()) { + if (maxAge != kUndefinedDuration) { _placedAfter = now - maxAge; _orderConstraintsBitmap.set(OrderConstraintsBitmap::ConstraintType::kPlacedAfter); } diff --git a/src/api-objects/src/tradeoptions.cpp b/src/api-objects/src/tradeoptions.cpp index 3bb626d4..be4ebb3a 100644 --- a/src/api-objects/src/tradeoptions.cpp +++ b/src/api-objects/src/tradeoptions.cpp @@ -4,6 +4,7 @@ #include "cct_string.hpp" #include "durationstring.hpp" +#include "exchangeconfig.hpp" #include "priceoptions.hpp" #include "timedef.hpp" #include "tradedefinitions.hpp" @@ -11,16 +12,6 @@ namespace cct { -TradeOptions::TradeOptions(TradeTimeoutAction timeoutAction, TradeMode tradeMode, Duration dur, - Duration minTimeBetweenPriceUpdates, TradeTypePolicy tradeTypePolicy, - TradeSyncPolicy tradeSyncPolicy) - : _maxTradeTime(dur), - _minTimeBetweenPriceUpdates(minTimeBetweenPriceUpdates), - _timeoutAction(timeoutAction), - _mode(tradeMode), - _tradeTypePolicy(tradeTypePolicy), - _tradeSyncPolicy(tradeSyncPolicy) {} - TradeOptions::TradeOptions(const PriceOptions &priceOptions, TradeTimeoutAction timeoutAction, TradeMode tradeMode, Duration dur, Duration minTimeBetweenPriceUpdates, TradeTypePolicy tradeTypePolicy, TradeSyncPolicy tradeSyncPolicy) @@ -28,10 +19,24 @@ TradeOptions::TradeOptions(const PriceOptions &priceOptions, TradeTimeoutAction _minTimeBetweenPriceUpdates(minTimeBetweenPriceUpdates), _priceOptions(priceOptions), _timeoutAction(timeoutAction), - _mode(tradeMode), + _tradeMode(tradeMode), _tradeTypePolicy(tradeTypePolicy), _tradeSyncPolicy(tradeSyncPolicy) {} +TradeOptions::TradeOptions(const TradeOptions &rhs, const ExchangeConfig &exchangeConfig) + : _maxTradeTime(rhs._maxTradeTime == kUndefinedDuration ? exchangeConfig.tradeConfig().timeout() + : rhs._maxTradeTime), + _minTimeBetweenPriceUpdates(rhs._minTimeBetweenPriceUpdates == kUndefinedDuration + ? exchangeConfig.tradeConfig().minPriceUpdateDuration() + : rhs._minTimeBetweenPriceUpdates), + _priceOptions(rhs._priceOptions.isDefault() ? PriceOptions(exchangeConfig.tradeConfig()) : rhs._priceOptions), + _timeoutAction(rhs._timeoutAction == TradeTimeoutAction::kDefault + ? exchangeConfig.tradeConfig().tradeTimeoutAction() + : rhs._timeoutAction), + _tradeMode(rhs._tradeMode), + _tradeTypePolicy(rhs._tradeTypePolicy), + _tradeSyncPolicy(rhs._tradeSyncPolicy) {} + bool TradeOptions::isMultiTradeAllowed(bool multiTradeAllowedByDefault) const { switch (_tradeTypePolicy) { case TradeTypePolicy::kDefault: @@ -47,10 +52,13 @@ bool TradeOptions::isMultiTradeAllowed(bool multiTradeAllowedByDefault) const { std::string_view TradeOptions::timeoutActionStr() const { switch (_timeoutAction) { + case TradeTimeoutAction::kDefault: + // Default will behave the same as cancel - this field is not publicly exposed + [[fallthrough]]; case TradeTimeoutAction::kCancel: return "cancel"; - case TradeTimeoutAction::kForceMatch: - return "force-match"; + case TradeTimeoutAction::kMatch: + return "match"; default: unreachable(); } diff --git a/src/api-objects/src/withdrawsordepositsconstraints.cpp b/src/api-objects/src/withdrawsordepositsconstraints.cpp index 0ce0dd1d..78b42493 100644 --- a/src/api-objects/src/withdrawsordepositsconstraints.cpp +++ b/src/api-objects/src/withdrawsordepositsconstraints.cpp @@ -14,12 +14,12 @@ WithdrawsOrDepositsConstraints::WithdrawsOrDepositsConstraints(CurrencyCode curr if (!_idSet.empty()) { _currencyIdTimeConstraintsBmp.set(CurrencyIdTimeConstraintsBmp::ConstraintType::kId); } - auto now = Clock::now(); - if (minAge != Duration()) { + const auto now = Clock::now(); + if (minAge != kUndefinedDuration) { _timeBefore = now - minAge; _currencyIdTimeConstraintsBmp.set(CurrencyIdTimeConstraintsBmp::ConstraintType::kReceivedBefore); } - if (maxAge != Duration()) { + if (maxAge != kUndefinedDuration) { _timeAfter = now - maxAge; _currencyIdTimeConstraintsBmp.set(CurrencyIdTimeConstraintsBmp::ConstraintType::kReceivedAfter); } diff --git a/src/api-objects/test/tradeoptions_test.cpp b/src/api-objects/test/tradeoptions_test.cpp new file mode 100644 index 00000000..778899e4 --- /dev/null +++ b/src/api-objects/test/tradeoptions_test.cpp @@ -0,0 +1,12 @@ +#include "tradeoptions.hpp" + +#include + +namespace cct { +TEST(TradeOptionsTest, DefaultTradeTimeoutAction) { + TradeOptions tradeOptions; + + EXPECT_FALSE(tradeOptions.placeMarketOrderAtTimeout()); + EXPECT_EQ(tradeOptions.timeoutActionStr(), "cancel"); +} +} // namespace cct \ No newline at end of file diff --git a/src/api/common/include/exchangeprivateapi.hpp b/src/api/common/include/exchangeprivateapi.hpp index d6329f93..b465c7f0 100644 --- a/src/api/common/include/exchangeprivateapi.hpp +++ b/src/api/common/include/exchangeprivateapi.hpp @@ -11,7 +11,7 @@ #include "currencyexchangeflatset.hpp" #include "depositsconstraints.hpp" #include "exchangebase.hpp" -#include "exchangeinfo.hpp" +#include "exchangeconfig.hpp" #include "exchangeprivateapitypes.hpp" #include "exchangepublicapi.hpp" #include "exchangepublicapitypes.hpp" @@ -118,7 +118,7 @@ class ExchangePrivate : public ExchangeBase { /// Builds an ExchangeName wrapping the exchange and the key name ExchangeName exchangeName() const { return {_exchangePublic.name(), _apiKey.name()}; } - const ExchangeInfo &exchangeInfo() const { return _exchangePublic.exchangeInfo(); } + const ExchangeConfig &exchangeConfig() const { return _exchangePublic.exchangeConfig(); } protected: ExchangePrivate(const CoincenterInfo &coincenterInfo, ExchangePublic &exchangePublic, const APIKey &apiKey); diff --git a/src/api/common/include/exchangepublicapi.hpp b/src/api/common/include/exchangepublicapi.hpp index 7a1a393c..c72cb8c2 100644 --- a/src/api/common/include/exchangepublicapi.hpp +++ b/src/api/common/include/exchangepublicapi.hpp @@ -19,7 +19,7 @@ namespace cct { class CoincenterInfo; -class ExchangeInfo; +class ExchangeConfig; class FiatConverter; namespace api { @@ -161,7 +161,7 @@ class ExchangePublic : public ExchangeBase { const CoincenterInfo &coincenterInfo() const { return _coincenterInfo; } - const ExchangeInfo &exchangeInfo() const { return _exchangeInfo; } + const ExchangeConfig &exchangeConfig() const { return _exchangeConfig; } CommonAPI &commonAPI() { return _commonApi; } @@ -180,7 +180,7 @@ class ExchangePublic : public ExchangeBase { FiatConverter &_fiatConverter; CommonAPI &_commonApi; const CoincenterInfo &_coincenterInfo; - const ExchangeInfo &_exchangeInfo; + const ExchangeConfig &_exchangeConfig; std::mutex _tradableMarketsMutex; std::mutex _allOrderBooksMutex; }; diff --git a/src/api/common/src/exchangeprivateapi.cpp b/src/api/common/src/exchangeprivateapi.cpp index d0e8e801..8619db4f 100644 --- a/src/api/common/src/exchangeprivateapi.cpp +++ b/src/api/common/src/exchangeprivateapi.cpp @@ -23,7 +23,7 @@ #include "depositsconstraints.hpp" #include "durationstring.hpp" #include "exchangebase.hpp" -#include "exchangeinfo.hpp" +#include "exchangeconfig.hpp" #include "exchangename.hpp" #include "exchangeprivateapitypes.hpp" #include "exchangepublicapi.hpp" @@ -40,6 +40,7 @@ #include "tradedamounts.hpp" #include "tradedefinitions.hpp" #include "tradeinfo.hpp" +#include "tradeoptions.hpp" #include "tradeside.hpp" #include "unreachable.hpp" #include "withdraw.hpp" @@ -85,14 +86,17 @@ void ExchangePrivate::addBalance(BalancePortfolio &balancePortfolio, MonetaryAmo TradedAmounts ExchangePrivate::trade(MonetaryAmount from, CurrencyCode toCurrency, const TradeOptions &options, const MarketsPath &conversionPath) { - const bool realOrderPlacedInSimulationMode = !isSimulatedOrderSupported() && exchangeInfo().placeSimulateRealOrder(); + // Use exchange config settings for un-overriden trade options + const auto &exchangeConfig = this->exchangeConfig(); + const TradeOptions actualOptions(options, exchangeConfig); + const bool realOrderPlacedInSimulationMode = !isSimulatedOrderSupported() && exchangeConfig.placeSimulateRealOrder(); const int nbTrades = static_cast(conversionPath.size()); - const bool isMultiTradeAllowed = options.isMultiTradeAllowed(exchangeInfo().multiTradeAllowedByDefault()); + const bool isMultiTradeAllowed = actualOptions.isMultiTradeAllowed(exchangeConfig.multiTradeAllowedByDefault()); ExchangeName exchangeName = this->exchangeName(); log::info("{}rade {} -> {} on {} requested", isMultiTradeAllowed && nbTrades > 1 ? "Multi t" : "T", from, toCurrency, exchangeName); - log::debug(options.str(realOrderPlacedInSimulationMode)); + log::debug(actualOptions.str(realOrderPlacedInSimulationMode)); TradedAmounts tradedAmounts(from.currencyCode(), toCurrency); if (conversionPath.empty()) { @@ -108,7 +112,7 @@ TradedAmounts ExchangePrivate::trade(MonetaryAmount from, CurrencyCode toCurrenc for (int tradePos = 0; tradePos < nbTrades; ++tradePos) { Market mk = conversionPath[tradePos]; log::info("Step {}/{} - trade {} into {}", tradePos + 1, nbTrades, avAmount, mk.opposite(avAmount.currencyCode())); - TradedAmounts stepTradedAmounts = marketTrade(avAmount, options, mk); + TradedAmounts stepTradedAmounts = marketTrade(avAmount, actualOptions, mk); avAmount = stepTradedAmounts.to; if (avAmount == 0) { break; @@ -135,7 +139,7 @@ TradedAmounts ExchangePrivate::marketTrade(MonetaryAmount from, const TradeOptio TradeContext tradeContext(mk, side, userRef); TradeInfo tradeInfo(tradeContext, tradeOptions); TradeOptions &options = tradeInfo.options; - const bool placeSimulatedRealOrder = exchangeInfo().placeSimulateRealOrder(); + const bool placeSimulatedRealOrder = exchangeConfig().placeSimulateRealOrder(); enum class NextAction : int8_t { kPlaceInitialOrder, kPlaceLimitOrder, kPlaceMarketOrder, kWait }; @@ -447,8 +451,9 @@ TradedAmounts ExchangePrivate::buySomeAmountToMakeFutureSellPossible( } TradedAmountsVectorWithFinalAmount ExchangePrivate::queryDustSweeper(CurrencyCode currencyCode) { - const MonetaryAmountByCurrencySet &dustThresholds = exchangeInfo().dustAmountsThreshold(); - const int dustSweeperMaxNbTrades = exchangeInfo().dustSweeperMaxNbTrades(); + const auto &exchangeConfig = this->exchangeConfig(); + const MonetaryAmountByCurrencySet &dustThresholds = exchangeConfig.dustAmountsThreshold(); + const int dustSweeperMaxNbTrades = exchangeConfig.dustSweeperMaxNbTrades(); const auto dustThresholdLb = dustThresholds.find(MonetaryAmount(0, currencyCode)); const auto eName = exchangeName(); @@ -460,7 +465,7 @@ TradedAmountsVectorWithFinalAmount ExchangePrivate::queryDustSweeper(CurrencyCod const MonetaryAmount dustThreshold = *dustThresholdLb; PriceOptions priceOptions(PriceStrategy::kTaker); - TradeOptions tradeOptions(priceOptions); + TradeOptions tradeOptions(TradeOptions{priceOptions}, exchangeConfig); MarketSet markets = _exchangePublic.queryTradableMarkets(); MarketPriceMap marketPriceMap; bool checkAmountBalanceAgainstDustThreshold = true; @@ -528,7 +533,7 @@ PlaceOrderInfo ExchangePrivate::placeOrderProcess(MonetaryAmount &from, Monetary const MonetaryAmount volume(isSell ? from : MonetaryAmount(from / price, mk.base())); if (tradeInfo.options.isSimulation() && !isSimulatedOrderSupported()) { - if (exchangeInfo().placeSimulateRealOrder()) { + if (exchangeConfig().placeSimulateRealOrder()) { log::debug("Place simulate real order - price {} will be overriden", price); MarketOrderBook marketOrderbook = _exchangePublic.queryOrderBook(mk); price = isSell ? marketOrderbook.getHighestTheoreticalPrice() : marketOrderbook.getLowestTheoreticalPrice(); @@ -552,13 +557,13 @@ PlaceOrderInfo ExchangePrivate::placeOrderProcess(MonetaryAmount &from, Monetary PlaceOrderInfo ExchangePrivate::computeSimulatedMatchedPlacedOrderInfo(MonetaryAmount volume, MonetaryAmount price, const TradeInfo &tradeInfo) const { - const bool placeSimulatedRealOrder = exchangeInfo().placeSimulateRealOrder(); + const bool placeSimulatedRealOrder = exchangeConfig().placeSimulateRealOrder(); const bool isTakerStrategy = tradeInfo.options.isTakerStrategy(placeSimulatedRealOrder); const bool isSell = tradeInfo.tradeContext.side == TradeSide::kSell; MonetaryAmount toAmount = isSell ? volume.convertTo(price) : volume; - ExchangeInfo::FeeType feeType = isTakerStrategy ? ExchangeInfo::FeeType::kTaker : ExchangeInfo::FeeType::kMaker; - toAmount = _coincenterInfo.exchangeInfo(_exchangePublic.name()).applyFee(toAmount, feeType); + ExchangeConfig::FeeType feeType = isTakerStrategy ? ExchangeConfig::FeeType::kTaker : ExchangeConfig::FeeType::kMaker; + toAmount = _coincenterInfo.exchangeConfig(_exchangePublic.name()).applyFee(toAmount, feeType); PlaceOrderInfo placeOrderInfo(OrderInfo(TradedAmounts(isSell ? volume : volume.toNeutral() * price, toAmount)), OrderId("SimulatedOrderId")); placeOrderInfo.setClosed(); diff --git a/src/api/common/src/exchangepublicapi.cpp b/src/api/common/src/exchangepublicapi.cpp index faa61e6b..b5640fdc 100644 --- a/src/api/common/src/exchangepublicapi.cpp +++ b/src/api/common/src/exchangepublicapi.cpp @@ -17,7 +17,7 @@ #include "coincenterinfo.hpp" #include "commonapi.hpp" #include "currencycode.hpp" -#include "exchangeinfo.hpp" +#include "exchangeconfig.hpp" #include "exchangepublicapitypes.hpp" #include "fiatconverter.hpp" #include "market.hpp" @@ -34,7 +34,7 @@ ExchangePublic::ExchangePublic(std::string_view name, FiatConverter &fiatConvert _fiatConverter(fiatConverter), _commonApi(commonApi), _coincenterInfo(coincenterInfo), - _exchangeInfo(coincenterInfo.exchangeInfo(name)) {} + _exchangeConfig(coincenterInfo.exchangeConfig(name)) {} std::optional ExchangePublic::convert(MonetaryAmount from, CurrencyCode toCurrency, const MarketsPath &conversionPath, const Fiats &fiats, @@ -46,8 +46,8 @@ std::optional ExchangePublic::convert(MonetaryAmount from, Curre if (conversionPath.empty()) { return std::nullopt; } - const ExchangeInfo::FeeType feeType = - priceOptions.isTakerStrategy() ? ExchangeInfo::FeeType::kTaker : ExchangeInfo::FeeType::kMaker; + const ExchangeConfig::FeeType feeType = + priceOptions.isTakerStrategy() ? ExchangeConfig::FeeType::kTaker : ExchangeConfig::FeeType::kMaker; if (marketOrderBookMap.empty()) { std::lock_guard guard(_allOrderBooksMutex); @@ -89,7 +89,7 @@ std::optional ExchangePublic::convert(MonetaryAmount from, Curre if (!optA) { return std::nullopt; } - from = _exchangeInfo.applyFee(*optA, feeType); + from = _exchangeConfig.applyFee(*optA, feeType); break; } default: diff --git a/src/api/common/test/exchangeprivateapi_test.cpp b/src/api/common/test/exchangeprivateapi_test.cpp index 29544bd7..b10ef710 100644 --- a/src/api/common/test/exchangeprivateapi_test.cpp +++ b/src/api/common/test/exchangeprivateapi_test.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -15,7 +16,7 @@ #include "coincenterinfo.hpp" #include "commonapi.hpp" #include "currencycode.hpp" -#include "exchangeinfo.hpp" +#include "exchangeconfig.hpp" #include "exchangeprivateapi_mock.hpp" #include "exchangeprivateapitypes.hpp" #include "exchangepublicapi_mock.hpp" @@ -79,6 +80,11 @@ class ExchangePrivateTest : public ::testing::Test { EXPECT_CALL(exchangePublic, queryTradableMarkets()).WillOnce(testing::Return(MarketSet{market})); } + TradeInfo computeTradeInfo(const TradeContext &tradeContext, const TradeOptions &tradeOptions) const { + TradeOptions resultingTradeOptions(tradeOptions, exchangePublic.exchangeConfig()); + return {tradeContext, resultingTradeOptions}; + } + LoadConfiguration loadConfiguration{kDefaultDataDir, LoadConfiguration::ExchangeConfigFileType::kTest}; CoincenterInfo coincenterInfo{settings::RunMode::kTestKeys, loadConfiguration}; CommonAPI commonAPI{coincenterInfo, Duration::max()}; @@ -119,7 +125,7 @@ TEST_F(ExchangePrivateTest, TakerTradeBaseToQuote) { PriceOptions priceOptions(PriceStrategy::kTaker); TradeOptions tradeOptions(priceOptions); TradeContext tradeContext(market, TradeSide::kSell); - TradeInfo tradeInfo(tradeContext, tradeOptions); + TradeInfo tradeInfo = computeTradeInfo(tradeContext, tradeOptions); MonetaryAmount tradedTo("23004 EUR"); @@ -142,7 +148,7 @@ TEST_F(ExchangePrivateTest, TakerTradeQuoteToBase) { PriceOptions priceOptions(PriceStrategy::kTaker); TradeOptions tradeOptions(priceOptions); TradeContext tradeContext(market, TradeSide::kBuy); - TradeInfo tradeInfo(tradeContext, tradeOptions); + TradeInfo tradeInfo = computeTradeInfo(tradeContext, tradeOptions); MonetaryAmount tradedTo = vol * pri.toNeutral(); @@ -163,11 +169,10 @@ TEST_F(ExchangePrivateTest, TradeAsyncPolicyTaker) { MonetaryAmount vol(from / pri, market.base()); PriceOptions priceOptions(PriceStrategy::kTaker); - TradeOptions tradeOptions(priceOptions, TradeTimeoutAction::kCancel, TradeMode::kReal, - TradeOptions::kDefaultTradeDuration, TradeOptions::kDefaultMinTimeBetweenPriceUpdates, - TradeTypePolicy::kDefault, TradeSyncPolicy::kAsynchronous); + TradeOptions tradeOptions(priceOptions, TradeTimeoutAction::kCancel, TradeMode::kReal, std::chrono::seconds(10), + std::chrono::seconds(5), TradeTypePolicy::kDefault, TradeSyncPolicy::kAsynchronous); TradeContext tradeContext(market, TradeSide::kBuy); - TradeInfo tradeInfo(tradeContext, tradeOptions); + TradeInfo tradeInfo = computeTradeInfo(tradeContext, tradeOptions); MonetaryAmount tradedTo = vol * pri.toNeutral(); @@ -191,10 +196,9 @@ TEST_F(ExchangePrivateTest, TradeAsyncPolicyMaker) { TradeContext tradeContext(market, side); PriceOptions priceOptions(PriceStrategy::kMaker); - TradeOptions tradeOptions(priceOptions, TradeTimeoutAction::kCancel, TradeMode::kReal, - TradeOptions::kDefaultTradeDuration, TradeOptions::kDefaultMinTimeBetweenPriceUpdates, - TradeTypePolicy::kDefault, TradeSyncPolicy::kAsynchronous); - TradeInfo tradeInfo(tradeContext, tradeOptions); + TradeOptions tradeOptions(priceOptions, TradeTimeoutAction::kCancel, TradeMode::kReal, std::chrono::seconds(10), + std::chrono::seconds(5), TradeTypePolicy::kDefault, TradeSyncPolicy::kAsynchronous); + TradeInfo tradeInfo = computeTradeInfo(tradeContext, tradeOptions); EXPECT_CALL(exchangePublic, queryOrderBook(market, testing::_)).WillOnce(testing::Return(marketOrderBook1)); @@ -219,7 +223,7 @@ TEST_F(ExchangePrivateTest, MakerTradeBaseToQuote) { PriceOptions priceOptions(PriceStrategy::kMaker); TradeOptions tradeOptions(priceOptions); - TradeInfo tradeInfo(tradeContext, tradeOptions); + TradeInfo tradeInfo = computeTradeInfo(tradeContext, tradeOptions); EXPECT_CALL(exchangePublic, queryOrderBook(market, testing::_)).WillOnce(testing::Return(marketOrderBook1)); @@ -253,9 +257,9 @@ TEST_F(ExchangePrivateTest, MakerTradeQuoteToBase) { MonetaryAmount vol1(from / pri1, market.base()); MonetaryAmount vol2(from / pri2, market.base()); - TradeOptions tradeOptions(TradeTimeoutAction::kCancel, TradeMode::kReal, Duration::max(), Duration::zero(), - TradeTypePolicy::kForceMultiTrade); - TradeInfo tradeInfo(tradeContext, tradeOptions); + TradeOptions tradeOptions(PriceOptions{}, TradeTimeoutAction::kCancel, TradeMode::kReal, Duration::max(), + Duration::zero(), TradeTypePolicy::kForceMultiTrade); + TradeInfo tradeInfo = computeTradeInfo(tradeContext, tradeOptions); { testing::InSequence seq; @@ -329,10 +333,10 @@ TEST_F(ExchangePrivateTest, SimulatedOrderShouldNotCallPlaceOrder) { MonetaryAmount pri(askPrice1); TradeSide side = TradeSide::kSell; - TradeOptions tradeOptions(TradeTimeoutAction::kCancel, TradeMode::kSimulation, Duration::max(), Duration::zero(), - TradeTypePolicy::kForceMultiTrade); + TradeOptions tradeOptions(PriceOptions{}, TradeTimeoutAction::kCancel, TradeMode::kSimulation, Duration::max(), + Duration::zero(), TradeTypePolicy::kForceMultiTrade); TradeContext tradeContext(market, side); - TradeInfo tradeInfo(tradeContext, tradeOptions); + TradeInfo tradeInfo = computeTradeInfo(tradeContext, tradeOptions); EXPECT_CALL(exchangePublic, queryOrderBook(market, testing::_)).WillOnce(testing::Return(marketOrderBook1)); @@ -340,7 +344,7 @@ TEST_F(ExchangePrivateTest, SimulatedOrderShouldNotCallPlaceOrder) { // In simulation mode, fee is applied MonetaryAmount toAmount = - exchangePublic.exchangeInfo().applyFee(from.toNeutral() * askPrice1, ExchangeInfo::FeeType::kMaker); + exchangePublic.exchangeConfig().applyFee(from.toNeutral() * askPrice1, ExchangeConfig::FeeType::kMaker); EXPECT_EQ(exchangePrivate.trade(from, market.quote(), tradeOptions), TradedAmounts(from, toAmount)); } @@ -355,9 +359,9 @@ TEST_F(ExchangePrivateTest, MakerTradeQuoteToBaseEmergencyTakerTrade) { MonetaryAmount vol1(from / pri1, market.base()); - TradeOptions tradeOptions(TradeTimeoutAction::kForceMatch, TradeMode::kReal, Duration::zero(), Duration::zero(), - TradeTypePolicy::kForceMultiTrade); - TradeInfo tradeInfo(tradeContext, tradeOptions); + TradeOptions tradeOptions(PriceOptions{}, TradeTimeoutAction::kMatch, TradeMode::kReal, Duration::zero(), + Duration::zero(), TradeTypePolicy::kForceMultiTrade); + TradeInfo tradeInfo = computeTradeInfo(tradeContext, tradeOptions); EXPECT_CALL(exchangePublic, queryOrderBook(market, testing::_)) .Times(2) @@ -402,9 +406,9 @@ TEST_F(ExchangePrivateTest, MakerTradeQuoteToBaseTimeout) { MonetaryAmount vol1(from / pri1, market.base()); - TradeOptions tradeOptions(TradeTimeoutAction::kCancel, TradeMode::kReal, Duration::zero(), Duration::zero(), - TradeTypePolicy::kForceMultiTrade); - TradeInfo tradeInfo(tradeContext, tradeOptions); + TradeOptions tradeOptions(PriceOptions{}, TradeTimeoutAction::kCancel, TradeMode::kReal, Duration::zero(), + Duration::zero(), TradeTypePolicy::kForceMultiTrade); + TradeInfo tradeInfo = computeTradeInfo(tradeContext, tradeOptions); EXPECT_CALL(exchangePublic, queryOrderBook(market, testing::_)).WillOnce(testing::Return(marketOrderBook1)); @@ -569,7 +573,7 @@ class ExchangePrivateDustSweeperTest : public ExchangePrivateTest { Market mk{from.currencyCode(), pri.currencyCode()}; TradeContext tradeContext(mk, TradeSide::kSell); - TradeInfo tradeInfo(tradeContext, tradeOptions); + TradeInfo tradeInfo = computeTradeInfo(tradeContext, tradeOptions); MonetaryAmount tradedTo = vol.toNeutral() * pri; @@ -595,7 +599,7 @@ class ExchangePrivateDustSweeperTest : public ExchangePrivateTest { MonetaryAmount vol(from / askPri, mk.base()); TradeContext tradeContext(mk, TradeSide::kBuy); - TradeInfo tradeInfo(tradeContext, tradeOptions); + TradeInfo tradeInfo = computeTradeInfo(tradeContext, tradeOptions); TradedAmounts tradedAmounts(MonetaryAmount{success ? from : MonetaryAmount(0), askPri.currencyCode()}, success ? vol : MonetaryAmount{0, vol.currencyCode()}); @@ -614,7 +618,7 @@ class ExchangePrivateDustSweeperTest : public ExchangePrivateTest { } std::optional dustThreshold(CurrencyCode cur) { - const auto &dustThresholds = exchangePublic.exchangeInfo().dustAmountsThreshold(); + const auto &dustThresholds = exchangePublic.exchangeConfig().dustAmountsThreshold(); auto dustThresholdLb = dustThresholds.find(MonetaryAmount(0, cur)); if (dustThresholdLb == dustThresholds.end()) { return std::nullopt; diff --git a/src/api/common/test/exchangepublicapi_test.cpp b/src/api/common/test/exchangepublicapi_test.cpp index 794be1c1..40fecf8a 100644 --- a/src/api/common/test/exchangepublicapi_test.cpp +++ b/src/api/common/test/exchangepublicapi_test.cpp @@ -10,7 +10,7 @@ #include "coincenterinfo.hpp" #include "commonapi.hpp" #include "currencycode.hpp" -#include "exchangeinfo.hpp" +#include "exchangeconfig.hpp" #include "exchangepublicapi_mock.hpp" #include "exchangepublicapitypes.hpp" #include "fiatconverter.hpp" @@ -131,8 +131,8 @@ TEST_F(ExchangePublicConvertTest, ConvertSimple) { std::optional ret = exchangePublic.convert(from, toCurrency, conversionPath, fiats, marketOrderBookMap, priceOptions); ASSERT_TRUE(ret.has_value()); - MonetaryAmount res = exchangePublic.exchangeInfo().applyFee( - marketOrderBook1.convert(from, priceOptions).value_or(MonetaryAmount{-1}), ExchangeInfo::FeeType::kMaker); + MonetaryAmount res = exchangePublic.exchangeConfig().applyFee( + marketOrderBook1.convert(from, priceOptions).value_or(MonetaryAmount{-1}), ExchangeConfig::FeeType::kMaker); EXPECT_EQ(ret, std::optional(res)); } @@ -143,10 +143,10 @@ TEST_F(ExchangePublicConvertTest, ConvertDouble) { std::optional ret = exchangePublic.convert(from, toCurrency, conversionPath, fiats, marketOrderBookMap, priceOptions); ASSERT_TRUE(ret.has_value()); - MonetaryAmount res = exchangePublic.exchangeInfo().applyFee( - marketOrderBook1.convert(from, priceOptions).value_or(MonetaryAmount{-1}), ExchangeInfo::FeeType::kMaker); - res = exchangePublic.exchangeInfo().applyFee(marketOrderBook2.convert(res, priceOptions).value_or(MonetaryAmount{-1}), - ExchangeInfo::FeeType::kMaker); + MonetaryAmount res = exchangePublic.exchangeConfig().applyFee( + marketOrderBook1.convert(from, priceOptions).value_or(MonetaryAmount{-1}), ExchangeConfig::FeeType::kMaker); + res = exchangePublic.exchangeConfig().applyFee( + marketOrderBook2.convert(res, priceOptions).value_or(MonetaryAmount{-1}), ExchangeConfig::FeeType::kMaker); EXPECT_EQ(ret, std::optional(res)); } diff --git a/src/api/common/test/fiatconverter_test.cpp b/src/api/common/test/fiatconverter_test.cpp index 663dfcb7..adb9a1e5 100644 --- a/src/api/common/test/fiatconverter_test.cpp +++ b/src/api/common/test/fiatconverter_test.cpp @@ -33,7 +33,7 @@ constexpr double kGBP = 0.88; constexpr std::string_view kSomeFakeURL = "some/fake/url"; } // namespace -CurlHandle::CurlHandle([[maybe_unused]] const BestURLPicker &bestURLPicker, +CurlHandle::CurlHandle([[maybe_unused]] BestURLPicker bestURLPicker, [[maybe_unused]] AbstractMetricGateway *pMetricGateway, [[maybe_unused]] const PermanentCurlOptions &permanentCurlOptions, [[maybe_unused]] settings::RunMode runMode) diff --git a/src/api/exchanges/include/binanceprivateapi.hpp b/src/api/exchanges/include/binanceprivateapi.hpp index b58df4dc..e6897e98 100644 --- a/src/api/exchanges/include/binanceprivateapi.hpp +++ b/src/api/exchanges/include/binanceprivateapi.hpp @@ -25,7 +25,7 @@ namespace cct { class CoincenterInfo; -class ExchangeInfo; +class ExchangeConfig; class FiatConverter; namespace api { diff --git a/src/api/exchanges/include/binancepublicapi.hpp b/src/api/exchanges/include/binancepublicapi.hpp index 013cd804..1b8b307b 100644 --- a/src/api/exchanges/include/binancepublicapi.hpp +++ b/src/api/exchanges/include/binancepublicapi.hpp @@ -20,7 +20,7 @@ namespace cct { class CoincenterInfo; -class ExchangeInfo; +class ExchangeConfig; class FiatConverter; namespace api { @@ -79,9 +79,9 @@ class BinancePublic : public ExchangePublic { MonetaryAmount computePriceForNotional(Market mk, int avgPriceMins); struct CommonInfo { - CommonInfo(const CoincenterInfo& coincenterInfo, const ExchangeInfo& exchangeInfo, settings::RunMode runMode); + CommonInfo(const CoincenterInfo& coincenterInfo, const ExchangeConfig& exchangeConfig, settings::RunMode runMode); - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; CurlHandle _curlHandle; }; @@ -105,15 +105,15 @@ class BinancePublic : public ExchangePublic { struct MarketsFunc { MarketSet operator()(); - CachedResult& _exchangeInfoCache; + CachedResult& _exchangeConfigCache; CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; struct AllOrderBooksFunc { MarketOrderBookMap operator()(int depth); - CachedResult& _exchangeInfoCache; + CachedResult& _exchangeConfigCache; CachedResult& _marketsCache; CommonInfo& _commonInfo; }; @@ -137,7 +137,7 @@ class BinancePublic : public ExchangePublic { }; CommonInfo _commonInfo; - CachedResult _exchangeInfoCache; + CachedResult _exchangeConfigCache; CachedResult _globalInfosCache; CachedResult _marketsCache; CachedResult _allOrderBooksCache; diff --git a/src/api/exchanges/include/bithumbpublicapi.hpp b/src/api/exchanges/include/bithumbpublicapi.hpp index 243197f0..558bfc66 100644 --- a/src/api/exchanges/include/bithumbpublicapi.hpp +++ b/src/api/exchanges/include/bithumbpublicapi.hpp @@ -11,7 +11,7 @@ namespace cct { class CoincenterInfo; -class ExchangeInfo; +class ExchangeConfig; class FiatConverter; namespace api { @@ -85,7 +85,7 @@ class BithumbPublic : public ExchangePublic { const CoincenterInfo& _coincenterInfo; CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; struct OrderBookFunc { @@ -93,7 +93,7 @@ class BithumbPublic : public ExchangePublic { const CoincenterInfo& _coincenterInfo; CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; struct TradedVolumeFunc { diff --git a/src/api/exchanges/include/huobiprivateapi.hpp b/src/api/exchanges/include/huobiprivateapi.hpp index f9952582..57b8d6ae 100644 --- a/src/api/exchanges/include/huobiprivateapi.hpp +++ b/src/api/exchanges/include/huobiprivateapi.hpp @@ -10,7 +10,7 @@ namespace cct { class CoincenterInfo; -class ExchangeInfo; +class ExchangeConfig; class FiatConverter; namespace api { diff --git a/src/api/exchanges/include/huobipublicapi.hpp b/src/api/exchanges/include/huobipublicapi.hpp index f74a4073..e1c7636f 100644 --- a/src/api/exchanges/include/huobipublicapi.hpp +++ b/src/api/exchanges/include/huobipublicapi.hpp @@ -16,7 +16,7 @@ namespace cct { class CoincenterInfo; -class ExchangeInfo; +class ExchangeConfig; class FiatConverter; namespace api { @@ -99,7 +99,7 @@ class HuobiPublic : public ExchangePublic { std::pair operator()(); CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; struct AllOrderBooksFunc { @@ -107,14 +107,14 @@ class HuobiPublic : public ExchangePublic { CachedResult& _marketsCache; CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; struct OrderBookFunc { MarketOrderBook operator()(Market mk, int depth); CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; struct TradedVolumeFunc { @@ -139,7 +139,7 @@ class HuobiPublic : public ExchangePublic { static bool ShouldDiscardChain(CurrencyCode cur, const json& chainDetail); - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; CurlHandle _curlHandle; CurlHandle _healthCheckCurlHandle; CachedResult _tradableCurrenciesCache; diff --git a/src/api/exchanges/include/krakenpublicapi.hpp b/src/api/exchanges/include/krakenpublicapi.hpp index d6a45f25..4c164168 100644 --- a/src/api/exchanges/include/krakenpublicapi.hpp +++ b/src/api/exchanges/include/krakenpublicapi.hpp @@ -13,7 +13,7 @@ namespace cct { class CoincenterInfo; -class ExchangeInfo; +class ExchangeConfig; namespace api { class CommonAPI; @@ -71,7 +71,7 @@ class KrakenPublic : public ExchangePublic { const CoincenterInfo& _coincenterInfo; CommonAPI& _commonApi; CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; class WithdrawalFeesFunc { @@ -106,7 +106,7 @@ class KrakenPublic : public ExchangePublic { CachedResult& _tradableCurrenciesCache; const CoincenterInfo& _coincenterInfo; CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; struct AllOrderBooksFunc { diff --git a/src/api/exchanges/include/kucoinprivateapi.hpp b/src/api/exchanges/include/kucoinprivateapi.hpp index 49fabd15..c8b13127 100644 --- a/src/api/exchanges/include/kucoinprivateapi.hpp +++ b/src/api/exchanges/include/kucoinprivateapi.hpp @@ -10,7 +10,7 @@ namespace cct { class CoincenterInfo; -class ExchangeInfo; +class ExchangeConfig; class FiatConverter; namespace api { diff --git a/src/api/exchanges/include/kucoinpublicapi.hpp b/src/api/exchanges/include/kucoinpublicapi.hpp index 924a7127..f3b03b7a 100644 --- a/src/api/exchanges/include/kucoinpublicapi.hpp +++ b/src/api/exchanges/include/kucoinpublicapi.hpp @@ -16,7 +16,7 @@ namespace cct { class CoincenterInfo; -class ExchangeInfo; +class ExchangeConfig; class FiatConverter; namespace api { @@ -104,7 +104,7 @@ class KucoinPublic : public ExchangePublic { std::pair operator()(); CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; struct AllOrderBooksFunc { @@ -112,14 +112,14 @@ class KucoinPublic : public ExchangePublic { CachedResult& _marketsCache; CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; struct OrderBookFunc { MarketOrderBook operator()(Market mk, int depth); CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; struct TradedVolumeFunc { diff --git a/src/api/exchanges/include/upbitprivateapi.hpp b/src/api/exchanges/include/upbitprivateapi.hpp index fb89d1f0..b0c967b3 100644 --- a/src/api/exchanges/include/upbitprivateapi.hpp +++ b/src/api/exchanges/include/upbitprivateapi.hpp @@ -72,7 +72,7 @@ class UpbitPrivate : public ExchangePrivate { CurlHandle& _curlHandle; const APIKey& _apiKey; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; CommonAPI& _commonApi; }; diff --git a/src/api/exchanges/include/upbitpublicapi.hpp b/src/api/exchanges/include/upbitpublicapi.hpp index 605d7f85..28c59ec8 100644 --- a/src/api/exchanges/include/upbitpublicapi.hpp +++ b/src/api/exchanges/include/upbitpublicapi.hpp @@ -12,7 +12,7 @@ namespace cct { class CoincenterInfo; -class ExchangeInfo; +class ExchangeConfig; class FiatConverter; namespace api { @@ -69,7 +69,7 @@ class UpbitPublic : public ExchangePublic { MarketSet operator()(); CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; struct TradableCurrenciesFunc { @@ -90,7 +90,7 @@ class UpbitPublic : public ExchangePublic { MarketOrderBookMap operator()(int depth); CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; CachedResult& _marketsCache; }; @@ -98,7 +98,7 @@ class UpbitPublic : public ExchangePublic { MarketOrderBook operator()(Market mk, int depth); CurlHandle& _curlHandle; - const ExchangeInfo& _exchangeInfo; + const ExchangeConfig& _exchangeConfig; }; struct TradedVolumeFunc { diff --git a/src/api/exchanges/src/binanceprivateapi.cpp b/src/api/exchanges/src/binanceprivateapi.cpp index 15468a79..bbe01781 100644 --- a/src/api/exchanges/src/binanceprivateapi.cpp +++ b/src/api/exchanges/src/binanceprivateapi.cpp @@ -207,23 +207,23 @@ BinancePrivate::BinancePrivate(const CoincenterInfo& coincenterInfo, BinancePubl : ExchangePrivate(coincenterInfo, binancePublic, apiKey), _curlHandle(BinancePublic::kURLBases, coincenterInfo.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(exchangeInfo().privateAPIRate()) - .setAcceptedEncoding(exchangeInfo().acceptEncoding()) - .setRequestCallLogLevel(exchangeInfo().requestsCallLogLevel()) - .setRequestAnswerLogLevel(exchangeInfo().requestsAnswerLogLevel()) + .setMinDurationBetweenQueries(exchangeConfig().privateAPIRate()) + .setAcceptedEncoding(exchangeConfig().acceptEncoding()) + .setRequestCallLogLevel(exchangeConfig().requestsCallLogLevel()) + .setRequestAnswerLogLevel(exchangeConfig().requestsAnswerLogLevel()) .build(), coincenterInfo.getRunMode()), _tradableCurrenciesCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), _curlHandle, + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), _curlHandle, _apiKey, binancePublic, _queryDelay), _depositWalletsCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kDepositWallet), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kDepositWallet), _cachedResultVault), _curlHandle, _apiKey, binancePublic, _queryDelay), _allWithdrawFeesCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), _curlHandle, _apiKey, binancePublic, _queryDelay), _withdrawFeesCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), _curlHandle, _apiKey, binancePublic, _queryDelay) {} CurrencyExchangeFlatSet BinancePrivate::TradableCurrenciesCache::operator()() { @@ -265,7 +265,7 @@ Wallet BinancePrivate::DepositWalletFunc::operator()(CurrencyCode currencyCode) _queryDelay, {{"coin", currencyCode.str()}}); std::string_view tag(result["tag"].get()); const CoincenterInfo& coincenterInfo = _exchangePublic.coincenterInfo(); - bool doCheckWallet = coincenterInfo.exchangeInfo(_exchangePublic.name()).validateDepositAddressesInFile(); + bool doCheckWallet = coincenterInfo.exchangeConfig(_exchangePublic.name()).validateDepositAddressesInFile(); WalletCheck walletCheck(coincenterInfo.dataDir(), doCheckWallet); Wallet wallet(ExchangeName(_exchangePublic.name(), _apiKey.name()), currencyCode, std::move(result["address"].get_ref()), tag, walletCheck, _apiKey.accountOwner()); @@ -609,7 +609,7 @@ PlaceOrderInfo BinancePrivate::placeOrder(MonetaryAmount from, MonetaryAmount vo const CurrencyCode toCurrencyCode(tradeInfo.tradeContext.toCur()); const Market mk = tradeInfo.tradeContext.mk; const std::string_view buyOrSell = fromCurrencyCode == mk.base() ? "SELL" : "BUY"; - const bool placeSimulatedRealOrder = binancePublic.exchangeInfo().placeSimulateRealOrder(); + const bool placeSimulatedRealOrder = binancePublic.exchangeConfig().placeSimulateRealOrder(); const bool isTakerStrategy = tradeInfo.options.isTakerStrategy(placeSimulatedRealOrder); const std::string_view orderType = isTakerStrategy ? "MARKET" : "LIMIT"; const bool isSimulation = tradeInfo.options.isSimulation(); diff --git a/src/api/exchanges/src/binancepublicapi.cpp b/src/api/exchanges/src/binancepublicapi.cpp index 45813ef3..aa7a59f9 100644 --- a/src/api/exchanges/src/binancepublicapi.cpp +++ b/src/api/exchanges/src/binancepublicapi.cpp @@ -86,28 +86,29 @@ VolAndPriNbDecimals QueryVolAndPriNbDecimals(const ExchangeInfoDataByMarket& exc BinancePublic::BinancePublic(const CoincenterInfo& coincenterInfo, FiatConverter& fiatConverter, api::CommonAPI& commonAPI) : ExchangePublic("binance", fiatConverter, commonAPI, coincenterInfo), - _commonInfo(coincenterInfo, exchangeInfo(), coincenterInfo.getRunMode()), - _exchangeInfoCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), - _commonInfo), + _commonInfo(coincenterInfo, exchangeConfig(), coincenterInfo.getRunMode()), + _exchangeConfigCache( + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), + _commonInfo), _globalInfosCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), coincenterInfo.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(_commonInfo._exchangeInfo.publicAPIRate()) - .setAcceptedEncoding(_commonInfo._exchangeInfo.acceptEncoding()) + .setMinDurationBetweenQueries(_commonInfo._exchangeConfig.publicAPIRate()) + .setAcceptedEncoding(_commonInfo._exchangeConfig.acceptEncoding()) .build(), coincenterInfo.getRunMode()), - _marketsCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kMarkets), _cachedResultVault), - _exchangeInfoCache, _commonInfo._curlHandle, _commonInfo._exchangeInfo), + _marketsCache(CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kMarkets), _cachedResultVault), + _exchangeConfigCache, _commonInfo._curlHandle, _commonInfo._exchangeConfig), _allOrderBooksCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kAllOrderBooks), _cachedResultVault), - _exchangeInfoCache, _marketsCache, _commonInfo), - _orderbookCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kOrderBook), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kAllOrderBooks), _cachedResultVault), + _exchangeConfigCache, _marketsCache, _commonInfo), + _orderbookCache(CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kOrderBook), _cachedResultVault), _commonInfo), _tradedVolumeCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kTradedVolume), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kTradedVolume), _cachedResultVault), _commonInfo), - _tickerCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kLastPrice), _cachedResultVault), + _tickerCache(CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kLastPrice), _cachedResultVault), _commonInfo) {} bool BinancePublic::healthCheck() { @@ -118,21 +119,21 @@ bool BinancePublic::healthCheck() { return result.empty(); } -BinancePublic::CommonInfo::CommonInfo(const CoincenterInfo& coincenterInfo, const ExchangeInfo& exchangeInfo, +BinancePublic::CommonInfo::CommonInfo(const CoincenterInfo& coincenterInfo, const ExchangeConfig& exchangeConfig, settings::RunMode runMode) - : _exchangeInfo(exchangeInfo), + : _exchangeConfig(exchangeConfig), _curlHandle(kURLBases, coincenterInfo.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(_exchangeInfo.publicAPIRate()) - .setAcceptedEncoding(_exchangeInfo.acceptEncoding()) - .setRequestCallLogLevel(_exchangeInfo.requestsCallLogLevel()) - .setRequestAnswerLogLevel(_exchangeInfo.requestsAnswerLogLevel()) + .setMinDurationBetweenQueries(_exchangeConfig.publicAPIRate()) + .setAcceptedEncoding(_exchangeConfig.acceptEncoding()) + .setRequestCallLogLevel(_exchangeConfig.requestsCallLogLevel()) + .setRequestAnswerLogLevel(_exchangeConfig.requestsAnswerLogLevel()) .build(), runMode) {} CurrencyExchangeFlatSet BinancePublic::queryTradableCurrencies(const json& data) const { CurrencyExchangeVector currencies; - const CurrencyCodeSet& excludedCurrencies = _commonInfo._exchangeInfo.excludedCurrenciesAll(); + const CurrencyCodeSet& excludedCurrencies = _commonInfo._exchangeConfig.excludedCurrenciesAll(); for (const json& coinJson : data) { std::string_view coin = coinJson["coin"].get(); if (coin.size() > CurrencyCode::kMaxLen) { @@ -168,8 +169,8 @@ CurrencyExchangeFlatSet BinancePublic::queryTradableCurrencies(const json& data) } MarketSet BinancePublic::MarketsFunc::operator()() { - BinancePublic::ExchangeInfoFunc::ExchangeInfoDataByMarket exchangeInfoData = _exchangeInfoCache.get(); - const CurrencyCodeSet& excludedCurrencies = _exchangeInfo.excludedCurrenciesAll(); + BinancePublic::ExchangeInfoFunc::ExchangeInfoDataByMarket exchangeInfoData = _exchangeConfigCache.get(); + const CurrencyCodeSet& excludedCurrencies = _exchangeConfig.excludedCurrenciesAll(); MarketSet ret; ret.reserve(static_cast(exchangeInfoData.size())); for (const auto& marketJsonPair : exchangeInfoData) { @@ -276,7 +277,7 @@ std::optional BinancePublic::queryWithdrawalFee(CurrencyCode cur } MonetaryAmount BinancePublic::sanitizePrice(Market mk, MonetaryAmount pri) { - const json& marketData = RetrieveMarketData(_exchangeInfoCache.get(), mk); + const json& marketData = RetrieveMarketData(_exchangeConfigCache.get(), mk); const json* pPriceFilter = nullptr; MonetaryAmount ret(pri); @@ -307,7 +308,7 @@ MonetaryAmount BinancePublic::sanitizePrice(Market mk, MonetaryAmount pri) { } } - VolAndPriNbDecimals volAndPriNbDecimals = QueryVolAndPriNbDecimals(_exchangeInfoCache.get(), mk); + VolAndPriNbDecimals volAndPriNbDecimals = QueryVolAndPriNbDecimals(_exchangeConfigCache.get(), mk); ret.truncate(volAndPriNbDecimals.priNbDecimals); if (pri != ret) { log::warn("Sanitize price {} -> {}", pri, ret); @@ -334,7 +335,7 @@ MonetaryAmount BinancePublic::computePriceForNotional(Market mk, int avgPriceMin MonetaryAmount BinancePublic::sanitizeVolume(Market mk, MonetaryAmount vol, MonetaryAmount priceForNotional, bool isTakerOrder) { - const json& marketData = RetrieveMarketData(_exchangeInfoCache.get(), mk); + const json& marketData = RetrieveMarketData(_exchangeConfigCache.get(), mk); MonetaryAmount ret(vol); const json* pMinNotionalFilter = nullptr; @@ -436,7 +437,7 @@ MonetaryAmount BinancePublic::sanitizeVolume(Market mk, MonetaryAmount vol, Mone } } - VolAndPriNbDecimals volAndPriNbDecimals = QueryVolAndPriNbDecimals(_exchangeInfoCache.get(), mk); + VolAndPriNbDecimals volAndPriNbDecimals = QueryVolAndPriNbDecimals(_exchangeConfigCache.get(), mk); ret.truncate(volAndPriNbDecimals.volNbDecimals); if (ret != vol) { log::warn("Sanitize volume {} -> {}", vol, ret); @@ -467,7 +468,7 @@ MarketOrderBookMap BinancePublic::AllOrderBooksFunc::operator()(int depth) { MonetaryAmount bidVol(tickerDetails["bidQty"].get(), mk.base()); ret.insert_or_assign(mk, MarketOrderBook(askPri, askVol, bidPri, bidVol, - QueryVolAndPriNbDecimals(_exchangeInfoCache.get(), mk), depth)); + QueryVolAndPriNbDecimals(_exchangeConfigCache.get(), mk), depth)); } log::info("Retrieved ticker information from {} markets", ret.size()); diff --git a/src/api/exchanges/src/bithumbprivateapi.cpp b/src/api/exchanges/src/bithumbprivateapi.cpp index b2fce5b0..af90b000 100644 --- a/src/api/exchanges/src/bithumbprivateapi.cpp +++ b/src/api/exchanges/src/bithumbprivateapi.cpp @@ -32,7 +32,7 @@ #include "deposit.hpp" #include "depositsconstraints.hpp" #include "durationstring.hpp" -#include "exchangeinfo.hpp" +#include "exchangeconfig.hpp" #include "exchangename.hpp" #include "exchangeprivateapi.hpp" #include "exchangeprivateapitypes.hpp" @@ -309,15 +309,15 @@ BithumbPrivate::BithumbPrivate(const CoincenterInfo& config, BithumbPublic& bith : ExchangePrivate(config, bithumbPublic, apiKey), _curlHandle(BithumbPublic::kUrlBase, config.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(exchangeInfo().privateAPIRate()) - .setAcceptedEncoding(exchangeInfo().acceptEncoding()) - .setRequestCallLogLevel(exchangeInfo().requestsCallLogLevel()) - .setRequestAnswerLogLevel(exchangeInfo().requestsAnswerLogLevel()) + .setMinDurationBetweenQueries(exchangeConfig().privateAPIRate()) + .setAcceptedEncoding(exchangeConfig().acceptEncoding()) + .setRequestCallLogLevel(exchangeConfig().requestsCallLogLevel()) + .setRequestAnswerLogLevel(exchangeConfig().requestsAnswerLogLevel()) .build(), config.getRunMode()), - _currencyOrderInfoRefreshTime(exchangeInfo().getAPICallUpdateFrequency(kCurrencyInfoBithumb)), + _currencyOrderInfoRefreshTime(exchangeConfig().getAPICallUpdateFrequency(kCurrencyInfoBithumb)), _depositWalletsCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kDepositWallet), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kDepositWallet), _cachedResultVault), _curlHandle, _apiKey, bithumbPublic) { if (config.getRunMode() != settings::RunMode::kQueryResponseOverriden) { json data = GetBithumbCurrencyInfoMapCache(_coincenterInfo.dataDir()).readAllJson(); @@ -385,7 +385,7 @@ Wallet BithumbPrivate::DepositWalletFunc::operator()(CurrencyCode currencyCode) : addressAndTag.end(), addressAndTag.end()); const CoincenterInfo& coincenterInfo = _exchangePublic.coincenterInfo(); - bool doCheckWallet = coincenterInfo.exchangeInfo(_exchangePublic.name()).validateDepositAddressesInFile(); + bool doCheckWallet = coincenterInfo.exchangeConfig(_exchangePublic.name()).validateDepositAddressesInFile(); WalletCheck walletCheck(coincenterInfo.dataDir(), doCheckWallet); Wallet wallet(ExchangeName(_exchangePublic.name(), _apiKey.name()), currencyCode, string(address), tag, walletCheck, _apiKey.accountOwner()); @@ -692,7 +692,7 @@ WithdrawsSet BithumbPrivate::queryRecentWithdraws(const WithdrawsConstraints& wi PlaceOrderInfo BithumbPrivate::placeOrder(MonetaryAmount /*from*/, MonetaryAmount volume, MonetaryAmount price, const TradeInfo& tradeInfo) { - const bool placeSimulatedRealOrder = _exchangePublic.exchangeInfo().placeSimulateRealOrder(); + const bool placeSimulatedRealOrder = _exchangePublic.exchangeConfig().placeSimulateRealOrder(); const bool isTakerStrategy = tradeInfo.options.isTakerStrategy(placeSimulatedRealOrder); const CurrencyCode fromCurrencyCode(tradeInfo.tradeContext.fromCur()); const CurrencyCode toCurrencyCode(tradeInfo.tradeContext.toCur()); @@ -715,9 +715,10 @@ PlaceOrderInfo BithumbPrivate::placeOrder(MonetaryAmount /*from*/, MonetaryAmoun // Volume is gross amount if from amount is in quote currency, we should remove the fees if (fromCurrencyCode == mk.quote()) { - ExchangeInfo::FeeType feeType = isTakerStrategy ? ExchangeInfo::FeeType::kTaker : ExchangeInfo::FeeType::kMaker; - const ExchangeInfo& exchangeInfo = _coincenterInfo.exchangeInfo(_exchangePublic.name()); - volume = exchangeInfo.applyFee(volume, feeType); + ExchangeConfig::FeeType feeType = + isTakerStrategy ? ExchangeConfig::FeeType::kTaker : ExchangeConfig::FeeType::kMaker; + const ExchangeConfig& exchangeConfig = _coincenterInfo.exchangeConfig(_exchangePublic.name()); + volume = exchangeConfig.applyFee(volume, feeType); } const bool isSimulationWithRealOrder = tradeInfo.options.isSimulation() && placeSimulatedRealOrder; diff --git a/src/api/exchanges/src/bithumbpublicapi.cpp b/src/api/exchanges/src/bithumbpublicapi.cpp index e9c5b164..d7e2fe96 100644 --- a/src/api/exchanges/src/bithumbpublicapi.cpp +++ b/src/api/exchanges/src/bithumbpublicapi.cpp @@ -85,30 +85,30 @@ BithumbPublic::BithumbPublic(const CoincenterInfo& config, FiatConverter& fiatCo : ExchangePublic("bithumb", fiatConverter, commonAPI, config), _curlHandle(kUrlBase, config.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(exchangeInfo().publicAPIRate()) - .setAcceptedEncoding(exchangeInfo().acceptEncoding()) - .setRequestCallLogLevel(exchangeInfo().requestsCallLogLevel()) - .setRequestAnswerLogLevel(exchangeInfo().requestsAnswerLogLevel()) + .setMinDurationBetweenQueries(exchangeConfig().publicAPIRate()) + .setAcceptedEncoding(exchangeConfig().acceptEncoding()) + .setRequestCallLogLevel(exchangeConfig().requestsCallLogLevel()) + .setRequestAnswerLogLevel(exchangeConfig().requestsAnswerLogLevel()) .build(), config.getRunMode()), _tradableCurrenciesCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), config, + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), config, commonAPI, _curlHandle), _withdrawalFeesCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), config.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(exchangeInfo().publicAPIRate()) - .setAcceptedEncoding(exchangeInfo().acceptEncoding()) + .setMinDurationBetweenQueries(exchangeConfig().publicAPIRate()) + .setAcceptedEncoding(exchangeConfig().acceptEncoding()) .build(), config.getRunMode()), _allOrderBooksCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kAllOrderBooks), _cachedResultVault), config, - _curlHandle, exchangeInfo()), - _orderbookCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kOrderBook), _cachedResultVault), - config, _curlHandle, exchangeInfo()), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kAllOrderBooks), _cachedResultVault), config, + _curlHandle, exchangeConfig()), + _orderbookCache(CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kOrderBook), _cachedResultVault), + config, _curlHandle, exchangeConfig()), _tradedVolumeCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kTradedVolume), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kTradedVolume), _cachedResultVault), _curlHandle) {} bool BithumbPublic::healthCheck() { @@ -126,7 +126,7 @@ bool BithumbPublic::healthCheck() { MarketSet BithumbPublic::queryTradableMarkets() { auto [pMarketOrderbookMap, lastUpdatedTime] = _allOrderBooksCache.retrieve(); if (pMarketOrderbookMap == nullptr || - lastUpdatedTime + exchangeInfo().getAPICallUpdateFrequency(kMarkets) < Clock::now()) { + lastUpdatedTime + exchangeConfig().getAPICallUpdateFrequency(kMarkets) < Clock::now()) { pMarketOrderbookMap = std::addressof(_allOrderBooksCache.get()); } MarketSet markets; @@ -226,8 +226,8 @@ CurrencyExchangeFlatSet BithumbPublic::TradableCurrenciesFunc::operator()() { } namespace { -MarketOrderBookMap GetOrderbooks(CurlHandle& curlHandle, const CoincenterInfo& config, const ExchangeInfo& exchangeInfo, - std::optional optM = std::nullopt, +MarketOrderBookMap GetOrderbooks(CurlHandle& curlHandle, const CoincenterInfo& config, + const ExchangeConfig& exchangeConfig, std::optional optM = std::nullopt, std::optional optDepth = std::nullopt) { MarketOrderBookMap ret; // 'all' seems to work as default for all public methods @@ -253,7 +253,7 @@ MarketOrderBookMap GetOrderbooks(CurlHandle& curlHandle, const CoincenterInfo& c log::error("Unexpected Bithumb reply for orderbook. May require code api update"); } CurrencyCode quoteCurrencyCode(config.standardizeCurrencyCode(quoteCurrency)); - const CurrencyCodeSet& excludedCurrencies = exchangeInfo.excludedCurrenciesAll(); + const CurrencyCodeSet& excludedCurrencies = exchangeConfig.excludedCurrenciesAll(); for (const auto& [baseOrSpecial, asksAndBids] : result.items()) { if (baseOrSpecial != "payment_currency" && baseOrSpecial != "timestamp") { const json* asksBids[2]; @@ -309,11 +309,11 @@ MarketOrderBookMap GetOrderbooks(CurlHandle& curlHandle, const CoincenterInfo& c } // namespace MarketOrderBookMap BithumbPublic::AllOrderBooksFunc::operator()() { - return GetOrderbooks(_curlHandle, _coincenterInfo, _exchangeInfo); + return GetOrderbooks(_curlHandle, _coincenterInfo, _exchangeConfig); } MarketOrderBook BithumbPublic::OrderBookFunc::operator()(Market mk, int depth) { - MarketOrderBookMap marketOrderBookMap = GetOrderbooks(_curlHandle, _coincenterInfo, _exchangeInfo, mk, depth); + MarketOrderBookMap marketOrderBookMap = GetOrderbooks(_curlHandle, _coincenterInfo, _exchangeConfig, mk, depth); auto it = marketOrderBookMap.find(mk); if (it == marketOrderBookMap.end()) { throw exception("Cannot find {} in market order book map", mk); diff --git a/src/api/exchanges/src/huobiprivateapi.cpp b/src/api/exchanges/src/huobiprivateapi.cpp index a8530693..c6c5efb6 100644 --- a/src/api/exchanges/src/huobiprivateapi.cpp +++ b/src/api/exchanges/src/huobiprivateapi.cpp @@ -118,15 +118,15 @@ HuobiPrivate::HuobiPrivate(const CoincenterInfo& coincenterInfo, HuobiPublic& hu : ExchangePrivate(coincenterInfo, huobiPublic, apiKey), _curlHandle(HuobiPublic::kURLBases, coincenterInfo.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(exchangeInfo().privateAPIRate()) - .setAcceptedEncoding(exchangeInfo().acceptEncoding()) - .setRequestCallLogLevel(exchangeInfo().requestsCallLogLevel()) - .setRequestAnswerLogLevel(exchangeInfo().requestsAnswerLogLevel()) + .setMinDurationBetweenQueries(exchangeConfig().privateAPIRate()) + .setAcceptedEncoding(exchangeConfig().acceptEncoding()) + .setRequestCallLogLevel(exchangeConfig().requestsCallLogLevel()) + .setRequestAnswerLogLevel(exchangeConfig().requestsAnswerLogLevel()) .build(), coincenterInfo.getRunMode()), _accountIdCache(CachedResultOptions(std::chrono::hours(96), _cachedResultVault), _curlHandle, apiKey), _depositWalletsCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kDepositWallet), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kDepositWallet), _cachedResultVault), _curlHandle, _apiKey, huobiPublic) {} bool HuobiPrivate::validateApiKey() { @@ -168,7 +168,7 @@ Wallet HuobiPrivate::DepositWalletFunc::operator()(CurrencyCode currencyCode) { std::string_view tag; ExchangeName exchangeName(_huobiPublic.name(), _apiKey.name()); const CoincenterInfo& coincenterInfo = _huobiPublic.coincenterInfo(); - bool doCheckWallet = coincenterInfo.exchangeInfo(_huobiPublic.name()).validateDepositAddressesInFile(); + bool doCheckWallet = coincenterInfo.exchangeConfig(_huobiPublic.name()).validateDepositAddressesInFile(); WalletCheck walletCheck(coincenterInfo.dataDir(), doCheckWallet); for (json& depositDetail : data) { tag = depositDetail["addressTag"].get(); @@ -469,7 +469,7 @@ PlaceOrderInfo HuobiPrivate::placeOrder(MonetaryAmount from, MonetaryAmount volu const Market mk = tradeInfo.tradeContext.mk; string lowerCaseMarket = mk.assetsPairStrLower(); - const bool placeSimulatedRealOrder = _exchangePublic.exchangeInfo().placeSimulateRealOrder(); + const bool placeSimulatedRealOrder = _exchangePublic.exchangeConfig().placeSimulateRealOrder(); const bool isTakerStrategy = tradeInfo.options.isTakerStrategy(placeSimulatedRealOrder); std::string_view type; if (isTakerStrategy) { diff --git a/src/api/exchanges/src/huobipublicapi.cpp b/src/api/exchanges/src/huobipublicapi.cpp index 9d74bea4..792b1a23 100644 --- a/src/api/exchanges/src/huobipublicapi.cpp +++ b/src/api/exchanges/src/huobipublicapi.cpp @@ -82,31 +82,32 @@ json PublicQuery(CurlHandle& curlHandle, std::string_view endpoint, const CurlPo HuobiPublic::HuobiPublic(const CoincenterInfo& config, FiatConverter& fiatConverter, api::CommonAPI& commonAPI) : ExchangePublic("huobi", fiatConverter, commonAPI, config), - _exchangeInfo(config.exchangeInfo(_name)), + _exchangeConfig(config.exchangeConfig(_name)), _curlHandle(kURLBases, config.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(_exchangeInfo.publicAPIRate()) - .setAcceptedEncoding(_exchangeInfo.acceptEncoding()) - .setRequestCallLogLevel(_exchangeInfo.requestsCallLogLevel()) - .setRequestAnswerLogLevel(_exchangeInfo.requestsAnswerLogLevel()) + .setMinDurationBetweenQueries(_exchangeConfig.publicAPIRate()) + .setAcceptedEncoding(_exchangeConfig.acceptEncoding()) + .setRequestCallLogLevel(_exchangeConfig.requestsCallLogLevel()) + .setRequestAnswerLogLevel(_exchangeConfig.requestsAnswerLogLevel()) .build(), config.getRunMode()), _healthCheckCurlHandle( kHealthCheckBaseUrl, config.metricGatewayPtr(), - PermanentCurlOptions::Builder().setMinDurationBetweenQueries(_exchangeInfo.publicAPIRate()).build(), + PermanentCurlOptions::Builder().setMinDurationBetweenQueries(_exchangeConfig.publicAPIRate()).build(), config.getRunMode()), _tradableCurrenciesCache( - CachedResultOptions(_exchangeInfo.getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), _curlHandle), - _marketsCache(CachedResultOptions(_exchangeInfo.getAPICallUpdateFrequency(kMarkets), _cachedResultVault), - _curlHandle, _exchangeInfo), + CachedResultOptions(_exchangeConfig.getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), _curlHandle), + _marketsCache(CachedResultOptions(_exchangeConfig.getAPICallUpdateFrequency(kMarkets), _cachedResultVault), + _curlHandle, _exchangeConfig), _allOrderBooksCache( - CachedResultOptions(_exchangeInfo.getAPICallUpdateFrequency(kAllOrderBooks), _cachedResultVault), - _marketsCache, _curlHandle, _exchangeInfo), - _orderbookCache(CachedResultOptions(_exchangeInfo.getAPICallUpdateFrequency(kOrderBook), _cachedResultVault), - _curlHandle, _exchangeInfo), + CachedResultOptions(_exchangeConfig.getAPICallUpdateFrequency(kAllOrderBooks), _cachedResultVault), + _marketsCache, _curlHandle, _exchangeConfig), + _orderbookCache(CachedResultOptions(_exchangeConfig.getAPICallUpdateFrequency(kOrderBook), _cachedResultVault), + _curlHandle, _exchangeConfig), _tradedVolumeCache( - CachedResultOptions(_exchangeInfo.getAPICallUpdateFrequency(kTradedVolume), _cachedResultVault), _curlHandle), - _tickerCache(CachedResultOptions(_exchangeInfo.getAPICallUpdateFrequency(kLastPrice), _cachedResultVault), + CachedResultOptions(_exchangeConfig.getAPICallUpdateFrequency(kTradedVolume), _cachedResultVault), + _curlHandle), + _tickerCache(CachedResultOptions(_exchangeConfig.getAPICallUpdateFrequency(kLastPrice), _cachedResultVault), _curlHandle) {} bool HuobiPublic::healthCheck() { @@ -210,7 +211,7 @@ std::pair HuobiPublic::Marke markets.reserve(static_cast(result.size())); - const CurrencyCodeSet& excludedCurrencies = _exchangeInfo.excludedCurrenciesAll(); + const CurrencyCodeSet& excludedCurrencies = _exchangeConfig.excludedCurrenciesAll(); for (const json& marketDetails : result) { std::string_view baseAsset = marketDetails["base-currency"].get(); diff --git a/src/api/exchanges/src/krakenprivateapi.cpp b/src/api/exchanges/src/krakenprivateapi.cpp index d927cbfc..c042fc0c 100644 --- a/src/api/exchanges/src/krakenprivateapi.cpp +++ b/src/api/exchanges/src/krakenprivateapi.cpp @@ -32,7 +32,7 @@ #include "deposit.hpp" #include "depositsconstraints.hpp" #include "durationstring.hpp" -#include "exchangeinfo.hpp" +#include "exchangeconfig.hpp" #include "exchangename.hpp" #include "exchangeprivateapi.hpp" #include "exchangeprivateapitypes.hpp" @@ -137,14 +137,14 @@ KrakenPrivate::KrakenPrivate(const CoincenterInfo& config, KrakenPublic& krakenP : ExchangePrivate(config, krakenPublic, apiKey), _curlHandle(KrakenPublic::kUrlBase, config.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(exchangeInfo().privateAPIRate()) - .setAcceptedEncoding(exchangeInfo().acceptEncoding()) - .setRequestCallLogLevel(exchangeInfo().requestsCallLogLevel()) - .setRequestAnswerLogLevel(exchangeInfo().requestsAnswerLogLevel()) + .setMinDurationBetweenQueries(exchangeConfig().privateAPIRate()) + .setAcceptedEncoding(exchangeConfig().acceptEncoding()) + .setRequestCallLogLevel(exchangeConfig().requestsCallLogLevel()) + .setRequestAnswerLogLevel(exchangeConfig().requestsAnswerLogLevel()) .build(), config.getRunMode()), _depositWalletsCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kDepositWallet), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kDepositWallet), _cachedResultVault), _curlHandle, _apiKey, krakenPublic) {} bool KrakenPrivate::validateApiKey() { @@ -231,7 +231,7 @@ Wallet KrakenPrivate::DepositWalletFunc::operator()(CurrencyCode currencyCode) { } const CoincenterInfo& coincenterInfo = _exchangePublic.coincenterInfo(); - bool doCheckWallet = coincenterInfo.exchangeInfo(_exchangePublic.name()).validateDepositAddressesInFile(); + bool doCheckWallet = coincenterInfo.exchangeConfig(_exchangePublic.name()).validateDepositAddressesInFile(); WalletCheck walletCheck(coincenterInfo.dataDir(), doCheckWallet); string address; string tag; @@ -460,7 +460,7 @@ PlaceOrderInfo KrakenPrivate::placeOrder([[maybe_unused]] MonetaryAmount from, M const CurrencyCode fromCurrencyCode(tradeInfo.tradeContext.fromCur()); const CurrencyCode toCurrencyCode(tradeInfo.tradeContext.toCur()); const bool isTakerStrategy = - tradeInfo.options.isTakerStrategy(_exchangePublic.exchangeInfo().placeSimulateRealOrder()); + tradeInfo.options.isTakerStrategy(_exchangePublic.exchangeConfig().placeSimulateRealOrder()); const bool isSimulation = tradeInfo.options.isSimulation(); const Market mk = tradeInfo.tradeContext.mk; KrakenPublic& krakenPublic = dynamic_cast(_exchangePublic); diff --git a/src/api/exchanges/src/krakenpublicapi.cpp b/src/api/exchanges/src/krakenpublicapi.cpp index dc46b6b4..e1872c5f 100644 --- a/src/api/exchanges/src/krakenpublicapi.cpp +++ b/src/api/exchanges/src/krakenpublicapi.cpp @@ -109,32 +109,32 @@ KrakenPublic::KrakenPublic(const CoincenterInfo& config, FiatConverter& fiatConv : ExchangePublic(kExchangeName, fiatConverter, commonAPI, config), _curlHandle(kUrlBase, config.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(exchangeInfo().publicAPIRate()) - .setAcceptedEncoding(exchangeInfo().acceptEncoding()) - .setRequestCallLogLevel(exchangeInfo().requestsCallLogLevel()) - .setRequestAnswerLogLevel(exchangeInfo().requestsAnswerLogLevel()) + .setMinDurationBetweenQueries(exchangeConfig().publicAPIRate()) + .setAcceptedEncoding(exchangeConfig().acceptEncoding()) + .setRequestCallLogLevel(exchangeConfig().requestsCallLogLevel()) + .setRequestAnswerLogLevel(exchangeConfig().requestsAnswerLogLevel()) .build(), config.getRunMode()), _tradableCurrenciesCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), config, - commonAPI, _curlHandle, exchangeInfo()), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), config, + commonAPI, _curlHandle, exchangeConfig()), _withdrawalFeesCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), config, - exchangeInfo().publicAPIRate()), - _marketsCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kMarkets), _cachedResultVault), - _tradableCurrenciesCache, config, _curlHandle, exchangeInfo()), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), config, + exchangeConfig().publicAPIRate()), + _marketsCache(CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kMarkets), _cachedResultVault), + _tradableCurrenciesCache, config, _curlHandle, exchangeConfig()), _allOrderBooksCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kAllOrderBooks), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kAllOrderBooks), _cachedResultVault), _tradableCurrenciesCache, _marketsCache, config, _curlHandle), - _orderBookCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kOrderBook), _cachedResultVault), + _orderBookCache(CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kOrderBook), _cachedResultVault), _tradableCurrenciesCache, _marketsCache, _curlHandle), - _tickerCache(CachedResultOptions(std::min(exchangeInfo().getAPICallUpdateFrequency(kTradedVolume), - exchangeInfo().getAPICallUpdateFrequency(kLastPrice)), + _tickerCache(CachedResultOptions(std::min(exchangeConfig().getAPICallUpdateFrequency(kTradedVolume), + exchangeConfig().getAPICallUpdateFrequency(kLastPrice)), _cachedResultVault), _tradableCurrenciesCache, _curlHandle) { json data = GetKrakenWithdrawInfoFile(_coincenterInfo.dataDir()).readAllJson(); if (!data.empty()) { - Duration withdrawDataRefreshTime = exchangeInfo().getAPICallUpdateFrequency(kWithdrawalFees); + Duration withdrawDataRefreshTime = exchangeConfig().getAPICallUpdateFrequency(kWithdrawalFees); TimePoint lastUpdatedTime(TimeInS(data["timeepoch"].get())); if (Clock::now() < lastUpdatedTime + withdrawDataRefreshTime) { // we can reuse file data @@ -198,13 +198,13 @@ KrakenPublic::WithdrawalFeesFunc::WithdrawalFeesFunc(const CoincenterInfo& coinc : _curlHandle1(kUrlWithdrawFee1, coincenterInfo.metricGatewayPtr(), PermanentCurlOptions::Builder() .setMinDurationBetweenQueries(minDurationBetweenQueries) - .setAcceptedEncoding(coincenterInfo.exchangeInfo(kExchangeName).acceptEncoding()) + .setAcceptedEncoding(coincenterInfo.exchangeConfig(kExchangeName).acceptEncoding()) .build(), coincenterInfo.getRunMode()), _curlHandle2(kUrlWithdrawFee2, coincenterInfo.metricGatewayPtr(), PermanentCurlOptions::Builder() .setMinDurationBetweenQueries(minDurationBetweenQueries) - .setAcceptedEncoding(coincenterInfo.exchangeInfo(kExchangeName).acceptEncoding()) + .setAcceptedEncoding(coincenterInfo.exchangeConfig(kExchangeName).acceptEncoding()) .build(), coincenterInfo.getRunMode()) {} @@ -362,7 +362,7 @@ KrakenPublic::WithdrawalFeesFunc::WithdrawalInfoMaps KrakenPublic::WithdrawalFee CurrencyExchangeFlatSet KrakenPublic::TradableCurrenciesFunc::operator()() { json result = PublicQuery(_curlHandle, "/public/Assets"); CurrencyExchangeVector currencies; - const CurrencyCodeSet& excludedCurrencies = _exchangeInfo.excludedCurrenciesAll(); + const CurrencyCodeSet& excludedCurrencies = _exchangeConfig.excludedCurrenciesAll(); for (const auto& [krakenAssetName, value] : result.items()) { std::string_view altCodeStr = value["altname"].get(); if (!CheckCurrencyExchange(krakenAssetName, altCodeStr, excludedCurrencies, _coincenterInfo)) { @@ -387,7 +387,7 @@ std::pair KrakenPublic::Mar std::pair ret; ret.first.reserve(static_cast(result.size())); ret.second.reserve(result.size()); - const CurrencyCodeSet& excludedCurrencies = _exchangeInfo.excludedCurrenciesAll(); + const CurrencyCodeSet& excludedCurrencies = _exchangeConfig.excludedCurrenciesAll(); const CurrencyExchangeFlatSet& currencies = _tradableCurrenciesCache.get(); for (const auto& [key, value] : result.items()) { if (!value.contains("ordermin")) { diff --git a/src/api/exchanges/src/kucoinprivateapi.cpp b/src/api/exchanges/src/kucoinprivateapi.cpp index c4ed476a..c924268c 100644 --- a/src/api/exchanges/src/kucoinprivateapi.cpp +++ b/src/api/exchanges/src/kucoinprivateapi.cpp @@ -26,7 +26,7 @@ #include "currencycode.hpp" #include "deposit.hpp" #include "depositsconstraints.hpp" -#include "exchangeinfo.hpp" +#include "exchangeconfig.hpp" #include "exchangename.hpp" #include "exchangeprivateapi.hpp" #include "exchangeprivateapitypes.hpp" @@ -160,14 +160,14 @@ KucoinPrivate::KucoinPrivate(const CoincenterInfo& coincenterInfo, KucoinPublic& : ExchangePrivate(coincenterInfo, kucoinPublic, apiKey), _curlHandle(KucoinPublic::kUrlBase, coincenterInfo.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(exchangeInfo().privateAPIRate()) - .setAcceptedEncoding(exchangeInfo().acceptEncoding()) - .setRequestCallLogLevel(exchangeInfo().requestsCallLogLevel()) - .setRequestAnswerLogLevel(exchangeInfo().requestsAnswerLogLevel()) + .setMinDurationBetweenQueries(exchangeConfig().privateAPIRate()) + .setAcceptedEncoding(exchangeConfig().acceptEncoding()) + .setRequestCallLogLevel(exchangeConfig().requestsCallLogLevel()) + .setRequestAnswerLogLevel(exchangeConfig().requestsAnswerLogLevel()) .build(), coincenterInfo.getRunMode()), _depositWalletsCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kDepositWallet), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kDepositWallet), _cachedResultVault), _curlHandle, _apiKey, kucoinPublic) {} bool KucoinPrivate::validateApiKey() { @@ -212,7 +212,7 @@ Wallet KucoinPrivate::DepositWalletFunc::operator()(CurrencyCode currencyCode) { std::string_view tag = (memoIt != result.end() && !memoIt->is_null()) ? memoIt->get() : ""; const CoincenterInfo& coincenterInfo = _kucoinPublic.coincenterInfo(); - bool doCheckWallet = coincenterInfo.exchangeInfo(_kucoinPublic.name()).validateDepositAddressesInFile(); + bool doCheckWallet = coincenterInfo.exchangeConfig(_kucoinPublic.name()).validateDepositAddressesInFile(); WalletCheck walletCheck(coincenterInfo.dataDir(), doCheckWallet); Wallet wallet(std::move(exchangeName), currencyCode, std::move(result["address"].get_ref()), tag, @@ -452,7 +452,7 @@ PlaceOrderInfo KucoinPrivate::placeOrder(MonetaryAmount from, MonetaryAmount vol const Market mk = tradeInfo.tradeContext.mk; - bool isTakerStrategy = tradeInfo.options.isTakerStrategy(_exchangePublic.exchangeInfo().placeSimulateRealOrder()); + bool isTakerStrategy = tradeInfo.options.isTakerStrategy(_exchangePublic.exchangeConfig().placeSimulateRealOrder()); KucoinPublic& kucoinPublic = dynamic_cast(_exchangePublic); diff --git a/src/api/exchanges/src/kucoinpublicapi.cpp b/src/api/exchanges/src/kucoinpublicapi.cpp index 282968ee..0e5608bd 100644 --- a/src/api/exchanges/src/kucoinpublicapi.cpp +++ b/src/api/exchanges/src/kucoinpublicapi.cpp @@ -66,26 +66,26 @@ KucoinPublic::KucoinPublic(const CoincenterInfo& config, FiatConverter& fiatConv : ExchangePublic("kucoin", fiatConverter, commonAPI, config), _curlHandle(kUrlBase, config.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(exchangeInfo().publicAPIRate()) - .setAcceptedEncoding(exchangeInfo().acceptEncoding()) - .setRequestCallLogLevel(exchangeInfo().requestsCallLogLevel()) - .setRequestAnswerLogLevel(exchangeInfo().requestsAnswerLogLevel()) + .setMinDurationBetweenQueries(exchangeConfig().publicAPIRate()) + .setAcceptedEncoding(exchangeConfig().acceptEncoding()) + .setRequestCallLogLevel(exchangeConfig().requestsCallLogLevel()) + .setRequestAnswerLogLevel(exchangeConfig().requestsAnswerLogLevel()) .build(), config.getRunMode()), _tradableCurrenciesCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), _curlHandle, + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), _curlHandle, _coincenterInfo, commonAPI), - _marketsCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kMarkets), _cachedResultVault), - _curlHandle, exchangeInfo()), + _marketsCache(CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kMarkets), _cachedResultVault), + _curlHandle, exchangeConfig()), _allOrderBooksCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kAllOrderBooks), _cachedResultVault), - _marketsCache, _curlHandle, exchangeInfo()), - _orderbookCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kOrderBook), _cachedResultVault), - _curlHandle, exchangeInfo()), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kAllOrderBooks), _cachedResultVault), + _marketsCache, _curlHandle, exchangeConfig()), + _orderbookCache(CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kOrderBook), _cachedResultVault), + _curlHandle, exchangeConfig()), _tradedVolumeCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kTradedVolume), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kTradedVolume), _cachedResultVault), _curlHandle), - _tickerCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kLastPrice), _cachedResultVault), + _tickerCache(CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kLastPrice), _cachedResultVault), _curlHandle) {} bool KucoinPublic::healthCheck() { @@ -146,7 +146,7 @@ std::pair KucoinPublic::Mar markets.reserve(static_cast(result.size())); - const CurrencyCodeSet& excludedCurrencies = _exchangeInfo.excludedCurrenciesAll(); + const CurrencyCodeSet& excludedCurrencies = _exchangeConfig.excludedCurrenciesAll(); for (const json& marketDetails : result) { const std::string_view baseAsset = marketDetails["baseCurrency"].get(); diff --git a/src/api/exchanges/src/upbitprivateapi.cpp b/src/api/exchanges/src/upbitprivateapi.cpp index eed75051..b53011d6 100644 --- a/src/api/exchanges/src/upbitprivateapi.cpp +++ b/src/api/exchanges/src/upbitprivateapi.cpp @@ -33,7 +33,7 @@ #include "deposit.hpp" #include "depositsconstraints.hpp" #include "durationstring.hpp" -#include "exchangeinfo.hpp" +#include "exchangeconfig.hpp" #include "exchangename.hpp" #include "exchangeprivateapi.hpp" #include "exchangeprivateapitypes.hpp" @@ -110,20 +110,20 @@ UpbitPrivate::UpbitPrivate(const CoincenterInfo& config, UpbitPublic& upbitPubli : ExchangePrivate(config, upbitPublic, apiKey), _curlHandle(UpbitPublic::kUrlBase, config.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(exchangeInfo().privateAPIRate()) - .setAcceptedEncoding(exchangeInfo().acceptEncoding()) - .setRequestCallLogLevel(exchangeInfo().requestsCallLogLevel()) - .setRequestAnswerLogLevel(exchangeInfo().requestsAnswerLogLevel()) + .setMinDurationBetweenQueries(exchangeConfig().privateAPIRate()) + .setAcceptedEncoding(exchangeConfig().acceptEncoding()) + .setRequestCallLogLevel(exchangeConfig().requestsCallLogLevel()) + .setRequestAnswerLogLevel(exchangeConfig().requestsAnswerLogLevel()) .build(), config.getRunMode()), _tradableCurrenciesCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), _curlHandle, - _apiKey, exchangeInfo(), upbitPublic._commonApi), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), _curlHandle, + _apiKey, exchangeConfig(), upbitPublic._commonApi), _depositWalletsCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kDepositWallet), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kDepositWallet), _cachedResultVault), _curlHandle, _apiKey, upbitPublic), _withdrawalFeesCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), _curlHandle, _apiKey, upbitPublic) {} bool UpbitPrivate::validateApiKey() { @@ -133,7 +133,7 @@ bool UpbitPrivate::validateApiKey() { } CurrencyExchangeFlatSet UpbitPrivate::TradableCurrenciesFunc::operator()() { - const CurrencyCodeSet& excludedCurrencies = _exchangeInfo.excludedCurrenciesAll(); + const CurrencyCodeSet& excludedCurrencies = _exchangeConfig.excludedCurrenciesAll(); CurrencyExchangeVector currencies; json result = PrivateQuery(_curlHandle, _apiKey, HttpRequestType::kGet, "/v1/status/wallet"); for (const json& curDetails : result) { @@ -238,7 +238,7 @@ Wallet UpbitPrivate::DepositWalletFunc::operator()(CurrencyCode currencyCode) { } const CoincenterInfo& coincenterInfo = _exchangePublic.coincenterInfo(); - bool doCheckWallet = coincenterInfo.exchangeInfo(_exchangePublic.name()).validateDepositAddressesInFile(); + bool doCheckWallet = coincenterInfo.exchangeConfig(_exchangePublic.name()).validateDepositAddressesInFile(); WalletCheck walletCheck(coincenterInfo.dataDir(), doCheckWallet); Wallet wallet(ExchangeName(_exchangePublic.name(), _apiKey.name()), currencyCode, std::move(addressIt->get_ref()), tag, walletCheck, _apiKey.accountOwner()); @@ -499,12 +499,13 @@ void UpbitPrivate::applyFee(Market mk, CurrencyCode fromCurrencyCode, bool isTak MonetaryAmount& volume) { if (fromCurrencyCode == mk.quote()) { // For 'buy', from amount is fee excluded - ExchangeInfo::FeeType feeType = isTakerStrategy ? ExchangeInfo::FeeType::kTaker : ExchangeInfo::FeeType::kMaker; - const ExchangeInfo& exchangeInfo = _coincenterInfo.exchangeInfo(_exchangePublic.name()); + ExchangeConfig::FeeType feeType = + isTakerStrategy ? ExchangeConfig::FeeType::kTaker : ExchangeConfig::FeeType::kMaker; + const ExchangeConfig& exchangeConfig = _coincenterInfo.exchangeConfig(_exchangePublic.name()); if (isTakerStrategy) { - from = exchangeInfo.applyFee(from, feeType); + from = exchangeConfig.applyFee(from, feeType); } else { - volume = exchangeInfo.applyFee(volume, feeType); + volume = exchangeConfig.applyFee(volume, feeType); } } } @@ -513,7 +514,7 @@ PlaceOrderInfo UpbitPrivate::placeOrder(MonetaryAmount from, MonetaryAmount volu const TradeInfo& tradeInfo) { const CurrencyCode fromCurrencyCode(tradeInfo.tradeContext.fromCur()); const CurrencyCode toCurrencyCode(tradeInfo.tradeContext.toCur()); - const bool placeSimulatedRealOrder = _exchangePublic.exchangeInfo().placeSimulateRealOrder(); + const bool placeSimulatedRealOrder = _exchangePublic.exchangeConfig().placeSimulateRealOrder(); const bool isTakerStrategy = tradeInfo.options.isTakerStrategy(placeSimulatedRealOrder); const Market mk = tradeInfo.tradeContext.mk; diff --git a/src/api/exchanges/src/upbitpublicapi.cpp b/src/api/exchanges/src/upbitpublicapi.cpp index cc4b20ba..7fa5231c 100644 --- a/src/api/exchanges/src/upbitpublicapi.cpp +++ b/src/api/exchanges/src/upbitpublicapi.cpp @@ -61,29 +61,29 @@ UpbitPublic::UpbitPublic(const CoincenterInfo& config, FiatConverter& fiatConver : ExchangePublic("upbit", fiatConverter, commonAPI, config), _curlHandle(kUrlBase, config.metricGatewayPtr(), PermanentCurlOptions::Builder() - .setMinDurationBetweenQueries(exchangeInfo().publicAPIRate()) - .setAcceptedEncoding(exchangeInfo().acceptEncoding()) - .setRequestCallLogLevel(exchangeInfo().requestsCallLogLevel()) - .setRequestAnswerLogLevel(exchangeInfo().requestsAnswerLogLevel()) + .setMinDurationBetweenQueries(exchangeConfig().publicAPIRate()) + .setAcceptedEncoding(exchangeConfig().acceptEncoding()) + .setRequestCallLogLevel(exchangeConfig().requestsCallLogLevel()) + .setRequestAnswerLogLevel(exchangeConfig().requestsAnswerLogLevel()) .build(), config.getRunMode()), - _marketsCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kMarkets), _cachedResultVault), - _curlHandle, exchangeInfo()), + _marketsCache(CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kMarkets), _cachedResultVault), + _curlHandle, exchangeConfig()), _tradableCurrenciesCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), _curlHandle, + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), _curlHandle, _marketsCache), _withdrawalFeesCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), _name, + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kWithdrawalFees), _cachedResultVault), _name, config.dataDir()), _allOrderBooksCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kAllOrderBooks), _cachedResultVault), - _curlHandle, exchangeInfo(), _marketsCache), - _orderbookCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kOrderBook), _cachedResultVault), - _curlHandle, exchangeInfo()), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kAllOrderBooks), _cachedResultVault), + _curlHandle, exchangeConfig(), _marketsCache), + _orderbookCache(CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kOrderBook), _cachedResultVault), + _curlHandle, exchangeConfig()), _tradedVolumeCache( - CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kTradedVolume), _cachedResultVault), + CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kTradedVolume), _cachedResultVault), _curlHandle), - _tickerCache(CachedResultOptions(exchangeInfo().getAPICallUpdateFrequency(kLastPrice), _cachedResultVault), + _tickerCache(CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kLastPrice), _cachedResultVault), _curlHandle) {} bool UpbitPublic::healthCheck() { @@ -131,7 +131,7 @@ bool UpbitPublic::CheckCurrencyCode(CurrencyCode standardCode, const CurrencyCod MarketSet UpbitPublic::MarketsFunc::operator()() { json result = PublicQuery(_curlHandle, "/v1/market/all", {{"isDetails", "true"}}); - const CurrencyCodeSet& excludedCurrencies = _exchangeInfo.excludedCurrenciesAll(); + const CurrencyCodeSet& excludedCurrencies = _exchangeConfig.excludedCurrenciesAll(); MarketSet ret; ret.reserve(static_cast(result.size())); for (const json& marketDetails : result) { diff --git a/src/api/interface/include/exchange.hpp b/src/api/interface/include/exchange.hpp index c5939398..9d561f78 100644 --- a/src/api/interface/include/exchange.hpp +++ b/src/api/interface/include/exchange.hpp @@ -7,7 +7,7 @@ #include "currencycode.hpp" #include "currencyexchange.hpp" #include "currencyexchangeflatset.hpp" -#include "exchangeinfo.hpp" +#include "exchangeconfig.hpp" #include "exchangename.hpp" #include "exchangeprivateapi.hpp" #include "exchangepublicapi.hpp" @@ -22,10 +22,10 @@ class Exchange { using ExchangePublic = api::ExchangePublic; /// Builds a Exchange without private exchange. All private requests will be forbidden. - Exchange(const ExchangeInfo &exchangeInfo, api::ExchangePublic &exchangePublic); + Exchange(const ExchangeConfig &exchangeConfig, api::ExchangePublic &exchangePublic); /// Build a Exchange with both private and public exchanges - Exchange(const ExchangeInfo &exchangeInfo, api::ExchangePublic &exchangePublic, + Exchange(const ExchangeConfig &exchangeConfig, api::ExchangePublic &exchangePublic, api::ExchangePrivate &exchangePrivate); std::string_view name() const { return _exchangePublic.name(); } @@ -55,7 +55,7 @@ class Exchange { throw exception("No private key associated to exchange {}", name()); } - const ExchangeInfo &exchangeInfo() const { return _exchangeInfo; } + const ExchangeConfig &exchangeConfig() const { return _exchangeConfig; } bool hasPrivateAPI() const { return _pExchangePrivate != nullptr; } @@ -113,6 +113,6 @@ class Exchange { private: api::ExchangePublic &_exchangePublic; api::ExchangePrivate *_pExchangePrivate = nullptr; - const ExchangeInfo &_exchangeInfo; + const ExchangeConfig &_exchangeConfig; }; } // namespace cct diff --git a/src/api/interface/src/exchange.cpp b/src/api/interface/src/exchange.cpp index da7a8787..b6ed7dd8 100644 --- a/src/api/interface/src/exchange.cpp +++ b/src/api/interface/src/exchange.cpp @@ -5,23 +5,23 @@ #include "cct_log.hpp" #include "currencycode.hpp" #include "currencyexchangeflatset.hpp" -#include "exchangeinfo.hpp" +#include "exchangeconfig.hpp" #include "exchangeprivateapi.hpp" #include "exchangepublicapi.hpp" namespace cct { -Exchange::Exchange(const ExchangeInfo &exchangeInfo, api::ExchangePublic &exchangePublic, +Exchange::Exchange(const ExchangeConfig &exchangeConfig, api::ExchangePublic &exchangePublic, api::ExchangePrivate &exchangePrivate) : _exchangePublic(exchangePublic), _pExchangePrivate(std::addressof(exchangePrivate)), - _exchangeInfo(exchangeInfo) {} + _exchangeConfig(exchangeConfig) {} -Exchange::Exchange(const ExchangeInfo &exchangeInfo, api::ExchangePublic &exchangePublic) - : _exchangePublic(exchangePublic), _exchangeInfo(exchangeInfo) {} +Exchange::Exchange(const ExchangeConfig &exchangeConfig, api::ExchangePublic &exchangePublic) + : _exchangePublic(exchangePublic), _exchangeConfig(exchangeConfig) {} bool Exchange::canWithdraw(CurrencyCode currencyCode, const CurrencyExchangeFlatSet ¤cyExchangeSet) const { - if (_exchangeInfo.excludedCurrenciesWithdrawal().contains(currencyCode)) { + if (_exchangeConfig.excludedCurrenciesWithdrawal().contains(currencyCode)) { return false; } auto lb = currencyExchangeSet.find(currencyCode); diff --git a/src/api/interface/src/exchangepool.cpp b/src/api/interface/src/exchangepool.cpp index 11c8cbab..1d04d5ef 100644 --- a/src/api/interface/src/exchangepool.cpp +++ b/src/api/interface/src/exchangepool.cpp @@ -50,7 +50,7 @@ ExchangePool::ExchangePool(const CoincenterInfo& coincenterInfo, FiatConverter& } const bool canUsePrivateExchange = _apiKeyProvider.contains(exchangeStr); - const ExchangeInfo& exchangeInfo = _coincenterInfo.exchangeInfo(exchangePublic->name()); + const ExchangeConfig& exchangeConfig = _coincenterInfo.exchangeConfig(exchangePublic->name()); if (canUsePrivateExchange) { for (std::string_view keyName : _apiKeyProvider.getKeyNames(exchangeStr)) { api::ExchangePrivate* exchangePrivate; @@ -72,7 +72,7 @@ ExchangePool::ExchangePool(const CoincenterInfo& coincenterInfo, FiatConverter& throw exception("Unsupported platform {}", exchangeStr); } - if (exchangeInfo.shouldValidateApiKey()) { + if (exchangeConfig.shouldValidateApiKey()) { if (exchangePrivate->validateApiKey()) { log::info("{} api key is valid", exchangeName); } else { @@ -81,10 +81,10 @@ ExchangePool::ExchangePool(const CoincenterInfo& coincenterInfo, FiatConverter& } } - _exchanges.emplace_back(exchangeInfo, *exchangePublic, *exchangePrivate); + _exchanges.emplace_back(exchangeConfig, *exchangePublic, *exchangePrivate); } } else { - _exchanges.emplace_back(exchangeInfo, *exchangePublic); + _exchanges.emplace_back(exchangeConfig, *exchangePublic); } } _exchanges.shrink_to_fit(); diff --git a/src/engine/include/coincenteroptions.hpp b/src/engine/include/coincenteroptions.hpp index d2fe2794..7a11cf91 100644 --- a/src/engine/include/coincenteroptions.hpp +++ b/src/engine/include/coincenteroptions.hpp @@ -10,6 +10,7 @@ #include "commandlineoption.hpp" #include "exchangepublicapi.hpp" #include "timedef.hpp" +#include "tradedefinitions.hpp" #include "tradeoptions.hpp" #include "withdrawoptions.hpp" @@ -62,8 +63,8 @@ class CoincenterCmdLineOptions { std::string_view tradeAll; std::string_view tradePrice; std::string_view tradeStrategy; - Duration tradeTimeout{TradeOptions().maxTradeTime()}; - Duration tradeUpdatePrice{TradeOptions().minTimeBetweenPriceUpdates()}; + Duration tradeTimeout = kUndefinedDuration; + Duration tradeUpdatePrice = kUndefinedDuration; std::string_view buy; std::string_view sell; @@ -79,8 +80,8 @@ class CoincenterCmdLineOptions { std::optional recentWithdrawsInfo; std::string_view ids; - Duration minAge{}; - Duration maxAge{}; + Duration minAge = kUndefinedDuration; + Duration maxAge = kUndefinedDuration; std::string_view withdrawApply; std::string_view withdrawApplyAll; @@ -102,6 +103,7 @@ class CoincenterCmdLineOptions { bool forceMultiTrade = false; bool forceSingleTrade = false; bool tradeTimeoutMatch = false; + bool tradeTimeoutCancel = false; bool tradeSim{TradeOptions().isSimulation()}; bool async = false; bool help = false; @@ -115,6 +117,7 @@ class CoincenterCmdLineOptions { static std::string_view SelectDefaultDataDir() noexcept; TradeTypePolicy computeTradeTypePolicy() const; + TradeTimeoutAction computeTradeTimeoutAction() const; }; } // namespace cct diff --git a/src/engine/include/coincenteroptionsdef.hpp b/src/engine/include/coincenteroptionsdef.hpp index d7a8760f..7aeaafcc 100644 --- a/src/engine/include/coincenteroptionsdef.hpp +++ b/src/engine/include/coincenteroptionsdef.hpp @@ -8,7 +8,7 @@ #include "apioutputtype.hpp" #include "cct_const.hpp" #include "commandlineoption.hpp" -#include "exchangeinfomap.hpp" +#include "exchangeconfigmap.hpp" #include "exchangepublicapi.hpp" #include "loadconfiguration.hpp" #include "static_string_view_helpers.hpp" @@ -25,10 +25,6 @@ class CoincenterCmdLineOptionsDefinitions { static constexpr int kDefaultMonitoringPort = 9091; // Prometheus default push port static constexpr Duration kDefaultRepeatTime = TimeInS(1); - static constexpr int64_t kDefaultTradeTimeoutSeconds = - std::chrono::duration_cast(TradeOptions().maxTradeTime()).count(); - static constexpr int64_t kMinUpdatePriceTimeSeconds = - std::chrono::duration_cast(TradeOptions().minTimeBetweenPriceUpdates()).count(); static constexpr int64_t kDefaultRepeatDurationSeconds = std::chrono::duration_cast(kDefaultRepeatTime).count(); @@ -73,18 +69,31 @@ class CoincenterCmdLineOptionsDefinitions { JoinStringView_v; - static constexpr std::string_view kTradeTimeout1 = "Adjust trade timeout (default: "; - static constexpr std::string_view kTradeTimeout2 = "s). Remaining orders will be cancelled after the timeout."; + static constexpr std::string_view kTradeStrategy1 = + "Customize the order price strategy of the trade\n" + " 'maker' : order price set at limit price\n" + " 'nibble': order price set at limit price +(buy)/-(sell) 1\n" + " 'taker' : order price will be at market price and matched immediately\n" + "Default strategy can be configured in "; + static constexpr std::string_view kTradeStrategy2 = + ".\nOrder price will be continuously updated and recomputed every '--update-price' step time.\n" + "This option is not compatible with '--price'"; + static constexpr std::string_view kTradeStrategy = + JoinStringView_v; + + static constexpr std::string_view kTradeTimeout1 = "Adjust trade timeout (default defined in "; + static constexpr std::string_view kTradeTimeout2 = + "). Remaining orders will follow trade timeout action mode which is cancel by default"; static constexpr std::string_view kTradeTimeout = - JoinStringView_v, kTradeTimeout2>; + JoinStringView_v; static constexpr std::string_view kTradeUpdatePrice1 = - "Set the min time allowed between two limit price updates (default: "; + "Set the min time allowed between two limit price updates (default defined in "; static constexpr std::string_view kTradeUpdatePrice2 = - "s). Avoids cancelling / placing new orders too often with high volumes which can be counter productive " + "). Avoids cancelling / placing new orders too often with high volumes which can be counter productive " "sometimes."; static constexpr std::string_view kTradeUpdatePrice = - JoinStringView_v, kTradeUpdatePrice2>; + JoinStringView_v; static constexpr std::string_view kSimulationMode1 = "Activates simulation mode only (default: "; static constexpr std::string_view kSimulationMode2 = TradeOptions().isSimulation() ? "true" : "false"; @@ -310,7 +319,7 @@ struct CoincenterAllowedOptions : private CoincenterCmdLineOptionsDefinitions { {{{"Trade", 4000}, "trade", "", - "Single trade from given start amount on a list of exchanges, " + "Trade from given start amount on a list of exchanges, " "or all that have sufficient balance on cur1 if none provided.\n" "Amount can be given as a percentage - in this case the desired percentage " "of available amount on matching exchanges will be traded.\n" @@ -319,7 +328,7 @@ struct CoincenterAllowedOptions : private CoincenterCmdLineOptionsDefinitions { {{{"Trade", 4000}, "trade-all", "", - "Single trade from available amount from given currency on a list of exchanges," + "Trade from available amount from given currency on a list of exchanges," " or all that have some balance on cur1 if none provided\n" "Order will be placed at limit price by default"}, &OptValueType::tradeAll}, @@ -332,7 +341,7 @@ struct CoincenterAllowedOptions : private CoincenterCmdLineOptionsDefinitions { {{{"Trade", 4010}, "--multi-trade", "", - "Force activation of multi trade mode for all exchanges, overriding default configuration of config file.\n" + "Allow multi step trades for this command, overriding default configuration of config file.\n" "It makes trade in multiple steps possible if exchange does not provide a direct currency market pair.\n" "The conversion path used is always one of the fastest(s). All other trade options apply to one unique trade " "step (for instance, the trade timeout is related to a single trade, not the series of all trades of a multi " @@ -353,17 +362,14 @@ struct CoincenterAllowedOptions : private CoincenterCmdLineOptionsDefinitions { " Order price will not be continuously updated.\n" "This option is not compatible with '--strategy'"}, &OptValueType::tradePrice}, - {{{"Trade", 4030}, - "--strategy", - "", - "Customize the order price strategy of the trade\n" - " 'maker' : order price set at limit price (default)\n" - " 'nibble': order price set at limit price +(buy)/-(sell) 1\n" - " 'taker' : order price will be at market price and matched immediately\n" - "Order price will be continuously updated and recomputed every '--update-price' step time.\n" - "This option is not compatible with '--price'"}, - &OptValueType::tradeStrategy}, + {{{"Trade", 4030}, "--strategy", "", kTradeStrategy}, &OptValueType::tradeStrategy}, {{{"Trade", 4030}, "--timeout", "