10#include <slick/net/http.hpp>
11#include <hyperliquid/info.hpp>
12#include <hyperliquid/utils/constants.hpp>
13#include <hyperliquid/utils/l2_diff.hpp>
14#include <slick/logger.hpp>
28 slick::stream_buffer_multiplexer &mux,
29 slick::queue<uint8_t>& control_queue,
30 slick::queue<uint8_t>& request_queue
32 : enabled_(config.empty() ? false : config.value(
"enabled", true))
33 , shm_name_(config.value(
"shm_name",
""))
34 , control_queue_(control_queue)
35 , request_queue_(request_queue)
36 , request_cursor_(request_queue.initial_reading_index())
37 , api_url_(config.value(
"api_url",
hyperliquid::MAINNET_API_URL))
43 event_buffer_ = mux.add_producer(
45 config.value(
"queue_size", 1u << 26),
46 config.value(
"control_size", 1u << 24),
47 shm_name_.empty() ?
nullptr : shm_name_.c_str()
50 LOG_INFO(
"Hyperliquid MD connector is disabled");
74 LOG_INFO(
"Hyperliquid MD: Connecting to {}", api_url_);
77 info_ = std::make_unique<hyperliquid::Info>(api_url_,
false,
true);
79 connected_.store(
true, std::memory_order_release);
81 LOG_INFO(
"Hyperliquid MD: Connected");
83 }
catch (
const std::exception& e) {
84 LOG_ERROR(
"Hyperliquid MD: connect() failed: {}", e.what());
86 connected_.store(
false, std::memory_order_release);
94 LOG_INFO(
"Hyperliquid MD: Disconnecting");
96 for (
auto& [sub_json_str, sub_id] : sub_ids_) {
98 info_->unsubscribe(nlohmann::json::parse(sub_json_str), sub_id);
103 connected_.store(
false, std::memory_order_release);
105 LOG_INFO(
"Hyperliquid MD: Disconnected");
110 LOG_INFO(
"Hyperliquid MD: Subscribing to {} instruments (type: {})",
118 auto iter = info_->name_to_coin.find(instr);
119 if (iter == info_->name_to_coin.end()) {
120 LOG_ERROR(
"HYPERLIQUID skip subscription of an invalid coin {}", instr);
124 coin_to_name_.emplace(std::make_pair(iter->second, instr));
131 trade_instruments_.push_back(instr);
133 sub = {{
"type",
"trades"}, {
"coin", instr}};
136 quote_instruments_.push_back(instr);
138 sub = {{
"type",
"bbo"}, {
"coin", instr}};
141 level2_instruments_.push_back(instr);
142 level2_depth_ = request.
depth;
144 sub = {{
"type",
"l2"}, {
"c", instr}};
147 level2_instruments_.push_back(instr);
148 level2_depth_ = request.
depth;
150 sub = {{
"type",
"l2Book"}, {
"coin", instr}, {
"fast",
true}};
153 LOG_WARN(
"Hyperliquid MD: no market-by-order feed, MBO subscription of {} ignored", instr);
157 int id = info_->subscribe(sub, [
this, ch_type](
const nlohmann::json& msg) {
158 if (ch_type ==
"trades") on_trades(msg);
159 else if (ch_type ==
"bbo") on_bbo(msg);
160 else if (ch_type ==
"l2") on_l2(msg);
161 else if (ch_type ==
"l2Book") on_l2book(msg);
162 else LOG_WARN(
"Hyperliquid MD: Unknown channel type: {}", ch_type);
164 sub_ids_.emplace_back(sub.dump(),
id);
172 auto remove_from = [&](std::vector<std::string>& list) {
175 list.erase(std::remove(list.begin(), list.end(), ins), list.end());
191 if (running_.load(std::memory_order_relaxed)) {
192 LOG_WARN(
"Hyperliquid MD: Already running");
195 running_.store(
true, std::memory_order_release);
197 worker_thread_ = std::thread(&HyperliquidMDConnector::run,
this);
201 if (!running_.load(std::memory_order_acquire))
return;
203 running_.store(
false, std::memory_order_release);
208 const std::unordered_map<int, int>& asset_to_sz_decimals) {
209 constexpr int FIRST_SPOT_ASSET = 10000;
210 std::vector<MdDefinition> definitions;
211 for (
const auto& [coin, asset] : coin_to_asset) {
212 if (asset >= FIRST_SPOT_ASSET) {
215 const auto decimals = asset_to_sz_decimals.find(asset);
218 .quantity_increment = decimals != asset_to_sz_decimals.end()
219 ?
to_qty_t(std::pow(10.0, -decimals->second))
228void HyperliquidMDConnector::publish_definitions() {
230 for (
const auto& definition : definitions) {
233 LOG_INFO(
"Hyperliquid MD: {} perp(s) defined", definitions.size());
236void HyperliquidMDConnector::run() {
237 LOG_INFO(
"Hyperliquid MD: Worker thread started");
241 publish_definitions();
244 while (running_.load(std::memory_order_acquire)) {
248 process_md_requests();
251 LOG_INFO(
"Hyperliquid MD: Worker thread stopped");
254void HyperliquidMDConnector::process_md_requests() {
258 [
this](
const MDSubscription& request) {
262 LOG_WARN(
"Hyperliquid MD skip subscription, not enabled");
265 [
this](
const MDSubscription& request) {
271 std::this_thread::yield();
275void HyperliquidMDConnector::subscribe_all() {
276 auto subscribe_coin_list = [&](
const std::vector<std::string>& coins,
277 const std::string& ch_type) {
278 for (
const auto& coin : coins) {
279 nlohmann::json sub = {{
"type", ch_type}, {
"coin", coin}};
280 int id = info_->subscribe(sub, [
this, ch_type](
const nlohmann::json& msg) {
281 if (ch_type ==
"trades") on_trades(msg);
282 else if (ch_type ==
"bbo") on_bbo(msg);
283 else if (ch_type ==
"l2") on_l2(msg);
284 else if (ch_type ==
"l2Book") on_l2book(msg);
285 else LOG_WARN(
"Hyperliquid MD: Unknown channel type: {}", ch_type);
287 sub_ids_.emplace_back(sub.dump(),
id);
291 subscribe_coin_list(trade_instruments_,
"trades");
292 subscribe_coin_list(quote_instruments_,
"bbo");
293 subscribe_coin_list(level2_instruments_,
"l2Book");
298void HyperliquidMDConnector::on_trades(
const nlohmann::json& msg) {
299 const auto data_ptr = msg.find(
"data");
300 if (data_ptr == msg.end() || !data_ptr->is_array())
return;
302 for (
const auto& trade : *data_ptr) {
304 const std::string coin = trade.at(
"coin").get<std::string>();
305 const double px = std::stod(trade.at(
"px").get<std::string>());
306 const double sz = std::stod(trade.at(
"sz").get<std::string>());
307 const std::string side_str = trade.value(
"side",
"B");
308 const uint64_t tid = trade.value(
"tid", uint64_t(0));
309 const uint64_t time_ms = trade.value(
"time", uint64_t(0));
310 std::string instr = coin;
311 auto iter = coin_to_name_.find(coin);
312 if (iter != coin_to_name_.end()) {
313 instr = iter->second;
319 ev.event_time_ns = time_ms * 1'000'000ULL;
320 ev.set_instrument(instr);
325 ev.is_buyer_maker = (side_str ==
"A");
329 }
catch (
const std::exception& e) {
330 LOG_ERROR(
"Hyperliquid MD: Failed to parse trade: {}", e.what());
335void HyperliquidMDConnector::on_bbo(
const nlohmann::json& msg) {
336 const auto data_ptr = msg.find(
"data");
337 if (data_ptr == msg.end())
return;
340 const auto& data = *data_ptr;
341 const std::string coin = data.at(
"coin").get<std::string>();
342 const uint64_t time_ms = data.value(
"time", uint64_t(0));
345 const auto& levels = data.at(
"levels");
346 if (levels.size() < 2)
return;
348 const auto& bids = levels[0];
349 const auto& asks = levels[1];
350 if (bids.empty() || asks.empty())
return;
352 const double bid_px = std::stod(bids[0][0].get<std::string>());
353 const double bid_sz = std::stod(bids[0][1].get<std::string>());
354 const double ask_px = std::stod(asks[0][0].get<std::string>());
355 const double ask_sz = std::stod(asks[0][1].get<std::string>());
357 std::string instr = coin;
358 auto iter = coin_to_name_.find(coin);
359 if (iter != coin_to_name_.end()) {
360 instr = iter->second;
366 ev.event_time_ns = time_ms * 1'000'000ULL;
367 ev.set_instrument(instr);
373 }
catch (
const std::exception& e) {
374 LOG_ERROR(
"Hyperliquid MD: Failed to parse bbo: {}", e.what());
378void HyperliquidMDConnector::on_l2(
const nlohmann::json& msg) {
379 const auto data_ptr = msg.find(
"data");
380 if (data_ptr == msg.end())
return;
383 const auto& data = *data_ptr;
384 const auto s_ptr = data.find(
"s");
385 if (s_ptr != data.end() && s_ptr->is_string()) {
388 const std::string coin = s_ptr->at(
"coin").get<std::string>();
389 const uint64_t time_ms = s_ptr->value(
"t", uint64_t(0));
391 std::string instr = coin;
392 auto iter = coin_to_name_.find(coin);
393 if (iter != coin_to_name_.end()) {
394 instr = iter->second;
397 const auto& levels = s_ptr->at(
"levels");
398 if (levels.size() < 2)
return;
400 const auto& bids = levels[0];
401 const auto& asks = levels[1];
402 const size_t total_levels = bids.size() + asks.size();
403 if (total_levels == 0)
return;
405 const uint32_t event_size =
static_cast<uint32_t
>(
406 sizeof(Level2UpdateEvent) + total_levels *
sizeof(PriceLevel));
411 ev.event_time_ns = time_ms * 1'000'000ULL;
412 ev.set_instrument(instr);
413 ev.is_snapshot =
true;
414 ev.sequence_num = time_ms;
415 ev.num_levels =
static_cast<uint16_t
>(total_levels);
418 for (
const auto& level : bids) {
419 ev.levels[idx].price =
to_price_t(std::stod(level[
"px"].get<std::string>()));
420 ev.levels[idx].quantity =
to_qty_t(std::stod(level[
"sz"].get<std::string>()));
423 bid_prices_.insert(ev.levels[idx].price);
426 for (
const auto& level : asks) {
427 ev.levels[idx].price =
to_price_t(std::stod(level[
"px"].get<std::string>()));
428 ev.levels[idx].quantity =
to_qty_t(std::stod(level[
"sz"].get<std::string>()));
431 ask_prices_.insert(ev.levels[idx].price);
438 const auto c_ptr = data.find(
"c");
439 if (c_ptr == data.end() || !c_ptr->is_string())
return;
441 const auto diff = hyperliquid::decode_l2_diff(c_ptr->get<std::string>());
443 const std::string coin = diff.at(
"c").get<std::string>();
444 const uint64_t time_ms = diff.value(
"t", uint64_t(0));
446 std::string instr = coin;
447 auto iter = coin_to_name_.find(coin);
448 if (iter != coin_to_name_.end()) {
449 instr = iter->second;
452 LOG_TRACE(
"Hyperliquid MD: l2 for {}: {}", instr, c_ptr->get<std::string>());
453 LOG_TRACE(
"Hyperliquid MD: l2 diff for {}: {}", instr, diff.dump());
455 const auto& removed_levels = diff.at(
"r");
456 if (!removed_levels.empty() && removed_levels.is_array() && removed_levels.size() == 2) {
457 const auto& bids = removed_levels[0];
458 const auto& asks = removed_levels[1];
459 const size_t total_levels = bids.size() + asks.size();
463 const uint32_t event_size =
static_cast<uint32_t
>(
464 sizeof(Level2UpdateEvent) + total_levels *
sizeof(PriceLevel));
469 ev.event_time_ns = time_ms * 1'000'000ULL;
470 ev.set_instrument(instr);
471 ev.is_snapshot =
false;
472 ev.sequence_num = time_ms;
476 for (
const auto& level_index : bids) {
477 auto index = level_index.get<
int>();
478 if (index < 0 || index >=
static_cast<int>(bid_prices_.size())) {
482 auto price = *std::next(bid_prices_.begin(), index);
484 bid_prices_.erase(price);
486 ev.levels[idx].price = price;
487 ev.levels[idx].quantity = 0;
493 for (
auto it = asks.rbegin(); it != asks.rend(); ++it) {
494 auto index = it->get<
int>();
495 if (index < 0 || index >=
static_cast<int>(ask_prices_.size())) {
499 auto price = *std::next(ask_prices_.begin(), index);
501 ask_prices_.erase(price);
503 ev.levels[idx].price = price;
504 ev.levels[idx].quantity = 0;
509 ev.num_levels =
static_cast<uint16_t
>(idx);
514 const auto& levels = diff.at(
"l");
515 if (levels.size() < 2)
return;
517 const auto& bids = levels[0];
518 const auto& asks = levels[1];
519 const size_t total_levels = bids.size() + asks.size();
520 if (total_levels == 0)
return;
522 const uint32_t event_size =
static_cast<uint32_t
>(
523 sizeof(Level2UpdateEvent) + total_levels *
sizeof(PriceLevel));
528 ev.event_time_ns = time_ms * 1'000'000ULL;
529 ev.set_instrument(instr);
530 ev.is_snapshot =
false;
531 ev.sequence_num = time_ms;
532 ev.num_levels =
static_cast<uint16_t
>(total_levels);
535 for (
const auto& level : bids) {
536 ev.levels[idx].price =
to_price_t(std::stod(level[
"p"].get<std::string>()));
537 ev.levels[idx].quantity =
to_qty_t(std::stod(level[
"s"].get<std::string>()));
540 bid_prices_.insert(ev.levels[idx].price);
543 for (
const auto& level : asks) {
544 ev.levels[idx].price =
to_price_t(std::stod(level[
"p"].get<std::string>()));
545 ev.levels[idx].quantity =
to_qty_t(std::stod(level[
"s"].get<std::string>()));
548 ask_prices_.insert(ev.levels[idx].price);
552 }
catch (
const std::exception& e) {
553 LOG_ERROR(
"Hyperliquid MD: Failed to parse l2 diff: {}", e.what());
557void HyperliquidMDConnector::on_l2book(
const nlohmann::json& msg) {
558 const auto data_ptr = msg.find(
"data");
559 if (data_ptr == msg.end())
return;
562 const auto& data = *data_ptr;
563 const std::string coin = data.at(
"coin").get<std::string>();
564 const uint64_t time_ms = data.value(
"time", uint64_t(0));
567 const auto& levels = data.at(
"levels");
568 if (levels.size() < 2)
return;
570 const auto& bids = levels[0];
571 const auto& asks = levels[1];
572 const size_t total_levels = bids.size() + asks.size();
574 if (total_levels == 0)
return;
576 std::string instr = coin;
577 auto iter = coin_to_name_.find(coin);
578 if (iter != coin_to_name_.end()) {
579 instr = iter->second;
582 const uint32_t event_size =
static_cast<uint32_t
>(
583 sizeof(Level2UpdateEvent) + total_levels *
sizeof(PriceLevel));
588 ev.event_time_ns = time_ms * 1'000'000ULL;
589 ev.set_instrument(instr);
590 ev.is_snapshot =
true;
591 ev.sequence_num = time_ms;
592 ev.num_levels =
static_cast<uint16_t
>(total_levels);
595 for (
const auto& level : bids) {
596 ev.levels[idx].price =
to_price_t(std::stod(level[
"px"].get<std::string>()));
597 ev.levels[idx].quantity =
to_qty_t(std::stod(level[
"sz"].get<std::string>()));
598 ev.levels[idx].num_orders = level[
"n"].get<uint32_t>();
602 for (
const auto& level : asks) {
603 ev.levels[idx].price =
to_price_t(std::stod(level[
"px"].get<std::string>()));
604 ev.levels[idx].quantity =
to_qty_t(std::stod(level[
"sz"].get<std::string>()));
605 ev.levels[idx].num_orders = level[
"n"].get<uint32_t>();
610 }
catch (
const std::exception& e) {
611 LOG_ERROR(
"Hyperliquid MD: Failed to parse l2Book: {}", e.what());
void set_md_connected(BrokerId id, bool v)
static BrokerStatusRegistry & instance()
static bool publish(slick::SlickQueue< uint8_t > &queue, uint32_t size, populate_event_fn &&populate_event_func)
HyperliquidMDConnector(const json &config, slick::stream_buffer_multiplexer &mux, slick::queue< uint8_t > &control_queue, slick::queue< uint8_t > &request_queue)
~HyperliquidMDConnector() override
void register_md_connector() override
bool unsubscribe(const MDSubscription &request) override
void disconnect() override
bool subscribe(const MDSubscription &request) override
price_t to_price_t(double value)
uint64_t get_timestamp_ns()
bool process_md_request(slick::queue< uint8_t > &queue, uint64_t &cursor, BrokerId broker, Subscribe &&on_subscribe, Unsubscribe &&on_unsubscribe)
std::vector< MdDefinition > hyperliquid_definitions(const std::unordered_map< std::string, int > &coin_to_asset, const std::unordered_map< int, int > &asset_to_sz_decimals)
bool publish_definition(slick::stream_buffer_multiplexer::producer_buffer &buffer, BrokerId broker, const MdDefinition &d)
static constexpr uint32_t producer_id
qty_t to_qty_t(double value)
SubscriptionType subscription_type