book.hpp
1#pragma once23#include "itch/feed/itch/event.hpp"45#include <cstddef>6#include <cstdint>7#include <map>8#include <optional>9#include <string>10#include <unordered_map>11#include <vector>1213namespace itch {1415struct Level {16 uint32_t price;17 uint64_t shares;18};1920struct LiveOrder {21 uint64_t id;22 char side;23 uint32_t shares, price;24};2526struct BookState {27 std::optional<uint16_t> locate;28 std::vector<LiveOrder> orders;29 std::vector<Level> bids, asks;30};3132struct Snapshot {33 uint64_t frame, timestamp;34 char type;35 std::vector<Level> bids, asks;36 size_t bid_levels, ask_levels;37 uint64_t byte_offset = 0;38 uint64_t byte_end_offset = 0;39};4041/** Reconstruct the displayed order book for one symbol from ordered ITCH events.42 * Instances are not thread-safe. After apply() fails, discard the instance rather than continue.43 */44class Book {45 public:46 explicit Book(std::string target);47 /** Apply one event; nullopt means directory-only or a different symbol.48 * max_depth limits the snapshot, not the stored price levels.49 * check_book enables a full order-to-level invariant check after each selected event.50 * Throws std::runtime_error on invalid order operations or inconsistent symbol/locate data.51 */52 std::optional<Snapshot> apply(const Event& event, size_t max_depth, bool check_book);53 /** Export deterministic state: orders sorted by ID and levels by ascending price. */54 BookState state() const;55 /** Inspect an existing order without copying the book (market trade adapter). */56 std::optional<LiveOrder> order(uint64_t id) const;57 /** Validate a saved state and replace the book only after all checks succeed.58 * frame identifies the checkpoint boundary in diagnostics; throws std::runtime_error on59 * failure.60 */61 void restore(const BookState& state, uint64_t frame);6263 private:64 struct Order {65 char side;66 uint32_t shares;67 uint32_t price;68 };6970 [[noreturn]] static void fail(uint64_t frame, const char* reason);71 void apply_directory(const Event& event);72 // Returns false for another symbol; selected adds update orders and levels together.73 bool add_order(const Event& event);74 // Reduce, delete or replace an existing order after locate selection.75 void change_order(const Event& event);76 void change_level(char side, uint32_t price, uint32_t shares, bool add, uint64_t frame);77 void verify_levels(uint64_t frame) const;78 Snapshot snapshot(const Event& event, size_t max_depth) const;7980 std::string target_;81 std::optional<uint16_t> locate_;82 std::unordered_map<uint64_t, Order> orders_;83 std::map<uint32_t, uint64_t> bids_, asks_;84};8586} // namespace itch