Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
hyperliquid_publisher.cpp
Go to the documentation of this file.
1#include <slick/logger.hpp>
6#include <utils/timestamp.hpp>
7#include <cstring>
8#include <format>
9
10using namespace slick::sim::md_publisher;
11using namespace slick::sim;
12using namespace slick::sim::utils;
13
15
17 const json& config,
18 slick::queue<Request>& request_queue,
19 slick::queue<uint8_t>& market_data_queue
20)
21 : WebsocketMarketDataPublisher(Venue::HYPERLIQUID, request_queue, market_data_queue, config.value("port", 5001))
22 , upstream_base_url_(config.value("upstream_base_url", "https://api.hyperliquid.xyz"))
23{}
24
25// void HyperliquidPublisher::start() {
26// running_.store(true, std::memory_order_release);
27// ws_thread_ = std::thread([this]() {
28// auto app = uWS::App();
29
30// app.ws<HyperliquidPerSocketData>("/*", {
31// .compression = uWS::SHARED_COMPRESSOR,
32// .maxPayloadLength = 2 << 24,
33// .idleTimeout = 120,
34// .maxBackpressure = 2 << 25,
35// .upgrade = nullptr,
36
37// .open = [this](auto* ws) {
38// ws->getUserData()->last_pong = std::chrono::steady_clock::now();
39// clients_.emplace(ws);
40// LOG_INFO("HyperliquidPublisher client connected {:p}", (void*)ws);
41// },
42
43// .message = [this](auto* ws, std::string_view message, uWS::OpCode) {
44// handleMessage(ws, message);
45// },
46
47// .drain = [](auto*) {},
48
49// .ping = [](auto* ws, std::string_view) {
50// LOG_TRACE("HyperliquidPublisher ping from {:p}", (void*)ws);
51// },
52
53// .pong = [this](auto* ws, std::string_view) {
54// ws->getUserData()->last_pong = std::chrono::steady_clock::now();
55// },
56
57// .close = [this](auto* ws, int code, std::string_view msg) {
58// handleClose(ws, code, msg);
59// }
60// })
61// .listen(port_, [this](auto* listen_socket) {
62// listen_socket_ = listen_socket;
63// if (listen_socket) {
64// LOG_INFO("HyperliquidPublisher started on port {}", port_);
65// loop_ = uWS::Loop::get();
66// loop_->defer([this]() {
67// heartbeat_timer_ = us_create_timer((struct us_loop_t*)loop_, 0, 0);
68// *((HyperliquidPublisher**)us_timer_ext(heartbeat_timer_)) = this;
69// us_timer_set(heartbeat_timer_, [](struct us_timer_t* t) {
70// (*((HyperliquidPublisher**)us_timer_ext(t)))->checkHeartbeats();
71// }, ping_interval_ms_, ping_interval_ms_);
72// });
73// schedulePublishProcessing();
74// } else {
75// LOG_ERROR("HyperliquidPublisher failed to listen on port {}", port_);
76// }
77// })
78// .run();
79// });
80// }
81
82// void HyperliquidPublisher::stop() {
83// running_.store(false, std::memory_order_release);
84// if (heartbeat_timer_) {
85// us_timer_close(heartbeat_timer_);
86// heartbeat_timer_ = nullptr;
87// }
88// if (listen_socket_ && loop_) {
89// // Closing the listen socket must happen on the loop's own thread;
90// // doing it cross-thread races with the loop's poll handles.
91// loop_->defer([this]() {
92// if (listen_socket_) {
93// us_listen_socket_close(0, listen_socket_);
94// listen_socket_ = nullptr;
95// }
96// });
97// }
98// if (ws_thread_.joinable()) {
99// ws_thread_.join();
100// }
101// }
102
103// void HyperliquidPublisher::schedulePublishProcessing() {
104// if (!running_.load(std::memory_order_acquire) || !loop_) return;
105// loop_->defer([this]() { publishMarketDataUpdate(); });
106// }
107
108void HyperliquidPublisher::setup_routes(uWS::App &app) {
109 app.ws<HyperliquidPerSocketData>("/*", {
110 .compression = uWS::SHARED_COMPRESSOR,
111 .maxPayloadLength = 2 << 24,
112 .idleTimeout = 120,
113 .maxBackpressure = 2 << 25,
114 .upgrade = nullptr,
115
116 .open = [this](auto* ws) {
117 ws->getUserData()->last_pong = std::chrono::steady_clock::now();
118 clients_.emplace(ws);
119 LOG_INFO("HyperliquidPublisher client connected {:p}", (void*)ws);
120 },
121
122 .message = [this](auto* ws, std::string_view message, uWS::OpCode) {
123 handle_message(ws, message);
124 },
125
126 .drain = [](auto*) {},
127
128 .ping = [](auto* ws, std::string_view) {
129 LOG_TRACE("HyperliquidPublisher ping from {:p}", (void*)ws);
130 },
131
132 .pong = [this](auto* ws, std::string_view) {
133 ws->getUserData()->last_pong = std::chrono::steady_clock::now();
134 },
135
136 .close = [this](auto* ws, int code, std::string_view msg) {
137 handle_close(ws, code, msg);
138 }
139 });
140
141 app.post("/info", [this](auto* res, auto* req) {
142 handle_info(res, req);
143 });
144}
145
146void HyperliquidPublisher::handle_info(uWS::HttpResponse<false>* res, uWS::HttpRequest*) {
147 proxy_hyperliquid_info_request(res, upstream_base_url_);
148}
149
150void HyperliquidPublisher::publish_market_data_update(MarketDataUpdate* update) {
151 switch (update->type) {
153 publish_subscription_response(update);
154 break;
156 publish_book_snapshot(update);
157 break;
159 publish_trade_summary(update);
160 break;
161 default:
162 break;
163 }
164}
165
166void HyperliquidPublisher::handle_message(wsT* ws, std::string_view message) {
167 try {
168 json msg = json::parse(message);
169
170 std::string method = msg.value("method", "");
171 if (method == "ping") {
172 json pong = {{"channel", "pong"}};
173 ws->send(pong.dump(), uWS::OpCode::TEXT);
174 return;
175 }
176
177 if (method != "subscribe" && method != "unsubscribe") {
178 send_error(ws, std::format("method `{}` is not supported", method));
179 return;
180 }
181
182 if (!msg.contains("subscription")) {
183 send_error(ws, "missing `subscription` field");
184 return;
185 }
186
187 const auto& sub = msg["subscription"];
188 std::string type = sub.value("type", "");
189
190 if (type == "l2Book") {
191 std::string coin = sub.value("coin", "");
192 if (coin.empty()) { send_error(ws, "missing `coin` in subscription"); return; }
193 if (method == "subscribe") {
194 subscribe_channel(ws, HyperliquidChannel::L2_BOOK, coin);
195 }
196 } else if (type == "trades") {
197 std::string coin = sub.value("coin", "");
198 if (coin.empty()) { send_error(ws, "missing `coin` in subscription"); return; }
199 if (method == "subscribe") {
200 subscribe_channel(ws, HyperliquidChannel::TRADES, coin);
201 }
202 } else if (type == "l2") {
203 // Undocumented channel — coin is field "c", not "coin".
204 std::string coin = sub.value("c", "");
205 if (coin.empty()) { send_error(ws, "missing `c` in subscription"); return; }
206 if (method == "subscribe") {
207 // Real Hyperliquid acks "l2" subscriptions immediately by
208 // echoing the subscription back, ahead of any snapshot data.
209 json ack = {
210 {"channel", "subscriptionResponse"},
211 {"data", {{"method", "subscribe"}, {"subscription", sub}}}
212 };
213 ws->send(ack.dump(), uWS::OpCode::TEXT);
214 subscribe_channel(ws, HyperliquidChannel::L2, coin);
215 }
216 } else if (type == "heartbeat") {
217 ws->getUserData()->subscribed_heartbeat = true;
218 json rsp = {{"channel", "subscriptions"}, {"data", {{"type", "heartbeat"}}}};
219 ws->send(rsp.dump(), uWS::OpCode::TEXT);
220 } else {
221 send_error(ws, std::format("subscription type `{}` is not supported", type));
222 }
223 } catch (const json::parse_error& e) {
224 send_error(ws, std::string("invalid JSON: ") + e.what());
225 }
226}
227
228void HyperliquidPublisher::subscribe_channel(wsT* ws, HyperliquidChannel channel, const std::string& coin) {
229 auto ch = static_cast<uint8_t>(channel);
230 const char* channel_name = channel == HyperliquidChannel::L2_BOOK ? "l2Book"
231 : channel == HyperliquidChannel::L2 ? "l2"
232 : "trades";
233 LOG_INFO("HyperliquidPublisher {:p} subscribe {}: {}", (void*)ws, channel_name, coin);
234
235 auto index = request_queue_.reserve();
236 auto* request = request_queue_[index];
237 utils::copy_wire_field(request->symbol, coin);
238 request->msg_type = MessageType::MD_SUBSCRIPTION;
239 request->md_subscription.channel = ch;
240 request->md_subscription.client = (void*)ws;
241 request_queue_.publish(index);
242
243 subscription_info_[ch][coin].emplace(ws);
244 symbol_channel_client_[coin].emplace(ch, ws);
245
246 auto* ud = ws->getUserData();
247 ud->subs[ch].active.emplace(coin);
248 ud->subs[ch].pending.emplace(coin);
249}
250
251void HyperliquidPublisher::publish_subscription_response(MarketDataUpdate* update) {
252 auto* response = reinterpret_cast<MDSubscriptionResponse*>(update->data);
253 uint8_t ch = response->channel;
254 auto& channel_sub = subscription_info_[ch];
255 auto it = channel_sub.find(update->symbol);
256 if (it == channel_sub.end() || it->second.empty()) return;
257
258 // A reject reserves room for the response header and nothing else, so the
259 // BookSnapshot read below would run off the end of the frame - and reserve()
260 // whatever level count the leftover bytes happened to describe. Tell the
261 // subscribers why instead.
262 if (response->reject_reason != MDSubscriptionRejectReason::NONE) {
263 auto message = std::format("subscription to `{}` rejected: {}",
264 update->symbol, to_string(response->reject_reason));
265 LOG_WARN(message);
266 for (auto* ws : it->second) {
267 send_error(ws, message);
268 }
269 return;
270 }
271
272 auto channel = static_cast<HyperliquidChannel>(ch);
273 json snapshot_msg;
274 json update_msg; // trades newer than the book snapshot, if any
275
276 if (channel == HyperliquidChannel::L2_BOOK || channel == HyperliquidChannel::L2) {
277 auto* snapshot = reinterpret_cast<BookSnapshot*>(response->data);
278 auto* levels = reinterpret_cast<MDLevel*>(snapshot->levels);
279
280 json::array_t bids, asks;
281 L2Levels curr_bid, curr_ask;
282 split_book_snapshot(levels, snapshot->num_bid, snapshot->num_ask,
283 bids, asks, curr_bid, curr_ask);
284
285 if (channel == HyperliquidChannel::L2_BOOK) {
286 snapshot_msg = {
287 {"channel", "l2Book"},
288 {"data", {
289 {"coin", update->symbol},
291 {"levels", {bids, asks}}
292 }}
293 };
294 } else {
295 // Undocumented "l2" channel: first delivery after subscribing is
296 // an uncompressed full snapshot under key "s" — there is nothing
297 // to diff against yet. Seed the diff baseline from it so the
298 // next routine book update can be sent as a compressed diff.
299 l2_diff_baseline_[update->symbol] = {std::move(curr_bid), std::move(curr_ask)};
300 snapshot_msg = {
301 {"channel", "l2"},
302 {"data", {{"s", {
303 {"coin", update->symbol},
305 {"levels", {bids, asks}}
306 }}}}
307 };
308 }
309 } else if (channel == HyperliquidChannel::TRADES) {
310 auto* trade_response = reinterpret_cast<MDTradeSnapshotResponse*>(response->data);
311 snapshot_msg = encode_trade_message(update->symbol, trade_response->trades,
312 trade_response->num_snapshot);
313 if (trade_response->num_update) {
314 // These are newer than the book snapshot this subscriber gets, so they
315 // are not settled history — deliver them as a normal update right
316 // after the snapshot.
317 update_msg = encode_trade_message(update->symbol,
318 trade_response->trades + trade_response->num_snapshot,
319 trade_response->num_update);
320 }
321 } else {
322 return;
323 }
324
325 for (auto* ws : it->second) {
326 auto* ud = ws->getUserData();
327 auto& sub = ud->subs[ch];
328 auto it_sym = sub.pending.find(update->symbol);
329 if (it_sym != sub.pending.end()) {
330 sub.pending.erase(it_sym);
331 sub.received.emplace_back(update->symbol);
332 ws->send(snapshot_msg.dump(), uWS::OpCode::TEXT);
333 LOG_DEBUG("HyperliquidPublisher sent subscription snapshot for {}", update->symbol);
334
335 if (!update_msg.is_null()) {
336 ws->send(update_msg.dump(), uWS::OpCode::TEXT);
337 }
338
339 if (sub.pending.empty()) {
340 json confirm = {
341 {"channel", "subscriptions"},
342 {"data", {{"subscriptions", sub.received}}}
343 };
344 ws->send(confirm.dump(), uWS::OpCode::TEXT);
345 }
346 }
347 }
348}
349
350void HyperliquidPublisher::publish_book_snapshot(MarketDataUpdate* update) {
351 auto l2book_ch = static_cast<uint8_t>(HyperliquidChannel::L2_BOOK);
352 auto l2_ch = static_cast<uint8_t>(HyperliquidChannel::L2);
353 auto it_l2book = subscription_info_[l2book_ch].find(update->symbol);
354 auto it_l2 = subscription_info_[l2_ch].find(update->symbol);
355 bool has_l2book = it_l2book != subscription_info_[l2book_ch].end() && !it_l2book->second.empty();
356 bool has_l2 = it_l2 != subscription_info_[l2_ch].end() && !it_l2->second.empty();
357 if (!has_l2book && !has_l2) return;
358
359 auto* snapshot = reinterpret_cast<BookSnapshot*>(update->data);
360 auto* levels = reinterpret_cast<MDLevel*>(snapshot->levels);
361
362 json::array_t bids, asks;
363 L2Levels curr_bid, curr_ask;
364 split_book_snapshot(levels, snapshot->num_bid, snapshot->num_ask,
365 bids, asks, curr_bid, curr_ask);
366 uint64_t time_ms = get_current_time_ns() / ONE_MILLISECOND_NS;
367
368 if (has_l2book) {
369 json msg = {
370 {"channel", "l2Book"},
371 {"data", {
372 {"coin", update->symbol},
373 {"time", time_ms},
374 {"levels", {bids, asks}}
375 }}
376 };
377 std::string payload = msg.dump();
378 for (auto* ws : it_l2book->second) {
379 ws->send(payload, uWS::OpCode::TEXT);
380 }
381 }
382
383 if (has_l2) {
384 auto& baseline = l2_diff_baseline_[update->symbol];
385 L2Diff diff = compute_l2_diff(baseline.first, baseline.second, curr_bid, curr_ask);
386 baseline.first = curr_bid;
387 baseline.second = curr_ask;
388
389 json diff_payload = {
390 {"c", update->symbol},
391 {"l", diff.l},
392 {"r", diff.r},
393 {"t", time_ms}
394 };
395 json msg = {
396 {"channel", "l2"},
397 {"data", {{"c", encode_l2_diff(diff_payload)}}}
398 };
399 std::string payload = msg.dump();
400 for (auto* ws : it_l2->second) {
401 ws->send(payload, uWS::OpCode::TEXT);
402 }
403 }
404}
405
406void HyperliquidPublisher::publish_trade_summary(MarketDataUpdate* update) {
407 auto ch = static_cast<uint8_t>(HyperliquidChannel::TRADES);
408 auto& channel_sub = subscription_info_[ch];
409 auto it = channel_sub.find(update->symbol);
410 if (it == channel_sub.end() || it->second.empty()) return;
411
412 auto* summary = reinterpret_cast<TradeSummary*>(update->data);
413 // No per-socket sequence number on this venue, so one payload serves everyone.
414 std::string payload = encode_trade_message(update->symbol, *summary).dump();
415 for (auto* ws : it->second) {
416 ws->send(payload, uWS::OpCode::TEXT);
417 }
418}
419
421 auto now = std::chrono::steady_clock::now();
422 for (auto it = clients_.begin(); it != clients_.end();) {
423 auto* ws = *it;
424 auto* ud = ws->getUserData();
425 auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - ud->last_pong);
426 if (elapsed > pong_timeout_) {
427 LOG_WARN("HyperliquidPublisher: client {:p} timed out, disconnecting", (void*)ws);
428 it = clients_.erase(it);
429 ws->close();
430 } else {
431 if (ud->subscribed_heartbeat) {
432 json hb = {
433 {"channel", "heartbeats"},
434 {"data", {{"time", format_timestamp_iso8601()}, {"counter", ud->heartbeat_count++}}}
435 };
436 ws->send(hb.dump(), uWS::OpCode::TEXT);
437 }
438 ws->send("", uWS::OpCode::PING);
439 ++it;
440 }
441 }
442}
443
444void HyperliquidPublisher::handle_close(wsT* ws, int code, std::string_view message) {
445 LOG_INFO("HyperliquidPublisher: client {:p} disconnected code={} msg={}", (void*)ws, code, message);
446 unsubscribe_md(ws);
447 clients_.erase(ws);
448}
449
450void HyperliquidPublisher::unsubscribe_md(wsT* ws) {
451 auto* ud = ws->getUserData();
452 for (uint8_t ch = 0; ch < static_cast<uint8_t>(HyperliquidChannel::__COUNT__); ++ch) {
453 for (const auto& coin : ud->subs[ch].active) {
454 auto index = request_queue_.reserve();
455 auto* req = request_queue_[index];
456 utils::copy_wire_field(req->symbol, coin);
457 req->msg_type = MessageType::MD_UNSUBSCRIPTION;
458 req->md_subscription.channel = ch;
459 req->md_subscription.client = (void*)ws;
460 request_queue_.publish(index);
461
462 auto it_sym = symbol_channel_client_.find(coin);
463 if (it_sym != symbol_channel_client_.end()) {
464 auto range = it_sym->second.equal_range(ch);
465 for (auto itr = range.first; itr != range.second; ) {
466 if (itr->second == ws) { itr = it_sym->second.erase(itr); break; }
467 else ++itr;
468 }
469 if (it_sym->second.empty()) symbol_channel_client_.erase(it_sym);
470 }
471 auto& coin_subs = subscription_info_[ch][coin];
472 coin_subs.erase(ws);
473 if (ch == static_cast<uint8_t>(HyperliquidChannel::L2) && coin_subs.empty()) {
474 l2_diff_baseline_.erase(coin);
475 }
476 }
477 ud->subs[ch].active.clear();
478 ud->subs[ch].pending.clear();
479 ud->subs[ch].received.clear();
480 }
481}
482
483void HyperliquidPublisher::send_error(wsT* ws, const std::string& error_msg) {
484 json err = {{"channel", "error"}, {"data", error_msg}};
485 ws->send(err.dump(), uWS::OpCode::TEXT);
486 LOG_ERROR("HyperliquidPublisher error: {}", error_msg);
487}
HyperliquidPublisher(const json &config, slick::queue< Request > &request_queue, slick::queue< uint8_t > &market_data_queue)
WebsocketMarketDataPublisher(Venue venue, slick::queue< Request > &request_queue, slick::queue< uint8_t > &market_data_queue, uint32_t port)
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)
json encode_trade_message(const char *coin, const TradeSummary &summary)
One executed trade.
slick::sim::exch::HyperliquidChannel HyperliquidChannel
L2Diff compute_l2_diff(const L2Levels &prev_bid, const L2Levels &prev_ask, const L2Levels &curr_bid, const L2Levels &curr_ask)
Conversions between wire decimals with a constant exponent of -9 (CME PRICE9, ICE Decimal9) and the s...
Definition decimal.hpp:9
constexpr uint64_t ONE_MILLISECOND_NS
bool copy_wire_field(char(&dst)[N], std::string_view src) noexcept
Copies a name into a fixed-width wire field.
uint64_t get_current_time_ns()
Definition timestamp.hpp:93
std::string format_timestamp_iso8601(const std::chrono::system_clock::time_point &tp, int num_sebsecond_digits=3)
Definition timestamp.hpp:9
@ HYPERLIQUID
Definition types.hpp:158
void proxy_hyperliquid_info_request(uWS::HttpResponse< false > *res, const std::string &upstream_base_url)
constexpr const char * to_string(FeedState state) noexcept
@ TRADE_SUMMARY
One executed trade.