Skip to content

Commit

Permalink
Possibility to export output in json
Browse files Browse the repository at this point in the history
  • Loading branch information
sjanel committed May 30, 2022
1 parent ac0dd11 commit c533cf2
Show file tree
Hide file tree
Showing 42 changed files with 3,220 additions and 441 deletions.
16 changes: 8 additions & 8 deletions CONFIG.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,11 @@ Contains options that are not exchange specific.

#### Options description

| Name | Value | Description |
| ---------------------- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **fiatConversionRate** | Duration string (ex: `8h`) | Minimum time between two consecutive requests of the same fiat conversion |
| **log.file** | Boolean | If `true`, will log in rotating files instead of standard output |
| **log.level** | String | Defines the log level. Can be {'off', 'critical', 'error', 'warning', 'info', 'debug', 'trace'} |
| **log.maxFileSize** | String (ex: `5Mi` for 5 Megabytes) | Defines in bytes the maximum logging file size. A string representation of an integral, possibly with one suffix ending such as k, M, G, T (1k multipliers) or Ki, Mi, Gi, Ti (1024 multipliers) are supported. |
| **log.maxNbFiles** | Integer | Number of maximum rotating files for log in files |
| **printResults** | Boolean | Print query results if `true` |
| Name | Value | Description |
| ---------------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **apiOutputType** | String among {`off`, `table`, `json`} | Configure the output type of coincenter queries |
| **fiatConversionRate** | Duration string (ex: `8h`) | Minimum time between two consecutive requests of the same fiat conversion |
| **log.file** | Boolean | If `true`, will log in rotating files instead of standard output |
| **log.level** | String | Defines the log level. Can be {'off', 'critical', 'error', 'warning', 'info', 'debug', 'trace'} |
| **log.maxFileSize** | String (ex: `5Mi` for 5 Megabytes) | Defines in bytes the maximum logging file size. A string representation of an integral, possibly with one suffix ending such as k, M, G, T (1k multipliers) or Ki, Mi, Gi, Ti (1024 multipliers) are supported. |
| **log.maxNbFiles** | Integer | Number of maximum rotating files for log in files |
26 changes: 24 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ Main features:
- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
- [General](#general)
- [Input / output](#input--output)
- [Format](#format)
- [Logging](#logging)
- [Public requests](#public-requests)
- [Markets](#markets)
Expand Down Expand Up @@ -110,7 +111,28 @@ See [CONFIG.md](CONFIG.md)

# Usage

## General
## Input / output

### Format

`coincenter` is a command line tool with ergonomic and easy to remember option schema. You will usually provide this kind of input:
- Command name, with short hand flag or long name (check with `-h` or `--help`)
- Followed by either:
- Nothing, meaning that command will be applied globally
- Amount with currency or any currency, separated by dash to specify pairs, or source - destination
- Comma separated list of exchanges (all are considered if not provided)

Example:
```
Ori curr. exchange1
| |
coincenter --trade 0.05BTC-USDT,kraken,huobi
| | |
from amt. to curr. exchange2
```

By default, result of command is printed in a formatted table on standard output.
You can also choose a *json* output format with option `-o json`.

### Logging

Expand Down
2 changes: 2 additions & 0 deletions src/api-objects/include/exchangeprivateapitypes.hpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
#pragma once

#include "cct_flatset.hpp"
#include "cct_vector.hpp"
#include "order.hpp"

namespace cct {
using Orders = vector<Order>;
using OrdersSet = FlatSet<Order>;
} // namespace cct
8 changes: 5 additions & 3 deletions src/api-objects/include/withdrawinfo.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ using WithdrawIdView = std::string_view;
namespace api {
class InitiatedWithdrawInfo {
public:
InitiatedWithdrawInfo(Wallet receivingWallet, WithdrawIdView withdrawId, MonetaryAmount grossEmittedAmount);
InitiatedWithdrawInfo(Wallet receivingWallet, WithdrawIdView withdrawId, MonetaryAmount grossEmittedAmount,
TimePoint initiatedTime = Clock::now());

TimePoint initiatedTime() const { return _initiatedTime; }

Expand Down Expand Up @@ -52,10 +53,11 @@ class SentWithdrawInfo {
class WithdrawInfo {
public:
/// Empty withdraw info, when no withdrawal has been done
WithdrawInfo(string &&msg = string()) : _withdrawIdOrMsgIfNotInitiated(std::move(msg)) {}
explicit WithdrawInfo(string &&msg = string()) : _withdrawIdOrMsgIfNotInitiated(std::move(msg)) {}

/// Constructs a withdraw info with all information
WithdrawInfo(const api::InitiatedWithdrawInfo &initiatedWithdrawInfo, const api::SentWithdrawInfo &sentWithdrawInfo);
WithdrawInfo(const api::InitiatedWithdrawInfo &initiatedWithdrawInfo, const api::SentWithdrawInfo &sentWithdrawInfo,
TimePoint receivedTime = Clock::now());

bool hasBeenInitiated() const { return _initiatedTime != TimePoint{}; }

Expand Down
8 changes: 4 additions & 4 deletions src/api-objects/src/withdrawinfo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@
namespace cct {
namespace api {
InitiatedWithdrawInfo::InitiatedWithdrawInfo(Wallet receivingWallet, WithdrawIdView withdrawId,
MonetaryAmount grossEmittedAmount)
MonetaryAmount grossEmittedAmount, TimePoint initiatedTime)
: _receivingWallet(std::move(receivingWallet)),
_withdrawIdOrMsgIfNotInitiated(withdrawId),
_initiatedTime(Clock::now()),
_initiatedTime(initiatedTime),
_grossEmittedAmount(grossEmittedAmount) {}
} // namespace api

WithdrawInfo::WithdrawInfo(const api::InitiatedWithdrawInfo &initiatedWithdrawInfo,
const api::SentWithdrawInfo &sentWithdrawInfo)
const api::SentWithdrawInfo &sentWithdrawInfo, TimePoint receivedTime)
: _receivingWallet(initiatedWithdrawInfo.receivingWallet()),
_withdrawIdOrMsgIfNotInitiated(initiatedWithdrawInfo.withdrawId()),
_initiatedTime(initiatedWithdrawInfo.initiatedTime()),
_receivedTime(Clock::now()),
_receivedTime(receivedTime),
_netEmittedAmount(sentWithdrawInfo.netEmittedAmount()) {}

const WithdrawId &WithdrawInfo::withdrawId() const {
Expand Down
3 changes: 0 additions & 3 deletions src/api/common/src/exchangeprivateapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,6 @@ TradedAmounts ExchangePrivate::trade(MonetaryAmount from, CurrencyCode toCurrenc
tradedAmounts.tradedTo = stepTradedAmounts.tradedTo;
}
}
if (!options.isSimulation() || realOrderPlacedInSimulationMode) {
log::info("**** Traded {} into {} ****", tradedAmounts.tradedFrom.str(), tradedAmounts.tradedTo.str());
}
return tradedAmounts;
}

Expand Down
1 change: 0 additions & 1 deletion src/api/exchanges/src/bithumbprivateapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
#include <algorithm>
#include <cassert>
#include <execution>
#include <iostream>
#include <thread>

#include "apikey.hpp"
Expand Down
11 changes: 11 additions & 0 deletions src/engine/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ add_unit_test(
coincenter_objects
)

add_unit_test(
queryresultprinter_test
src/balanceperexchangeportfolio.cpp
src/coincentercommandtype.cpp
src/queryresultprinter.cpp
test/queryresultprinter_test.cpp
LIBRARIES
coincenter_exchangeapi
coincenter_objects
)

add_unit_test(
stringoptionparser_test
src/stringoptionparser.cpp
Expand Down
19 changes: 10 additions & 9 deletions src/engine/include/balanceperexchangeportfolio.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,27 @@

#include <ostream>

#include "balanceportfolio.hpp"
#include "cct_const.hpp"
#include "cct_smallvector.hpp"
#include "exchangename.hpp"
#include "cct_json.hpp"
#include "queryresulttypes.hpp"

namespace cct {
class BalancePerExchangePortfolio {
public:
void add(ExchangeName exchangeName, BalancePortfolio balancePortfolio);
explicit BalancePerExchangePortfolio(const BalancePerExchange &balancePerExchange)
: _balancePerExchange(balancePerExchange) {}

/// Pretty print table of balance.
/// @param wide if true, all exchange amount will be printed as well
void print(std::ostream &os, bool wide) const;
void printTable(std::ostream &os, bool wide) const;

/// Print in json format.
json printJson(CurrencyCode equiCurrency) const;

private:
// +1 for total in first position
using BalancePortfolioVector = SmallVector<BalancePortfolio, kTypicalNbPrivateAccounts + 1>;
BalancePortfolio computeTotal() const;

BalancePortfolioVector _balances{1};
ExchangeNames _exchanges;
const BalancePerExchange &_balancePerExchange;
};

} // namespace cct
2 changes: 1 addition & 1 deletion src/engine/include/coincenter.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class Coincenter {
ConversionPathPerExchange getConversionPaths(Market m, ExchangeNameSpan exchangeNames);

/// Get withdraw fees for all exchanges from given list (or all exchanges if list is empty)
WithdrawFeePerExchange getWithdrawFees(CurrencyCode currencyCode, ExchangeNameSpan exchangeNames);
MonetaryAmountPerExchange getWithdrawFees(CurrencyCode currencyCode, ExchangeNameSpan exchangeNames);

/// Trade a specified amount of a given currency into another one, using the market defined in the given exchanges.
/// If no exchange name is given, it will attempt to trade given amount on all exchanges with the sufficient balance.
Expand Down
28 changes: 4 additions & 24 deletions src/engine/include/coincentercommand.hpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#pragma once

#include <cstdint>
#include <variant>

#include "coincentercommandtype.hpp"
#include "currencycode.hpp"
#include "exchangename.hpp"
#include "market.hpp"
Expand All @@ -13,27 +13,7 @@
namespace cct {
class CoincenterCommand {
public:
enum class Type : int8_t {
kMarkets,
kConversionPath,
kLastPrice,
kTicker,
kOrderbook,
kLastTrades,
kLast24hTradedVolume,
kWithdrawFee,

kBalance,
kDepositInfo,
kOrdersOpened,
kOrdersCancel,
kTrade,
kBuy,
kSell,
kWithdraw,
};

explicit CoincenterCommand(Type type) : _type(type) {}
explicit CoincenterCommand(CoincenterCommandType type) : _type(type) {}

CoincenterCommand& setExchangeNames(const ExchangeNames& exchangeNames);
CoincenterCommand& setExchangeNames(ExchangeNames&& exchangeNames);
Expand Down Expand Up @@ -78,7 +58,7 @@ class CoincenterCommand {
CurrencyCode cur1() const { return _cur1; }
CurrencyCode cur2() const { return _cur2; }

Type type() const { return _type; }
CoincenterCommandType type() const { return _type; }

bool isPercentageAmount() const { return _isPercentageAmount; }

Expand All @@ -94,7 +74,7 @@ class CoincenterCommand {
int _n = -1;
Market _market;
CurrencyCode _cur1, _cur2;
Type _type;
CoincenterCommandType _type;
bool _isPercentageAmount = false;
};

Expand Down
28 changes: 28 additions & 0 deletions src/engine/include/coincentercommandtype.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#pragma once

#include <cstdint>
#include <string_view>

namespace cct {
enum class CoincenterCommandType : int8_t {
kMarkets,
kConversionPath,
kLastPrice,
kTicker,
kOrderbook,
kLastTrades,
kLast24hTradedVolume,
kWithdrawFee,

kBalance,
kDepositInfo,
kOrdersOpened,
kOrdersCancel,
kTrade,
kBuy,
kSell,
kWithdraw,
};

std::string_view CoincenterCommandTypeToString(CoincenterCommandType type);
} // namespace cct
30 changes: 11 additions & 19 deletions src/engine/include/coincenteroptions.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,14 @@ struct CoincenterCmdLineOptions {
static constexpr int64_t kDefaultRepeatDurationSeconds =
std::chrono::duration_cast<std::chrono::seconds>(kDefaultRepeatTime).count();

static constexpr std::string_view kSingleQuote = "'";
static constexpr std::string_view kClosingParenthesis = ")";
static constexpr std::string_view kOutput1 = "Output format. One of (";
static constexpr std::string_view kOutput2 = ") (default configured in general config file)";
static constexpr std::string_view kOutput =
JoinStringView_v<kOutput1, kApiOutputTypeNoPrintStr, CharToStringView_v<'|'>, kApiOutputTypeTableStr,
CharToStringView_v<'|'>, kApiOutputTypeJsonStr, kOutput2>;

static constexpr std::string_view kData1 = "Use given 'data' directory instead of the one chosen at build time '";
static constexpr std::string_view kData = JoinStringView_v<kData1, kDefaultDataDir, kSingleQuote>;
static constexpr std::string_view kData = JoinStringView_v<kData1, kDefaultDataDir, CharToStringView_v<'\''>>;

static constexpr std::string_view kRepeat1 = "Set delay between each repeat (default: ";
static constexpr std::string_view kRepeat2 = "s)";
Expand All @@ -44,7 +47,7 @@ struct CoincenterCmdLineOptions {
static constexpr std::string_view kLastTradesN1 = "Change number of last trades to query (default: ";
static constexpr std::string_view kLastTradesN =
JoinStringView_v<kLastTradesN1, IntToStringView_v<api::ExchangePublic::kNbLastTradesDefault>,
kClosingParenthesis>;
CharToStringView_v<')'>>;

static constexpr std::string_view kSmartBuy1 =
"Attempt to buy the specified amount in total, on matching exchange accounts (all are considered if none "
Expand Down Expand Up @@ -98,23 +101,22 @@ struct CoincenterCmdLineOptions {
static constexpr std::string_view kMonitoringPort1 = "Specify port of metric gateway instance (default: ";
static constexpr std::string_view kMonitoringPort =
JoinStringView_v<kMonitoringPort1, IntToStringView_v<CoincenterCmdLineOptions::kDefaultMonitoringPort>,
kClosingParenthesis>;
CharToStringView_v<')'>>;

static constexpr std::string_view kMonitoringIP1 = "Specify IP (v4) of metric gateway instance (default: ";
static constexpr std::string_view kMonitoringIP =
JoinStringView_v<kMonitoringIP1, CoincenterCmdLineOptions::kDefaultMonitoringIPAddress, kClosingParenthesis>;
JoinStringView_v<kMonitoringIP1, CoincenterCmdLineOptions::kDefaultMonitoringIPAddress, CharToStringView_v<')'>>;

static void PrintVersion(std::string_view programName);

std::string_view dataDir = kDefaultDataDir;

std::string_view apiOutputType;
std::string_view logLevel;
bool help = false;
bool version = false;
bool logFile = false;
bool logConsole = false;
bool printResults = false;
bool noPrintResults = false;
std::optional<std::string_view> nosecrets;
CommandLineOptionalInt repeats;
Duration repeatTime = kDefaultRepeatTime;
Expand Down Expand Up @@ -192,16 +194,7 @@ struct CoincenterAllowedOptions {
&OptValueType::logConsole},
{{{"General", 4}, "--log-file", "", "Log to rotating files (default configured in general config file)"},
&OptValueType::logFile},
{{{"General", 5},
"--print",
"",
"Force print results in standard output (default configured in general config file)"},
&OptValueType::printResults},
{{{"General", 6},
"--no-print",
"",
"Force no print of results in standard output (default configured in general config file)"},
&OptValueType::noPrintResults},
{{{"General", 5}, "--output", 'o', "", CoincenterCmdLineOptions::kOutput}, &OptValueType::apiOutputType},
{{{"General", 7},
"--no-secrets",
"<[exch1,...]>",
Expand Down Expand Up @@ -229,7 +222,6 @@ struct CoincenterAllowedOptions {

{{{"Public queries", 20},
"--orderbook",
'o',
"<cur1-cur2[,exch1,...]>",
"Print order book of currency pair for all exchanges offering "
"this market, or only for specified exchanges."},
Expand Down
2 changes: 1 addition & 1 deletion src/engine/include/commandlineoptionsparser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <map>
#include <memory>
#include <optional>
#include <ostream>
#include <span>
#include <string_view>

Expand Down
2 changes: 1 addition & 1 deletion src/engine/include/exchangesorchestrator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class ExchangesOrchestrator {
const ExchangeName &fromPrivateExchangeName, const ExchangeName &toPrivateExchangeName,
Duration withdrawRefreshTime = api::ExchangePrivate::kWithdrawInfoRefreshTime);

WithdrawFeePerExchange getWithdrawFees(CurrencyCode currencyCode, ExchangeNameSpan exchangeNames);
MonetaryAmountPerExchange getWithdrawFees(CurrencyCode currencyCode, ExchangeNameSpan exchangeNames);

MonetaryAmountPerExchange getLast24hTradedVolumePerExchange(Market m, ExchangeNameSpan exchangeNames);

Expand Down
Loading

0 comments on commit c533cf2

Please sign in to comment.