Files
spark/src/lib/domain/BookLevel.h
T

104 lines
3.0 KiB
C++

#pragma once
#include "Price.h"
#include "Quantity.h"
#include "lib/io/JsonReader.h"
#include <cstddef>
#include <nlohmann/json.hpp>
namespace bts::domain {
class BookLevel {
public:
Price price = {};
Quantity total_quantity = {};
Quantity direct_quantity = {};
std::size_t n_orders = {};
/**
* @brief Gets an empty book
*
* @details This method offers protection against changes to the default
* constructor. For example, the default constructor could be optimized
* one day so that members aren't initialized at all. No matter what
* changes the future brings, this method will always return an empty book.
*
* @return An empty BookLevel
*/
static constexpr BookLevel empty() noexcept;
constexpr bool is_empty() const noexcept;
constexpr Quantity implied_quantity() const;
};
void from_json(const nlohmann::json &j, BookLevel &bl);
void to_json(nlohmann::json &j, const BookLevel &bl);
constexpr bool operator==(const BookLevel &lhs, const BookLevel &rhs);
constexpr bool operator!=(const BookLevel &lhs, const BookLevel &rhs);
std::ostream &operator<<(std::ostream &out, const BookLevel &lvl) noexcept;
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
constexpr BookLevel BookLevel::empty() noexcept {
return {Price::nan(), Quantity{0}, Quantity{0}, 0};
}
constexpr bool BookLevel::is_empty() const noexcept {
return total_quantity == 0 || price.is_nan();
}
constexpr Quantity BookLevel::implied_quantity() const {
return total_quantity - direct_quantity;
}
inline void from_json(const nlohmann::json &j, BookLevel &bl) {
io::JsonReader jr{&j};
bool success = jr.read("price", bl.price) &&
jr.read("total_qty", bl.total_quantity) &&
jr.read("direct_qty", bl.direct_quantity) &&
jr.read("n_orders", bl.n_orders);
if (!success) {
const auto j_str = j.dump(2);
LOG(md, Error, "Failed to parse json to BookLevel:\n{}", j_str);
}
}
inline void to_json(nlohmann::json &j, const BookLevel &bl) {
j = nlohmann::json{
{"price", bl.price},
{"total_qty", bl.total_quantity},
{"direct_qty", bl.direct_quantity},
{"n_orders", bl.n_orders},
};
}
constexpr bool operator==(const BookLevel &lhs, const BookLevel &rhs) {
return lhs.direct_quantity == rhs.direct_quantity &&
lhs.total_quantity == rhs.total_quantity &&
lhs.n_orders == rhs.n_orders &&
(lhs.price == rhs.price ||
(lhs.price.is_nan() && rhs.price.is_nan()));
}
constexpr bool operator!=(const BookLevel &lhs, const BookLevel &rhs) {
return !(lhs == rhs);
}
inline std::ostream &operator<<(
std::ostream &out, const BookLevel &lvl) noexcept {
out << lvl.price << " (" << lvl.direct_quantity;
if (lvl.direct_quantity != lvl.total_quantity) {
out << "/" << lvl.total_quantity;
}
if (lvl.n_orders != 0) {
out << ", " << lvl.n_orders;
}
out << ")";
return out;
}
} // namespace bts::domain