kraken: parse: add input file parser

This commit is contained in:
Bruno BELANYI 2022-03-12 01:54:51 +01:00
parent 9550598a87
commit 12f458cf94
3 changed files with 99 additions and 0 deletions

View file

@ -1,9 +1,12 @@
add_library(parse STATIC add_library(parse STATIC
order.cc order.cc
order.hh order.hh
parse.cc
parse.hh
) )
target_link_libraries(parse PRIVATE target_link_libraries(parse PRIVATE
csv
utils utils
) )

79
src/parse/parse.cc Normal file
View file

@ -0,0 +1,79 @@
#include "parse.hh"
#include <string>
#include <cassert>
#include "csv/read-csv.hh"
namespace kraken::parse {
namespace {
Side parse_side(std::string_view side) {
if (side == "B") {
return Side::BID;
} else if (side == "S") {
return Side::ASK;
} else {
throw ParseError("Not a valid side");
}
}
TradeOrder trade_from_raw(csv::csv_line_type const& raw_order) {
assert(raw_order[0] == "N");
if (raw_order.size() != 7) {
throw ParseError("Not a valid trade order");
}
auto const user = User{std::stoi(raw_order[1])};
auto const symbol = Symbol{raw_order[2]};
auto const price = Price{std::stoi(raw_order[3])};
auto const quantity = Quantity{std::stoi(raw_order[4])};
auto const side = Side{parse_side(raw_order[5])};
auto const id = UserOrderId{std::stoi(raw_order[6])};
return TradeOrder{
user, symbol, price, quantity, side, id,
};
}
CancelOrder cancel_from_raw(csv::csv_line_type const& raw_order) {
assert(raw_order[0] == "C");
if (raw_order.size() != 3) {
throw ParseError("Not a valid cancel order");
}
auto const user = User{std::stoi(raw_order[1])};
auto const id = UserOrderId{std::stoi(raw_order[2])};
return CancelOrder{
user,
id,
};
}
} // namespace
std::vector<Order> parse_orders(std::istream& input) {
auto const raw_orders = read_csv(input, kraken::csv::CsvHeader::KEEP);
auto orders = std::vector<Order>{};
for (auto const& raw_order : raw_orders) {
if (raw_order[0] == "N") {
orders.emplace_back(trade_from_raw(raw_order));
} else if (raw_order[0] == "C") {
orders.emplace_back(cancel_from_raw(raw_order));
} else if (raw_order[0] == "F") {
orders.emplace_back(FlushOrder{});
} else {
throw ParseError("Not a valid order");
}
}
return orders;
}
} // namespace kraken::parse

17
src/parse/parse.hh Normal file
View file

@ -0,0 +1,17 @@
#pragma once
#include <iosfwd>
#include <stdexcept>
#include <vector>
#include "order.hh"
namespace kraken::parse {
struct ParseError : public std::runtime_error {
using std::runtime_error::runtime_error;
};
std::vector<Order> parse_orders(std::istream& input);
} // namespace kraken::parse