Skip to content

Commit

Permalink
Addition of formatting to simplify code for ExchangeName and exception
Browse files Browse the repository at this point in the history
  • Loading branch information
sjanel committed Oct 29, 2022
1 parent b074f0d commit 66c7462
Show file tree
Hide file tree
Showing 29 changed files with 89 additions and 261 deletions.
5 changes: 1 addition & 4 deletions src/api/common/src/cryptowatchapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ string Query(CurlHandle& curlHandle, std::string_view endpoint, CurlPostData&& p
const json& CollectResults(const json& dataJson) {
auto errIt = dataJson.find("error");
if (errIt != dataJson.end() && !errIt->empty()) {
std::string_view errMsg = errIt->front().get<std::string_view>();
string ex("Cryptowatch::query error: ");
ex.append(errMsg);
throw exception(std::move(ex));
throw exception("Cryptowatch::query error: {}", errIt->front().get<std::string_view>());
}
return dataJson["result"];
}
Expand Down
12 changes: 1 addition & 11 deletions src/api/common/src/exchangepublicapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -204,17 +204,7 @@ Market ExchangePublic::retrieveMarket(CurrencyCode c1, CurrencyCode c2, const Ma
if (!markets.contains(m)) {
m = m.reverse();
if (!markets.contains(m)) {
string ex("Cannot find ");
ex.append(c1.str())
.append("-")
.append(c2.str())
.append(" nor ")
.append(c2.str())
.append("-")
.append(c1.str())
.append(" markets on ")
.append(_name);
throw exception(std::move(ex));
throw exception("Cannot find {}-{} nor {}-{} markets on {}", c1, c2, c2, c1, _name);
}
}
return m;
Expand Down
6 changes: 1 addition & 5 deletions src/api/exchanges/src/binanceprivateapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,7 @@ json PrivateQuery(CurlHandle& curlHandle, const APIKey& apiKey, HttpRequestType
statusCode = ret["code"];
}
log::error("Full Binance json error: '{}'", ret.dump());
string ex("Error: ");
ex.append(MonetaryAmount(statusCode).amountStr());
ex.append(", msg: ");
ex.append(ret["msg"].get<std::string_view>());
throw exception(std::move(ex));
throw exception("Error: {}, msg: {}", MonetaryAmount(statusCode), ret["msg"].get<std::string_view>());
}
return ret;
}
Expand Down
14 changes: 3 additions & 11 deletions src/api/exchanges/src/binancepublicapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,7 @@ json PublicQuery(CurlHandle& curlHandle, std::string_view method, const CurlPost
if (foundErrorIt != ret.end() && foundMsgIt != ret.end()) {
const int statusCode = foundErrorIt->get<int>(); // "1100" for instance
log::error("Full Binance json error: '{}'", ret.dump());
string ex("Error: ");
ex.append(MonetaryAmount(statusCode).amountStr());
ex.append(", msg: ");
ex.append(foundMsgIt->get<std::string_view>());
throw exception(std::move(ex));
throw exception("Error: {}, msg: ", MonetaryAmount(statusCode), foundMsgIt->get<std::string_view>());
}
return ret;
}
Expand All @@ -48,9 +44,7 @@ template <class ExchangeInfoDataByMarket>
const json& RetrieveMarketData(const ExchangeInfoDataByMarket& exchangeInfoData, Market m) {
auto it = exchangeInfoData.find(m);
if (it == exchangeInfoData.end()) {
string ex("Unable to retrieve market data ");
ex.append(m.str());
throw exception(std::move(ex));
throw exception("Unable to retrieve {} data", m);
}
return it->second;
}
Expand Down Expand Up @@ -248,9 +242,7 @@ MonetaryAmount BinancePublic::queryWithdrawalFee(CurrencyCode currencyCode) {
return ComputeWithdrawalFeesFromNetworkList(cur, el["networkList"]);
}
}
string ex("Unable to find withdrawal fee for ");
currencyCode.appendStr(ex);
throw exception(std::move(ex));
throw exception("Unable to find withdrawal fee for {}", currencyCode);
}

