1#include <slick/logger.hpp>
18 slick::queue<Request>& request_queue,
19 slick::queue<uint8_t>& market_data_queue
22 , upstream_base_url_(config.value(
"upstream_base_url",
"https://api.hyperliquid.xyz"))
108void HyperliquidPublisher::setup_routes(uWS::App &app) {
110 .compression = uWS::SHARED_COMPRESSOR,
111 .maxPayloadLength = 2 << 24,
113 .maxBackpressure = 2 << 25,
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);
122 .message = [
this](
auto* ws, std::string_view message, uWS::OpCode) {
123 handle_message(ws, message);
126 .drain = [](
auto*) {},
128 .ping = [](
auto* ws, std::string_view) {
129 LOG_TRACE(
"HyperliquidPublisher ping from {:p}", (
void*)ws);
132 .pong = [
this](
auto* ws, std::string_view) {
133 ws->getUserData()->last_pong = std::chrono::steady_clock::now();
136 .close = [
this](
auto* ws,
int code, std::string_view msg) {
137 handle_close(ws, code, msg);
141 app.post(
"/info", [
this](
auto* res,
auto* req) {
142 handle_info(res, req);
146void HyperliquidPublisher::handle_info(uWS::HttpResponse<false>* res, uWS::HttpRequest*) {
150void HyperliquidPublisher::publish_market_data_update(MarketDataUpdate* update) {
151 switch (update->
type) {
153 publish_subscription_response(update);
156 publish_book_snapshot(update);
159 publish_trade_summary(update);
166void HyperliquidPublisher::handle_message(wsT* ws, std::string_view message) {
168 json msg = json::parse(message);
170 std::string method = msg.value(
"method",
"");
171 if (method ==
"ping") {
172 json pong = {{
"channel",
"pong"}};
173 ws->send(pong.dump(), uWS::OpCode::TEXT);
177 if (method !=
"subscribe" && method !=
"unsubscribe") {
178 send_error(ws, std::format(
"method `{}` is not supported", method));
182 if (!msg.contains(
"subscription")) {
183 send_error(ws,
"missing `subscription` field");
187 const auto& sub = msg[
"subscription"];
188 std::string type = sub.value(
"type",
"");
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);
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);
202 }
else if (type ==
"l2") {
204 std::string coin = sub.value(
"c",
"");
205 if (coin.empty()) { send_error(ws,
"missing `c` in subscription");
return; }
206 if (method ==
"subscribe") {
210 {
"channel",
"subscriptionResponse"},
211 {
"data", {{
"method",
"subscribe"}, {
"subscription", sub}}}
213 ws->send(ack.dump(), uWS::OpCode::TEXT);
214 subscribe_channel(ws, HyperliquidChannel::L2, coin);
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);
221 send_error(ws, std::format(
"subscription type `{}` is not supported", type));
223 }
catch (
const json::parse_error& e) {
224 send_error(ws, std::string(
"invalid JSON: ") + e.what());
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"
233 LOG_INFO(
"HyperliquidPublisher {:p} subscribe {}: {}", (
void*)ws, channel_name, coin);
239 request->md_subscription.channel = ch;
240 request->md_subscription.client = (
void*)ws;
243 subscription_info_[ch][coin].emplace(ws);
244 symbol_channel_client_[coin].emplace(ch, ws);
246 auto* ud = ws->getUserData();
247 ud->subs[ch].active.emplace(coin);
248 ud->subs[ch].pending.emplace(coin);
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;
263 auto message = std::format(
"subscription to `{}` rejected: {}",
266 for (
auto* ws : it->second) {
267 send_error(ws, message);
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);
280 json::array_t bids, asks;
283 bids, asks, curr_bid, curr_ask);
285 if (channel == HyperliquidChannel::L2_BOOK) {
287 {
"channel",
"l2Book"},
291 {
"levels", {bids, asks}}
299 l2_diff_baseline_[update->
symbol] = {std::move(curr_bid), std::move(curr_ask)};
305 {
"levels", {bids, asks}}
309 }
else if (channel == HyperliquidChannel::TRADES) {
310 auto* trade_response =
reinterpret_cast<MDTradeSnapshotResponse*
>(response->data);
312 trade_response->num_snapshot);
313 if (trade_response->num_update) {
318 trade_response->trades + trade_response->num_snapshot,
319 trade_response->num_update);
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);
335 if (!update_msg.is_null()) {
336 ws->send(update_msg.dump(), uWS::OpCode::TEXT);
339 if (sub.pending.empty()) {
341 {
"channel",
"subscriptions"},
342 {
"data", {{
"subscriptions", sub.received}}}
344 ws->send(confirm.dump(), uWS::OpCode::TEXT);
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;
359 auto* snapshot =
reinterpret_cast<BookSnapshot*
>(update->
data);
360 auto* levels =
reinterpret_cast<MDLevel*
>(snapshot->levels);
362 json::array_t bids, asks;
365 bids, asks, curr_bid, curr_ask);
370 {
"channel",
"l2Book"},
374 {
"levels", {bids, asks}}
377 std::string payload = msg.dump();
378 for (
auto* ws : it_l2book->second) {
379 ws->send(payload, uWS::OpCode::TEXT);
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;
389 json diff_payload = {
399 std::string payload = msg.dump();
400 for (
auto* ws : it_l2->second) {
401 ws->send(payload, uWS::OpCode::TEXT);
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;
412 auto* summary =
reinterpret_cast<TradeSummary*
>(update->
data);
415 for (
auto* ws : it->second) {
416 ws->send(payload, uWS::OpCode::TEXT);
421 auto now = std::chrono::steady_clock::now();
422 for (
auto it = clients_.begin(); it != clients_.end();) {
424 auto* ud = ws->getUserData();
425 auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - ud->last_pong);
427 LOG_WARN(
"HyperliquidPublisher: client {:p} timed out, disconnecting", (
void*)ws);
428 it = clients_.erase(it);
431 if (ud->subscribed_heartbeat) {
433 {
"channel",
"heartbeats"},
436 ws->send(hb.dump(), uWS::OpCode::TEXT);
438 ws->send(
"", uWS::OpCode::PING);
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);
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) {
458 req->md_subscription.channel = ch;
459 req->md_subscription.client = (
void*)ws;
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; }
469 if (it_sym->second.empty()) symbol_channel_client_.erase(it_sym);
471 auto& coin_subs = subscription_info_[ch][coin];
473 if (ch ==
static_cast<uint8_t
>(HyperliquidChannel::L2) && coin_subs.empty()) {
474 l2_diff_baseline_.erase(coin);
477 ud->subs[ch].active.clear();
478 ud->subs[ch].pending.clear();
479 ud->subs[ch].received.clear();
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);
HyperliquidPublisher(const json &config, slick::queue< Request > &request_queue, slick::queue< uint8_t > &market_data_queue)
slick::queue< Request > & request_queue_
virtual void check_heartbeats()=0
std::chrono::seconds pong_timeout_
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...
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()
std::string format_timestamp_iso8601(const std::chrono::system_clock::time_point &tp, int num_sebsecond_digits=3)
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.
static uint_fast64_t heartbeat_count