Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
hyperliquid_l2_diff.cpp
Go to the documentation of this file.
3
4#include <openssl/evp.h>
5#include <zlib.h>
6
7#include <algorithm>
8#include <stdexcept>
9#include <unordered_map>
10#include <unordered_set>
11
12using namespace slick::sim;
13
14namespace {
15
16std::string format_price(price_t price) {
18}
19
20std::string format_qty(qty_t qty) {
22}
23
24// One side's changed/added levels (l) and removed indices (r).
25//
26// Keep the venue's ordering: l is best price first; r is ascending price,
27// which means descending index for bids. Set descending_index for bids only.
28// A client removing bids one at a time relies on that order. Ascending indices
29// would shift later entries, leave stale levels and desynchronise the book.
30void diff_side(const slick::sim::md_publisher::L2Levels& prev,
32 bool descending_index,
33 nlohmann::json& l_out, nlohmann::json& r_out) {
34 std::unordered_map<price_t, qty_t> prev_by_price;
35 prev_by_price.reserve(prev.size());
36 for (const auto& [price, qty] : prev) {
37 prev_by_price.emplace(price, qty);
38 }
39
40 std::unordered_set<price_t> curr_prices;
41 curr_prices.reserve(curr.size());
42 for (const auto& [price, qty] : curr) {
43 curr_prices.insert(price);
44 }
45
46 l_out = nlohmann::json::array();
47 for (const auto& [price, qty] : curr) {
48 auto it = prev_by_price.find(price);
49 if (it == prev_by_price.end() || it->second != qty) {
50 l_out.push_back({{"p", format_price(price)}, {"s", format_qty(qty)}});
51 }
52 }
53
54 r_out = nlohmann::json::array();
55 if (descending_index) {
56 for (size_t i = prev.size(); i-- > 0; ) {
57 if (!curr_prices.contains(prev[i].first)) {
58 r_out.push_back(i);
59 }
60 }
61 } else {
62 for (size_t i = 0; i < prev.size(); ++i) {
63 if (!curr_prices.contains(prev[i].first)) {
64 r_out.push_back(i);
65 }
66 }
67 }
68}
69
70std::string base64_encode(const std::vector<uint8_t>& data) {
71 if (data.empty()) return {};
72 std::string out(4 * ((data.size() + 2) / 3), '\0');
73 int len = EVP_EncodeBlock(
74 reinterpret_cast<unsigned char*>(out.data()),
75 data.data(), static_cast<int>(data.size()));
76 out.resize(static_cast<size_t>(len));
77 return out;
78}
79
80} // namespace
81
83
84void split_book_snapshot(const MDLevel* levels, uint32_t num_bid, uint32_t num_ask,
85 nlohmann::json::array_t& bids, nlohmann::json::array_t& asks,
86 L2Levels& curr_bid, L2Levels& curr_ask) {
87 const uint32_t bid_count = std::min(num_bid, L2_PUBLISH_DEPTH);
88 const uint32_t ask_count = std::min(num_ask, L2_PUBLISH_DEPTH);
89
90 bids.clear();
91 asks.clear();
92 curr_bid.clear();
93 curr_ask.clear();
94 bids.reserve(bid_count);
95 asks.reserve(ask_count);
96 curr_bid.reserve(bid_count);
97 curr_ask.reserve(ask_count);
98
99 // MDLevel is declared under `#pragma pack(1)`, so every level past the first
100 // starts at an odd offset and its members are underaligned. Load them into
101 // locals before handing them on: json's converting constructor and
102 // emplace_back both bind `const T&`, and a reference to an underaligned
103 // member is UB - UBSan's alignment check fails the build on it.
104 auto emit = [](const MDLevel& level, nlohmann::json::array_t& out, L2Levels& baseline) {
105 const price_t price = level.price;
106 const qty_t qty = level.qty;
107 const uint32_t num_orders = level.num_orders;
108 out.push_back({
109 {"px", format_price(price)},
110 {"sz", format_qty(qty)},
111 {"n", num_orders}
112 });
113 baseline.emplace_back(price, qty);
114 };
115
116 for (uint32_t i = 0; i < bid_count; ++i) {
117 emit(levels[i], bids, curr_bid);
118 }
119 // The ask block starts after every bid the frame carries, not after the ones
120 // published: truncating the bids must not walk the read cursor back.
121 for (uint32_t i = 0; i < ask_count; ++i) {
122 emit(levels[num_bid + i], asks, curr_ask);
123 }
124}
125
126L2Diff compute_l2_diff(const L2Levels& prev_bid, const L2Levels& prev_ask,
127 const L2Levels& curr_bid, const L2Levels& curr_ask) {
128 nlohmann::json l_bid, r_bid, l_ask, r_ask;
129 diff_side(prev_bid, curr_bid, /*descending_index=*/true, l_bid, r_bid);
130 diff_side(prev_ask, curr_ask, /*descending_index=*/false, l_ask, r_ask);
131
132 L2Diff diff;
133 diff.l = nlohmann::json::array({std::move(l_bid), std::move(l_ask)});
134 diff.r = nlohmann::json::array({std::move(r_bid), std::move(r_ask)});
135 return diff;
136}
137
138std::string encode_l2_diff(const nlohmann::json& payload) {
139 const std::string plain = payload.dump();
140
141 z_stream stream{};
142 if (deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
143 throw std::runtime_error("Failed to initialize raw deflate encoder");
144 }
145 stream.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(plain.data()));
146 stream.avail_in = static_cast<uInt>(plain.size());
147
148 std::vector<uint8_t> compressed(deflateBound(&stream, static_cast<uLong>(plain.size())));
149 stream.next_out = compressed.data();
150 stream.avail_out = static_cast<uInt>(compressed.size());
151
152 int result = deflate(&stream, Z_FINISH);
153 size_t produced = compressed.size() - stream.avail_out;
154 deflateEnd(&stream);
155 if (result != Z_STREAM_END) {
156 throw std::runtime_error("Failed to deflate l2 diff payload");
157 }
158 compressed.resize(produced);
159
160 return base64_encode(compressed);
161}
162
163} // end namespace slick::sim::md_publisher
std::vector< std::pair< price_t, qty_t > > L2Levels
std::string encode_l2_diff(const nlohmann::json &payload)
void split_book_snapshot(const MDLevel *levels, uint32_t num_bid, uint32_t num_ask, nlohmann::json::array_t &bids, nlohmann::json::array_t &asks, L2Levels &curr_bid, L2Levels &curr_ask)
constexpr uint32_t L2_PUBLISH_DEPTH
std::string to_hyperliquid_number(int_fast64_t value)
Formats a fixed-point price or size as Hyperliquid does on the wire.
L2Diff compute_l2_diff(const L2Levels &prev_bid, const L2Levels &prev_ask, const L2Levels &curr_bid, const L2Levels &curr_ask)
int_fast64_t qty_t
Definition types.hpp:22
int_fast64_t price_t
Definition types.hpp:21