MonetaryAmount BinancePublic::sanitizePrice(Market m, MonetaryAmount pri) {
Expand Down
17 changes: 6 additions & 11 deletions src/api/exchanges/src/bithumbprivateapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -225,9 +225,7 @@ json PrivateQuery(CurlHandle& curlHandle, const APIKey& apiKey, std::string_view
}
}
log::error("Full Bithumb json error: '{}'", ret.dump());
string ex("Bithumb error: ");
ex.append(statusCode).append(" \"").append(msg).append("\"");
throw exception(std::move(ex));
throw exception("Bithumb error: {} \"{}\"", statusCode, msg);
}
}
return ret;
Expand Down Expand Up @@ -280,10 +278,9 @@ BalancePortfolio BithumbPrivate::queryAccountBalance(CurrencyCode equiCurrency)
Wallet BithumbPrivate::DepositWalletFunc::operator()(CurrencyCode currencyCode) {
json ret = PrivateQuery(_curlHandle, _apiKey, kWalletAddressEndpointStr, {{"currency", currencyCode.str()}});
if (ret.empty()) {
string err("Bithumb wallet is not created for ");
currencyCode.appendStr(err);
err.append(", it should be done with the UI first (no way to do it via API).");
throw exception(std::move(err));
throw exception(
"Bithumb wallet is not created for {}, it should be done with the UI first (no way to do it via API)",
currencyCode);
}
std::string_view addressAndTag = ret["data"]["wallet_address"].get<std::string_view>();
std::size_t tagPos = addressAndTag.find('&');
Expand Down Expand Up @@ -636,7 +633,7 @@ SentWithdrawInfo BithumbPrivate::isWithdrawSuccessfullySent(const InitiatedWithd
}
std::size_t first = unitsStr.find_first_of("0123456789");
if (first == std::string_view::npos) {
throw exception("Bithumb: cannot parse amount " + string(unitsStr));
throw exception("Bithumb: cannot parse amount {}", unitsStr);
}
MonetaryAmount consumedAmt(std::string_view(unitsStr.begin() + first, unitsStr.end()), currencyCode);
if (consumedAmt == initiatedWithdrawInfo.grossEmittedAmount()) {
Expand All @@ -650,9 +647,7 @@ SentWithdrawInfo BithumbPrivate::isWithdrawSuccessfullySent(const InitiatedWithd
initiatedWithdrawInfo.grossEmittedAmount());
}
}
string msg("Bithumb: unable to find withdrawal confirmation of ");
msg.append(initiatedWithdrawInfo.grossEmittedAmount().str());
throw exception(std::move(msg));
throw exception("Bithumb: unable to find withdrawal confirmation of {}", initiatedWithdrawInfo.grossEmittedAmount());
}

