csv.cpp
1#include "itch/output/csv.hpp"23#include <iomanip>4#include <sstream>56namespace itch {7namespace {89std::string price(uint32_t raw_price) {10 std::ostringstream out;11 out << raw_price / 10000 << '.' << std::setfill('0') << std::setw(4) << raw_price % 10000;12 return out.str();13}1415std::string depth(const std::vector<Level>& levels) {16 std::ostringstream out;17 for (size_t i = 0; i < levels.size(); ++i) {18 if (i) {19 out << '|';20 }21 out << price(levels[i].price) << ':' << levels[i].shares;22 }23 return out.str();24}2526} // namespace2728const char* csv_header(bool with_offset) {29 return with_offset ? "frame,timestamp_ns,type,bid,bid_shares,ask,ask_shares,bid_levels,ask_"30 "levels,bid_depth,ask_depth,byte_offset,byte_end_offset"31 : "frame,timestamp_ns,type,bid,bid_shares,ask,ask_shares,bid_levels,ask_"32 "levels,bid_depth,ask_depth";33}3435std::string csv_line(const Snapshot& snapshot, bool with_offset) {36 std::ostringstream out;37 out << snapshot.frame << ',' << snapshot.timestamp << ',' << snapshot.type << ',';38 if (snapshot.bids.empty()) {39 out << ',';40 } else {41 out << price(snapshot.bids.front().price) << ',' << snapshot.bids.front().shares;42 }43 out << ',';44 if (snapshot.asks.empty()) {45 out << ',';46 } else {47 out << price(snapshot.asks.front().price) << ',' << snapshot.asks.front().shares;48 }49 out << ',' << snapshot.bid_levels << ',' << snapshot.ask_levels << ',' << depth(snapshot.bids)50 << ',' << depth(snapshot.asks);51 if (with_offset) {52 out << ',' << snapshot.byte_offset << ',' << snapshot.byte_end_offset;53 }54 return out.str();55}5657} // namespace itch