Skip to content

Commit

Permalink
[Code cleaning] - Fix shadow warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
sjanel committed Nov 9, 2024
1 parent 36be43f commit 9782f53
Show file tree
Hide file tree
Showing 22 changed files with 113 additions and 114 deletions.
6 changes: 3 additions & 3 deletions cmake/CoincenterUtils.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ function (target_set_coincenter_options name)
if(MSVC)
target_compile_options(${name} PRIVATE /W3)
else()
target_compile_options(${name} PRIVATE -Wall -Wextra -pedantic -Wshadow -Winline)
target_compile_options(${name} PRIVATE -Wall -Wextra -pedantic -Wshadow)
endif()
else()
if(MSVC)
target_compile_options(${name} PRIVATE /W1)
else()
target_compile_options(${name} PRIVATE -Wdisabled-optimization)
target_compile_options(${name} PRIVATE -Wdisabled-optimization -Winline)
endif()
endif()

Expand Down
12 changes: 5 additions & 7 deletions src/api-objects/include/tradeinfo.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@ namespace cct::api {
using UserRefInt = int32_t;

struct TradeContext {
TradeContext(Market market, TradeSide s, UserRefInt userRef = 0) : mk(market), side(s), userRef(userRef) {}
CurrencyCode fromCur() const { return side == TradeSide::kSell ? market.base() : market.quote(); }
CurrencyCode toCur() const { return side == TradeSide::kBuy ? market.base() : market.quote(); }

CurrencyCode fromCur() const { return side == TradeSide::kSell ? mk.base() : mk.quote(); }
CurrencyCode toCur() const { return side == TradeSide::kBuy ? mk.base() : mk.quote(); }

Market mk;
TradeSide side;
UserRefInt userRef; // Used by Kraken for instance, used to group orders queries context
Market market;
TradeSide side{};
UserRefInt userRef{}; // Used by Kraken for instance, used to group orders queries context
};

struct TradeInfo {
Expand Down
2 changes: 2 additions & 0 deletions src/api/common/include/exchange-permanent-curl-options.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace cct {
class ExchangeConfig;

namespace api {

class ExchangePermanentCurlOptions {
public:
explicit ExchangePermanentCurlOptions(const ExchangeConfig &exchangeConfig);
Expand All @@ -20,6 +21,7 @@ class ExchangePermanentCurlOptions {
private:
const ExchangeConfig &_exchangeConfig;
};

} // namespace api

} // namespace cct
12 changes: 6 additions & 6 deletions src/api/common/include/fiatconverter.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,16 +67,16 @@ class FiatConverter : public CacheFileUpdatorInterface {
TimePoint lastUpdatedTime;
};

std::optional<double> queryCurrencyRate(Market mk);
std::optional<double> queryCurrencyRate(Market market);

std::optional<double> queryCurrencyRateSource1(Market mk);
std::optional<double> queryCurrencyRateSource2(Market mk);
std::optional<double> queryCurrencyRateSource1(Market market);
std::optional<double> queryCurrencyRateSource2(Market market);

std::optional<double> retrieveRateFromCache(Market mk) const;
std::optional<double> retrieveRateFromCache(Market market) const;

void store(Market mk, double rate);
void store(Market market, double rate);

void refreshLastUpdatedTime(Market mk);
void refreshLastUpdatedTime(Market market);

using PricesMap = std::unordered_map<Market, PriceTimedValue>;

Expand Down
1 change: 1 addition & 0 deletions src/api/common/src/exchange-permanent-curl-options.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "exchange-permanent-curl-options.hpp"

#include "exchangeconfig.hpp"
#include "permanentcurloptions.hpp"

namespace cct::api {

Expand Down
2 changes: 1 addition & 1 deletion src/api/common/src/exchangeprivateapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ TradedAmountsVectorWithFinalAmount ExchangePrivate::queryDustSweeper(CurrencyCod

PlaceOrderInfo ExchangePrivate::placeOrderProcess(MonetaryAmount &from, MonetaryAmount price,
const TradeInfo &tradeInfo) {
const Market mk = tradeInfo.tradeContext.mk;
const Market mk = tradeInfo.tradeContext.market;
const bool isSell = tradeInfo.tradeContext.side == TradeSide::kSell;
const MonetaryAmount volume(isSell ? from : MonetaryAmount(from / price, mk.base()));

Expand Down
56 changes: 28 additions & 28 deletions src/api/common/src/fiatconverter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -89,17 +89,17 @@ void FiatConverter::updateCacheFile() const {
GetRatesCacheFile(_dataDir).writeJson(data);
}

std::optional<double> FiatConverter::queryCurrencyRate(Market mk) {
auto ret = queryCurrencyRateSource1(mk);
std::optional<double> FiatConverter::queryCurrencyRate(Market market) {
auto ret = queryCurrencyRateSource1(market);
if (ret) {
return ret;
}
ret = queryCurrencyRateSource2(mk);
ret = queryCurrencyRateSource2(market);
return ret;
}

std::optional<double> FiatConverter::queryCurrencyRateSource1(Market mk) {
const auto qStr = mk.assetsPairStrUpper('_');
std::optional<double> FiatConverter::queryCurrencyRateSource1(Market market) {
const auto qStr = market.assetsPairStrUpper('_');

const CurlOptions opts(HttpRequestType::kGet, {{"q", qStr}, {"apiKey", _apiKey}});

Expand All @@ -111,17 +111,17 @@ std::optional<double> FiatConverter::queryCurrencyRateSource1(Market mk) {
//{"query":{"count":1},"results":{"EUR_KRW":{"id":"EUR_KRW","val":1329.475323,"to":"KRW","fr":"EUR"}}}
const auto resultsIt = data.find("results");
if (data.is_discarded() || resultsIt == data.end() || !resultsIt->contains(qStr)) {
log::warn("No JSON data received from fiat currency converter service's first source for pair '{}'", mk);
refreshLastUpdatedTime(mk);
log::warn("No JSON data received from fiat currency converter service's first source for pair '{}'", market);
refreshLastUpdatedTime(market);
return std::nullopt;
}
const auto& rates = (*resultsIt)[qStr];
const double rate = rates["val"];
store(mk, rate);
store(market, rate);
return rate;
}

std::optional<double> FiatConverter::queryCurrencyRateSource2(Market mk) {
std::optional<double> FiatConverter::queryCurrencyRateSource2(Market market) {
const auto dataStr = _curlHandle2.query("", CurlOptions(HttpRequestType::kGet));
static constexpr bool kAllowExceptions = false;
const json::container jsonData = json::container::parse(dataStr, nullptr, kAllowExceptions);
Expand All @@ -132,7 +132,7 @@ std::optional<double> FiatConverter::queryCurrencyRateSource2(Market mk) {
const auto baseIt = jsonData.find("base");
const auto ratesIt = jsonData.find("rates");
if (baseIt == jsonData.end() || ratesIt == jsonData.end()) {
log::warn("No JSON data received from fiat currency converter service's second source", mk);
log::warn("No JSON data received from fiat currency converter service's second source", market);
return {};
}

Expand All @@ -145,53 +145,53 @@ std::optional<double> FiatConverter::queryCurrencyRateSource2(Market mk) {

_pricesMap.insert_or_assign(Market(_baseRateSource2, currencyCode), PriceTimedValue(rateDouble, nowTime));
}
return retrieveRateFromCache(mk);
return retrieveRateFromCache(market);
}

void FiatConverter::store(Market mk, double rate) {
log::debug("Stored rate {} for {}", rate, mk);
void FiatConverter::store(Market market, double rate) {
log::debug("Stored rate {} for {}", rate, market);
const TimePoint nowTime = Clock::now();

_pricesMap.insert_or_assign(mk.reverse(), PriceTimedValue(static_cast<double>(1) / rate, nowTime));
_pricesMap.insert_or_assign(std::move(mk), PriceTimedValue(rate, nowTime));
_pricesMap.insert_or_assign(market.reverse(), PriceTimedValue(static_cast<double>(1) / rate, nowTime));
_pricesMap.insert_or_assign(std::move(market), PriceTimedValue(rate, nowTime));
}

void FiatConverter::refreshLastUpdatedTime(Market mk) {
const auto it = _pricesMap.find(mk);
void FiatConverter::refreshLastUpdatedTime(Market market) {
const auto it = _pricesMap.find(market);
if (it != _pricesMap.end()) {
// Update cache time anyway to avoid querying too much the service
const TimePoint nowTime = Clock::now();

it->second.lastUpdatedTime = nowTime;
_pricesMap[mk.reverse()].lastUpdatedTime = nowTime;
_pricesMap[market.reverse()].lastUpdatedTime = nowTime;
}
}

std::optional<double> FiatConverter::convert(double amount, CurrencyCode from, CurrencyCode to) {
if (from == to) {
return amount;
}
const Market mk(from, to);
const Market market(from, to);

double rate;

std::lock_guard<std::mutex> guard(_pricesMutex);

const auto optRate = retrieveRateFromCache(mk);
const auto optRate = retrieveRateFromCache(market);
if (optRate) {
rate = *optRate;
} else {
if (_ratesUpdateFrequency == Duration::max()) {
log::error("Unable to query fiat currency rates and no rate found in cache for {}", mk);
log::error("Unable to query fiat currency rates and no rate found in cache for {}", market);
return {};
}
std::optional<double> queriedRate = queryCurrencyRate(mk);
std::optional<double> queriedRate = queryCurrencyRate(market);
if (queriedRate) {
rate = *queriedRate;
} else {
const auto it = _pricesMap.find(mk);
const auto it = _pricesMap.find(market);
if (it == _pricesMap.end()) {
log::error("Unable to query fiat currency rates and no rate found in cache for {}", mk);
log::error("Unable to query fiat currency rates and no rate found in cache for {}", market);
return {};
}
log::warn("Fiat currency rate service unavailable, use not up to date currency rate in cache");
Expand All @@ -202,23 +202,23 @@ std::optional<double> FiatConverter::convert(double amount, CurrencyCode from, C
return amount * rate;
}

std::optional<double> FiatConverter::retrieveRateFromCache(Market mk) const {
std::optional<double> FiatConverter::retrieveRateFromCache(Market market) const {
const auto rateIfYoung = [this, nowTime = Clock::now()](Market mk) -> std::optional<double> {
const auto it = _pricesMap.find(mk);
if (it != _pricesMap.end() && nowTime - it->second.lastUpdatedTime < _ratesUpdateFrequency) {
return it->second.rate;
}
return {};
};
const auto directRate = rateIfYoung(mk);
const auto directRate = rateIfYoung(market);
if (directRate) {
return directRate;
}
if (_baseRateSource2.isDefined()) {
// Try with dual rates from base source.
const auto rateBase1 = rateIfYoung(Market(_baseRateSource2, mk.base()));
const auto rateBase1 = rateIfYoung(Market(_baseRateSource2, market.base()));
if (rateBase1) {
const auto rateBase2 = rateIfYoung(Market(_baseRateSource2, mk.quote()));
const auto rateBase2 = rateIfYoung(Market(_baseRateSource2, market.quote()));
if (rateBase2) {
return *rateBase2 / *rateBase1;
}
Expand Down
2 changes: 1 addition & 1 deletion src/api/common/test/exchangeprivateapi_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ namespace cct::api {

static inline bool operator==(const TradeContext &lhs, const TradeContext &rhs) {
// We don't compare on value userRef which is set from a timestamp
return lhs.mk == rhs.mk && lhs.side == rhs.side;
return lhs.market == rhs.market && lhs.side == rhs.side;
}

static inline bool operator==(const TradeInfo &lhs, const TradeInfo &rhs) {
Expand Down
4 changes: 2 additions & 2 deletions src/api/exchanges/src/binanceprivateapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -672,7 +672,7 @@ PlaceOrderInfo BinancePrivate::placeOrder(MonetaryAmount from, MonetaryAmount vo
BinancePublic& binancePublic = dynamic_cast<BinancePublic&>(_exchangePublic);
const CurrencyCode fromCurrencyCode(tradeInfo.tradeContext.fromCur());
const CurrencyCode toCurrencyCode(tradeInfo.tradeContext.toCur());
const Market mk = tradeInfo.tradeContext.mk;
const Market mk = tradeInfo.tradeContext.market;
const std::string_view buyOrSell = fromCurrencyCode == mk.base() ? "SELL" : "BUY";
const bool placeSimulatedRealOrder = binancePublic.exchangeConfig().placeSimulateRealOrder();
const bool isTakerStrategy = tradeInfo.options.isTakerStrategy(placeSimulatedRealOrder);
Expand Down Expand Up @@ -743,7 +743,7 @@ PlaceOrderInfo BinancePrivate::placeOrder(MonetaryAmount from, MonetaryAmount vo

OrderInfo BinancePrivate::queryOrder(OrderIdView orderId, const TradeContext& tradeContext,
HttpRequestType requestType) {
const Market mk = tradeContext.mk;
const Market mk = tradeContext.market;
const CurrencyCode fromCurrencyCode = tradeContext.side == TradeSide::kSell ? mk.base() : mk.quote();
const CurrencyCode toCurrencyCode = tradeContext.side == TradeSide::kBuy ? mk.base() : mk.quote();
const string assetsStr = mk.assetsPairStrUpper();
Expand Down
23 changes: 11 additions & 12 deletions src/api/exchanges/src/bithumbprivateapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -265,22 +265,22 @@ json::container PrivateQueryProcessWithRetries(CurlHandle& curlHandle, const API

json::container ret = requestRetry.queryJson(
endpoint,
[endpoint](json::container& ret) {
const auto errorCode = BithumbPublic::StatusCodeFromJsonResponse(ret);
[endpoint](json::container& jsonResponse) {
const auto errorCode = BithumbPublic::StatusCodeFromJsonResponse(jsonResponse);
if (errorCode == 0 || errorCode == BithumbPublic::kStatusNotPresentError) {
return RequestRetry::Status::kResponseOK;
}

std::string_view msg;
auto messageIt = ret.find("message");
if (messageIt != ret.end()) {
auto messageIt = jsonResponse.find("message");
if (messageIt != jsonResponse.end()) {
msg = messageIt->get<std::string_view>();
switch (errorCode) {
case kBadRequestErrorCode:
CheckAndLogSynchronizedTime(msg);
break;
case kOrderRelatedErrorCode:
if (CheckOrderErrors(endpoint, msg, ret)) {
if (CheckOrderErrors(endpoint, msg, jsonResponse)) {
return RequestRetry::Status::kResponseOK;
}
break;
Expand All @@ -290,12 +290,11 @@ json::container PrivateQueryProcessWithRetries(CurlHandle& curlHandle, const API
}
return RequestRetry::Status::kResponseError;
},
[endpoint, &apiKey](CurlOptions& opts) {
auto [strData, nonce] = GetStrData(endpoint, opts.postData().str());

[endpoint, &apiKey](CurlOptions& curlOptions) {
auto [strData, nonce] = GetStrData(endpoint, curlOptions.postData().str());
auto signature = B64Encode(ssl::Sha512Hex(strData, apiKey.privateKey()));

SetHttpHeaders(opts, apiKey, signature, nonce);
SetHttpHeaders(curlOptions, apiKey, signature, nonce);
});

return ret;
Expand Down Expand Up @@ -851,7 +850,7 @@ PlaceOrderInfo BithumbPrivate::placeOrder(MonetaryAmount /*from*/, MonetaryAmoun
const CurrencyCode toCurrencyCode(tradeInfo.tradeContext.toCur());
PlaceOrderInfo placeOrderInfo(OrderInfo(TradedAmounts(fromCurrencyCode, toCurrencyCode)), OrderId("UndefinedId"));

const Market mk = tradeInfo.tradeContext.mk;
const Market mk = tradeInfo.tradeContext.market;

// It seems Bithumb uses "standard" currency codes, no need to translate them
CurlPostData placePostData{{kOrderCurrencyParamStr, mk.base().str()}, {kPaymentCurParamStr, mk.quote().str()}};
Expand Down Expand Up @@ -1041,14 +1040,14 @@ CurlPostData OrderInfoPostData(Market mk, TradeSide side, OrderIdView orderId) {

void BithumbPrivate::cancelOrderProcess(OrderIdView orderId, const TradeContext& tradeContext) {
json::container ret = PrivateQuery(_curlHandle, _apiKey, "/trade/cancel",
OrderInfoPostData(tradeContext.mk, tradeContext.side, orderId));
OrderInfoPostData(tradeContext.market, tradeContext.side, orderId));
if (ret.is_discarded()) {
log::error("Cancel order process failed for {}, assuming order cancelled", exchangeName());
}
}

OrderInfo BithumbPrivate::queryOrderInfo(OrderIdView orderId, const TradeContext& tradeContext) {
const Market mk = tradeContext.mk;
const Market mk = tradeContext.market;
const CurrencyCode fromCurrencyCode = tradeContext.fromCur();
const CurrencyCode toCurrencyCode = tradeContext.toCur();

Expand Down
4 changes: 2 additions & 2 deletions src/api/exchanges/src/huobiprivateapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -604,7 +604,7 @@ PlaceOrderInfo HuobiPrivate::placeOrder(MonetaryAmount from, MonetaryAmount volu

PlaceOrderInfo placeOrderInfo(OrderInfo(TradedAmounts(fromCurrencyCode, toCurrencyCode)), OrderId("UndefinedId"));

const Market mk = tradeInfo.tradeContext.mk;
const Market mk = tradeInfo.tradeContext.market;
string lowerCaseMarket = mk.assetsPairStrLower();

const bool placeSimulatedRealOrder = _exchangePublic.exchangeConfig().placeSimulateRealOrder();
Expand Down Expand Up @@ -672,7 +672,7 @@ OrderInfo HuobiPrivate::cancelOrder(OrderIdView orderId, const TradeContext& tra
OrderInfo HuobiPrivate::queryOrderInfo(OrderIdView orderId, const TradeContext& tradeContext) {
const CurrencyCode fromCurrencyCode = tradeContext.fromCur();
const CurrencyCode toCurrencyCode = tradeContext.toCur();
const Market mk = tradeContext.mk;
const Market mk = tradeContext.market;

string endpoint(kBaseUrlOrders);
endpoint.append(orderId);
Expand Down
10 changes: 5 additions & 5 deletions src/api/exchanges/src/huobipublicapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ json::container PublicQuery(CurlHandle& curlHandle, std::string_view endpoint,

RequestRetry requestRetry(curlHandle, CurlOptions(HttpRequestType::kGet));

json::container jsonResponse = requestRetry.queryJson(method, [](const json::container& jsonResponse) {
json::container baseRet = requestRetry.queryJson(method, [](const json::container& jsonResponse) {
const auto dataIt = jsonResponse.find("data");
if (dataIt == jsonResponse.end()) {
const auto tickIt = jsonResponse.find("tick");
Expand All @@ -69,12 +69,12 @@ json::container PublicQuery(CurlHandle& curlHandle, std::string_view endpoint,
return RequestRetry::Status::kResponseOK;
});
json::container ret;
const auto dataIt = jsonResponse.find("data");
if (dataIt != jsonResponse.end()) {
const auto dataIt = baseRet.find("data");
if (dataIt != baseRet.end()) {
ret.swap(*dataIt);
} else {
const auto tickIt = jsonResponse.find("tick");
if (tickIt != jsonResponse.end()) {
const auto tickIt = baseRet.find("tick");
if (tickIt != baseRet.end()) {
ret.swap(*tickIt);
}
}
Expand Down
Loading

0 comments on commit 9782f53

Please sign in to comment.