bool BithumbPrivate::isWithdrawReceived(const InitiatedWithdrawInfo& initiatedWithdrawInfo,
Expand Down
14 changes: 4 additions & 10 deletions src/api/exchanges/src/bithumbpublicapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,9 @@ json PublicQuery(CurlHandle& curlHandle, std::string_view endpoint, CurrencyCode
std::string_view statusCode = errorIt->get<std::string_view>(); // "5300" for instance
if (statusCode != "0000") { // "0000" stands for: request OK
log::error("Full Bithumb json error: '{}'", ret.dump());
string err("Bithumb error: ");
err.append(statusCode);
auto msgIt = ret.find("message");
if (msgIt != ret.end()) {
err.append(" \"");
err.append(msgIt->get<std::string_view>());
err.push_back('\"');
}
throw exception(std::move(err));
throw exception("Bithumb error: {}, msg: {}", statusCode,
msgIt != ret.end() ? msgIt->get<std::string_view>() : "null");
}
}
return ret["data"];
Expand Down Expand Up @@ -88,7 +82,7 @@ MonetaryAmount BithumbPublic::queryWithdrawalFee(CurrencyCode currencyCode) {
const auto& map = _withdrawalFeesCache.get();
auto it = map.find(currencyCode);
if (it == map.end()) {
throw exception("Unable to find currency code in withdrawal fees");
throw exception("Unable to find {} in withdrawal fees", currencyCode);
}
return it->second;
}
Expand Down Expand Up @@ -263,7 +257,7 @@ MarketOrderBook BithumbPublic::OrderBookFunc::operator()(Market m, int count) {
MarketOrderBookMap marketOrderBookMap = GetOrderbooks(_curlHandle, _coincenterInfo, _exchangeInfo, m, count);
auto it = marketOrderBookMap.find(m);
if (it == marketOrderBookMap.end()) {
throw exception("Unexpected answer from get OrderBooks");
throw exception("Cannot find {} in market order book map", m);
}
return it->second;
}
Expand Down
26 changes: 5 additions & 21 deletions src/api/exchanges/src/huobiprivateapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,8 @@ json PrivateQuery(CurlHandle& curlHandle, const APIKey& apiKey, HttpRequestType
auto statusIt = ret.find("status");
if (statusIt != ret.end() && statusIt->get<std::string_view>() != "ok") {
log::error("Full Huobi json error: '{}'", ret.dump());
string errMsg("Huobi error: ");
auto errIt = ret.find("err-msg");
if (errIt == ret.end()) {
errMsg.append("unknown");
} else {
errMsg.append(errIt->get<std::string_view>());
}
throw exception(std::move(errMsg));
throw exception("Huobi error: {}", errIt == ret.end() ? "unknown" : errIt->get<std::string_view>());
}

return ret;
Expand Down Expand Up @@ -367,21 +361,11 @@ InitiatedWithdrawInfo HuobiPrivate::launchWithdraw(MonetaryAmount grossAmount, W
HuobiPublic::WithdrawParams withdrawParams = huobiPublic.getWithdrawParams(currencyCode);
MonetaryAmount netEmittedAmount = grossAmount - fee;
if (!withdrawParams.minWithdrawAmt.isDefault() && netEmittedAmount < withdrawParams.minWithdrawAmt) {
string err("Minimum withdraw amount for ");
currencyCode.appendStr(err);
err.append(" on Huobi is ")
.append(withdrawParams.minWithdrawAmt.amountStr())
.append(", cannot withdraw ")
.append(netEmittedAmount.str());
throw exception(std::move(err));
throw exception("Minimum withdraw amount for {} on Huobi is {}, cannot withdraw {}", currencyCode,
withdrawParams.minWithdrawAmt, netEmittedAmount);
} else if (!withdrawParams.maxWithdrawAmt.isDefault() && netEmittedAmount > withdrawParams.maxWithdrawAmt) {
string err("Maximum withdraw amount for ");
currencyCode.appendStr(err);
err.append(" on Huobi is ")
.append(withdrawParams.maxWithdrawAmt.amountStr())
.append(", cannot withdraw ")
.append(netEmittedAmount.str());
throw exception(std::move(err));
throw exception("Maximum withdraw amount for {} on Huobi is {}, cannot withdraw {}", currencyCode,
withdrawParams.maxWithdrawAmt, netEmittedAmount);
}
if (netEmittedAmount.nbDecimals() > withdrawParams.withdrawPrecision) {
log::warn("Withdraw amount precision for Huobi is {} - truncating {}", withdrawParams.withdrawPrecision,
Expand Down
4 changes: 1 addition & 3 deletions src/api/exchanges/src/huobipublicapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,7 @@ MonetaryAmount HuobiPublic::queryWithdrawalFee(CurrencyCode currencyCode) {
}
}
}
string msg("Unable to find withdrawal fee for ");
currencyCode.appendStr(msg);
throw exception(std::move(msg));
throw exception("Unable to find withdrawal fee for {}", currencyCode);
}

MarketOrderBookMap HuobiPublic::AllOrderBooksFunc::operator()(int depth) {
Expand Down
22 changes: 6 additions & 16 deletions src/api/exchanges/src/krakenprivateapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@ json PrivateQuery(CurlHandle& curlHandle, const APIKey& apiKey, std::string_view
ret = json::parse(R"({" error ":[]," result ":{" count ":1}})");
} else {
log::error("Full Kraken json error: '{}'", ret.dump());
string ex("Kraken error: ");
ex.append(msg);
throw exception(std::move(ex));
throw exception("Kraken error: {}", msg);
}
}
return ret["result"];
Expand Down Expand Up @@ -107,9 +105,7 @@ Wallet KrakenPrivate::DepositWalletFunc::operator()(CurrencyCode currencyCode) {
CurrencyExchange krakenCurrency = _exchangePublic.convertStdCurrencyToCurrencyExchange(currencyCode);
json res = PrivateQuery(_curlHandle, _apiKey, "/private/DepositMethods", {{"asset", krakenCurrency.altStr()}});
if (res.empty()) {
string msg("No deposit method found on Kraken for ");
currencyCode.appendStr(msg);
throw exception(std::move(msg));
throw exception("No deposit method found on Kraken for {}", currencyCode);
}
// Don't keep a view on 'method' value, we will override json data just below. We can just steal the string.
string method = std::move(res.front()["method"].get_ref<string&>());
Expand All @@ -121,9 +117,7 @@ Wallet KrakenPrivate::DepositWalletFunc::operator()(CurrencyCode currencyCode) {
res = PrivateQuery(_curlHandle, _apiKey, "/private/DepositAddresses",
{{"asset", krakenCurrency.altStr()}, {"method", method}, {"new", "true"}});
if (res.empty()) {
string err("Cannot create a new deposit address on Kraken for ");
currencyCode.appendStr(err);
throw exception(std::move(err));
throw exception("Cannot create a new deposit address on Kraken for {}", currencyCode);
}
}
ExchangeName exchangeName(_exchangePublic.name(), _apiKey.name());
Expand Down Expand Up @@ -157,9 +151,7 @@ Wallet KrakenPrivate::DepositWalletFunc::operator()(CurrencyCode currencyCode) {
} else {
// Heuristic: this last field may change key name and is optional (tag for XRP, memo for EOS for instance)
if (!tag.empty()) {
string msg("Tag already set / unknown key information for ");
currencyCode.appendStr(msg);
throw exception(std::move(msg));
throw exception("Tag already set / unknown key information for {}", currencyCode);
}
if (valueStr.is_number_integer()) {
SetString(tag, static_cast<long>(valueStr));
Expand Down Expand Up @@ -388,7 +380,7 @@ json KrakenPrivate::queryOrdersData(int64_t userRef, const OrderId& orderId, Que
log::warn("{} is not present in opened nor closed orders, retry {}", orderId, nbRetries);
continue;
}
throw exception("I lost contact with Kraken order " + orderId);
throw exception("I lost contact with Kraken order {}", orderId);
}
return data;

Expand Down Expand Up @@ -430,9 +422,7 @@ SentWithdrawInfo KrakenPrivate::isWithdrawSuccessfullySent(const InitiatedWithdr
return SentWithdrawInfo(netWithdrawAmount, status == "Success");
}
}
string msg("Kraken: unable to find withdrawal confirmation of ");
msg.append(initiatedWithdrawInfo.grossEmittedAmount().str());
throw exception(std::move(msg));
throw exception("Kraken: unable to find withdrawal confirmation of {}", initiatedWithdrawInfo.grossEmittedAmount());
}

bool KrakenPrivate::isWithdrawReceived(const InitiatedWithdrawInfo& initiatedWithdrawInfo,
Expand Down
25 changes: 5 additions & 20 deletions src/api/exchanges/src/krakenpublicapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@ json PublicQuery(CurlHandle& curlHandle, std::string_view method, CurlPostData&&
auto errorIt = ret.find("error");
if (errorIt != ret.end() && !errorIt->empty()) {
log::error("Full Kraken json error: '{}'", ret.dump());
std::string_view msg = errorIt->front().get<std::string_view>();
string ex("Kraken error: ");
ex.append(msg);
throw exception(std::move(ex));
throw exception("Kraken error: {}", errorIt->front().get<std::string_view>());
}
return ret["result"];
}
Expand Down Expand Up @@ -366,18 +363,12 @@ MarketOrderBookMap KrakenPublic::AllOrderBooksFunc::operator()(int depth) {
for (Market m : markets) {
auto lb = krakenCurrencies.find(m.base());
if (lb == krakenCurrencies.end()) {
string msg("Cannot find ");
m.base().appendStr(msg);
msg.append(" in Kraken currencies");
throw exception(std::move(msg));
throw exception("Cannot find {} in Kraken currencies", m.base());
}
CurrencyExchange krakenCurrencyExchangeBase = *lb;
lb = krakenCurrencies.find(m.quote());
if (lb == krakenCurrencies.end()) {
string msg("Cannot find ");
m.quote().appendStr(msg);
msg.append(" in Kraken currencies");
throw exception(std::move(msg));
throw exception("Cannot find {} in Kraken currencies", m.quote());
}
CurrencyExchange krakenCurrencyExchangeQuote = *lb;
Market krakenMarket(krakenCurrencyExchangeBase.altCode(), krakenCurrencyExchangeQuote.altCode());
Expand Down Expand Up @@ -426,18 +417,12 @@ MarketOrderBook KrakenPublic::OrderBookFunc::operator()(Market m, int count) {
CurrencyExchangeFlatSet krakenCurrencies = _tradableCurrenciesCache.get();
auto lb = krakenCurrencies.find(m.base());
if (lb == krakenCurrencies.end()) {
string msg("Cannot find ");
m.base().appendStr(msg);
msg.append(" in Kraken currencies");
throw exception(std::move(msg));
throw exception("Cannot find {} in Kraken currencies", m.base());
}
CurrencyExchange krakenCurrencyExchangeBase = *lb;
lb = krakenCurrencies.find(m.quote());
if (lb == krakenCurrencies.end()) {
string msg("Cannot find ");
m.quote().appendStr(msg);
msg.append(" in Kraken currencies");
throw exception(std::move(msg));
throw exception("Cannot find {} in Kraken currencies", m.quote());
}
CurrencyExchange krakenCurrencyExchangeQuote = *lb;
string krakenAssetPair = krakenCurrencyExchangeBase.altStr();
Expand Down
12 changes: 4 additions & 8 deletions src/api/exchanges/src/kucoinprivateapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,16 @@ json PrivateQuery(CurlHandle& curlHandle, const APIKey& apiKey, HttpRequestType
json ret = json::parse(curlHandle.query(endpoint, std::move(opts)));
auto errCodeIt = ret.find("code");
if (errCodeIt != ret.end() && errCodeIt->get<std::string_view>() != "200000") {
string errStr("Kucoin error: ");
errStr.append(errCodeIt->get<std::string_view>());
auto msgIt = ret.find("msg");
if (msgIt != ret.end()) {
errStr.append(" - ");
errStr.append(msgIt->get<std::string_view>());
}
std::string_view msg = msgIt == ret.end() ? "null" : msgIt->get<std::string_view>();
if (requestType == HttpRequestType::kDelete) {
log::warn("{} bypassed, object probably disappeared correctly", errStr);
log::warn("Kucoin error {} bypassed, object probably disappeared correctly. Msg: {}",
errCodeIt->get<std::string_view>(), msg);
ret.clear();
return ret;
}
log::error("Full Kucoin json error: '{}'", ret.dump());
throw exception(std::move(errStr));
throw exception("Kucoin error: {}, msg: {}", errCodeIt->get<std::string_view>(), msg);
}
return ret["data"];
}
Expand Down
8 changes: 2 additions & 6 deletions src/api/exchanges/src/kucoinpublicapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ json PublicQuery(CurlHandle& curlHandle, std::string_view endpoint, const CurlPo
auto errorIt = ret.find("code");
if (errorIt != ret.end() && errorIt->get<std::string_view>() != "200000") {
log::error("Full Kucoin json error: '{}'", ret.dump());
string err("Kucoin error: ");
err.append(errorIt->get<std::string_view>());
throw exception(std::move(err));
throw exception("Kucoin error: {}", errorIt->get<std::string_view>());
}
return ret["data"];
}
Expand Down Expand Up @@ -152,9 +150,7 @@ MonetaryAmount KucoinPublic::queryWithdrawalFee(CurrencyCode currencyCode) {
const auto& currencyInfoSet = _tradableCurrenciesCache.get();
auto it = currencyInfoSet.find(TradableCurrenciesFunc::CurrencyInfo(currencyCode));
if (it == currencyInfoSet.end()) {
string msg("Unable to find withdrawal fee for ");
currencyCode.appendStr(msg);
throw exception(std::move(msg));
throw exception("Unable to find withdrawal fee for {}", currencyCode);
}
return MonetaryAmount(it->withdrawalMinFee, it->currencyExchange.standardCode());
}
Expand Down
Loading

0 comments on commit 66c7462

Please sign in to comment.