1#include <slick/logger.hpp>
32 if (!config.contains(
"md_feeds")) {
36 for (
const auto &feed_cfg : config[
"md_feeds"]) {
37 std::string type = feed_cfg.value(
"type",
"");
38 if (!feed_cfg.value(
"enabled",
true)) {
39 LOG_INFO(
"Hyperliquid skipping disabled md_feed type {}", type);
42 if (type ==
"hyperliquid_live_ws") {
43 use_live_feed_ =
true;
44 live_ws_base_url_ = feed_cfg.value(
"base_url", live_ws_base_url_);
45 std::vector<std::string> coins;
46 if (feed_cfg.contains(
"coins")) {
47 coins = feed_cfg[
"coins"].get<std::vector<std::string>>();
49 auto feed = std::make_shared<md_feed::HyperliquidLiveWSFeed>(
this, live_ws_base_url_, coins);
51 for (
const auto &coin : coins) {
52 map_coin_feed_.emplace(coin, feed);
62Symbol* HyperliquidExchange::addSymbol(std::string_view coin) {
75 event_queue_.push_back({FeedEvent::Type::L2_BOOK, msg});
79 if (!msg.contains(
"data"))
return;
80 event_queue_.push_back({FeedEvent::Type::TRADES, msg[
"data"]});
84 LOG_WARN(
"Hyperliquid WebSocket feed disconnected");
86 for (
auto &[coin, feed] : map_coin_feed_) {
87 auto *symbol = sym_mgr.getSymbol(coin,
venue_);
89 pending_md_subscription_[
static_cast<size_t>(HyperliquidChannel::L2_BOOK)].emplace(symbol);
90 pending_md_subscription_[
static_cast<size_t>(HyperliquidChannel::L2)].emplace(symbol);
91 pending_md_subscription_[
static_cast<size_t>(HyperliquidChannel::TRADES)].emplace(symbol);
99 reinterpret_pointer_cast<md_feed::HyperliquidLiveWSFeed>(feed)->getInfo()->dispatch(100);
101 for (
auto &evt : event_queue_) {
102 if (evt.type == FeedEvent::Type::L2_BOOK) {
103 processL2BookEvent(evt.data);
105 processTradesEvent(evt.data);
108 event_queue_.clear();
114void HyperliquidExchange::processL2BookEvent(
const nlohmann::json& data) {
115 if (data.contains(
"levels")) {
116 processL2Snapshot(data);
117 }
else if (data.contains(
"l") && data.contains(
"r")) {
128void HyperliquidExchange::processL2Snapshot(
const nlohmann::json& data) {
129 if (!data.contains(
"coin") || !data.contains(
"levels"))
return;
131 const std::string coin = data[
"coin"].get<std::string>();
133 auto *symbol = sym_mgr.getSymbol(coin,
venue_);
135 symbol = addSymbol(coin);
139 const auto& levels_arr = data[
"levels"];
140 if (levels_arr.size() < 2)
return;
142 uint64_t event_time_ms = data.value(
"time", uint64_t{0});
145 symbol->order_book_->clearMDOrders();
147 auto &ref = l2_ref_levels_[symbol];
151 auto process_side = [&](
const nlohmann::json& side_levels,
Side side, std::vector<price_t>& ref_side) {
153 for (
const auto& level : side_levels) {
154 double px = std::stod(level[
"px"].get<std::string>());
155 double sz = std::stod(level[
"sz"].get<std::string>());
158 if (qty <= 0) [[unlikely]]
continue;
160 if (symbol->matching_engine_) {
161 auto trade_summaries = symbol->matching_engine_->match(
162 side, order_id, price, qty, *symbol->order_book_, event_time_ns, 0);
163 for (
const auto& summary : trade_summaries) {
168 symbol->order_book_->addOrder(order_id, book_side, price, qty, event_time_ns, 0, 0,
true);
172 ref_side.push_back(price);
176 process_side(levels_arr[0],
Side::BUY, ref[0]);
177 process_side(levels_arr[1],
Side::SELL, ref[1]);
179 symbol->order_book_->setLastUpdate(event_time_ns, 0);
181 finalizeL2Event(symbol);
183 symbol->md_level_update_cache_.clear();
184 symbol->md_order_update_cache_.clear();
185 LOG_TRACE(
"Hyperliquid l2 snapshot applied: {}", coin);
193void HyperliquidExchange::processL2Diff(
const nlohmann::json& data) {
194 if (!data.contains(
"c"))
return;
196 const auto coin = data[
"c"].get<std::string_view>();
198 auto *symbol = sym_mgr.getSymbol(coin,
venue_);
200 symbol = addSymbol(coin);
204 const auto& levels_arr = data[
"l"];
205 if (levels_arr.size() < 2)
return;
207 uint64_t event_time_ms = data.value(
"t", uint64_t{0});
210 auto &ref = l2_ref_levels_[symbol];
212 auto apply_removals = [&](
const nlohmann::json& indices,
Side side, std::vector<price_t>& ref_side) {
216 std::vector<price_t> removed_prices;
217 removed_prices.reserve(indices.size());
218 for (
const auto& idx_json : indices) {
219 auto idx = idx_json.get<
size_t>();
220 if (idx < ref_side.size()) {
221 removed_prices.push_back(ref_side[idx]);
223 LOG_WARN(
"Hyperliquid l2 diff: removed-level index {} out of range (have {}) for {}",
224 idx, ref_side.size(), coin);
227 for (
price_t price : removed_prices) {
228 applyPhantomLevelUpdate(symbol, side, price, 0, event_time_ns);
229 if (
auto it = std::find(ref_side.begin(), ref_side.end(), price); it != ref_side.end()) {
235 if (
const auto& removed = data.value(
"r", nlohmann::json::array()); removed.is_array() && removed.size() == 2) {
236 apply_removals(removed[0],
Side::BUY, ref[0]);
237 apply_removals(removed[1],
Side::SELL, ref[1]);
240 auto apply_changes = [&](
const nlohmann::json& side_levels,
Side side, std::vector<price_t>& ref_side) {
241 for (
const auto& level : side_levels) {
242 double px = std::stod(level[
"p"].get<std::string>());
243 double sz = std::stod(level[
"s"].get<std::string>());
247 applyPhantomLevelUpdate(symbol, side, price, qty, event_time_ns);
249 auto it = std::lower_bound(ref_side.begin(), ref_side.end(), price,
250 [side](
price_t a,
price_t b) { return utils::isPriceBetter(side, a, b); });
251 if (it == ref_side.end() || *it != price) {
252 ref_side.insert(it, price);
257 apply_changes(levels_arr[0],
Side::BUY, ref[0]);
258 apply_changes(levels_arr[1],
Side::SELL, ref[1]);
260 symbol->order_book_->setLastUpdate(event_time_ns, 0);
262 finalizeL2Event(symbol);
264 symbol->md_level_update_cache_.clear();
265 symbol->md_order_update_cache_.clear();
266 LOG_TRACE(
"Hyperliquid l2 diff applied: {}", coin);
275void HyperliquidExchange::applyPhantomLevelUpdate(
280 auto [level, index] = book.getLevel(book_side, price);
286 if (target_qty <= 0)
return;
287 qty_t qty = target_qty;
291 side, order_id, price, qty, book, event_time_ns, 0);
292 for (
const auto& summary : trade_summaries) {
297 book.addOrder(order_id, book_side, price, qty, event_time_ns, 0, 0,
true);
311void HyperliquidExchange::finalizeL2Event(
Symbol* symbol) {
317 bool l2book_was_pending =
false;
318 bool l2_was_pending =
false;
320 auto &pending_l2book = pending_md_subscription_[
static_cast<size_t>(HyperliquidChannel::L2_BOOK)];
321 if (
auto it = pending_l2book.find(symbol); it != pending_l2book.end()) {
322 symbol->
order_book_->populateL2SubscriptionResponse(
323 md_queue_,
static_cast<uint8_t
>(HyperliquidChannel::L2_BOOK));
324 pending_l2book.erase(it);
325 l2book_was_pending =
true;
328 auto &pending_l2 = pending_md_subscription_[
static_cast<size_t>(HyperliquidChannel::L2)];
329 if (
auto it = pending_l2.find(symbol); it != pending_l2.end()) {
330 symbol->
order_book_->populateL2SubscriptionResponse(
331 md_queue_,
static_cast<uint8_t
>(HyperliquidChannel::L2));
332 pending_l2.erase(it);
333 l2_was_pending =
true;
336 if (!l2book_was_pending || !l2_was_pending) {
342void HyperliquidExchange::processTradesEvent(
const nlohmann::json& data) {
343 if (!data.is_array() || data.empty())
return;
345 const std::string coin = data[0].value(
"coin",
"");
346 if (coin.empty())
return;
348 auto *symbol = sym_mgr.getSymbol(coin,
venue_);
353 for (
const auto& trade : data) {
354 std::string side_str = trade.value(
"side",
"B");
356 double px = std::stod(trade[
"px"].get<std::string>());
357 double sz = std::stod(trade[
"sz"].get<std::string>());
358 uint64_t time_ms = trade.value(
"time", uint64_t{0});
374 side, order_id, price, qty, book, event_time_ns, 0);
380 book.addOrder(order_id, book_side, price, qty, event_time_ns, 0, 0,
true);
383 for (
const auto& summary : trade_summaries) {
387 summary.phantom_qty, event_time_ns);
401 std::string coin = request.
symbol;
403 auto *symbol = sym_mgr.getSymbol(coin,
venue_);
406 symbol = addSymbol(coin);
414 if (use_live_feed_) {
417 auto it_feed = map_coin_feed_.find(coin);
418 if (it_feed == map_coin_feed_.end()) {
420 std::shared_ptr<md_feed::HyperliquidLiveWSFeed> live_feed;
422 live_feed = std::dynamic_pointer_cast<md_feed::HyperliquidLiveWSFeed>(
md_feeds_.front());
425 auto new_feed = std::make_shared<md_feed::HyperliquidLiveWSFeed>(
this, live_ws_base_url_);
428 live_feed = new_feed;
430 live_feed->addCoin(coin);
431 map_coin_feed_.emplace(coin, live_feed);
433 auto live_feed = std::dynamic_pointer_cast<md_feed::HyperliquidLiveWSFeed>(it_feed->second);
435 live_feed->addCoin(coin);
442 if (channel == HyperliquidChannel::TRADES) {
445 pending_md_subscription_[
static_cast<size_t>(channel)].emplace(symbol);
448 auto &pending = pending_md_subscription_[
static_cast<size_t>(channel)];
449 if (pending.find(symbol) == pending.end()) {
451 if (channel == HyperliquidChannel::L2_BOOK || channel == HyperliquidChannel::L2) {
452 symbol->
order_book_->populateL2SubscriptionResponse(
453 md_queue_,
static_cast<uint8_t
>(channel));
454 }
else if (channel == HyperliquidChannel::TRADES) {
461 if (channel == HyperliquidChannel::L2_BOOK || channel == HyperliquidChannel::L2) {
462 symbol->
order_book_->populateL2SubscriptionResponse(
463 md_queue_,
static_cast<uint8_t
>(channel));
464 }
else if (channel == HyperliquidChannel::TRADES) {
471 std::string coin = request.
symbol;
472 auto *symbol = sym_mgr.getSymbol(coin,
venue_);
476 auto it_feed = map_coin_feed_.find(coin);
477 if (it_feed != map_coin_feed_.end()) {
479 map_coin_feed_.erase(it_feed);
static SymbolManager & instance()
virtual std::tuple< OrdRejectReason, std::vector< TradeSummaryInfo > > match(Order *order, price_t order_price, qty_t order_qty, OrderBook &book, time_t request_time, time_t event_time, uint64_t seq_num=0, SelfMatchPreventionMode smp_mode=SelfMatchPreventionMode::NONE)=0
queue< Request > request_queue_
void publishTradeSubscriptionResponse(Symbol *symbol, uint8_t channel)
Frames the SUB_RESPONSE for a venue's trade channel from the symbol's recent-trade history,...
queue< uint8_t > md_queue_
std::vector< std::unique_ptr< order_gateway::OrderGateway > > order_gateways_
void reconcilePhantomQty(Symbol *symbol, Side side, price_t price, qty_t target_qty, time_t event_time, uint64_t seq_num, bool end_event)
Adjusts the phantom (market-mirroring) quantity at an existing (side, price) level toward target_qty,...
std::vector< std::shared_ptr< md_feed::MDFeed > > md_feeds_
Feeds owned by the exchange and managed by base start()/stop().
Exchange(Venue venue, const nlohmann::json &config)
std::unique_ptr< md_publisher::MarketDataPublisher > md_publisher_
void publishTradeSummary(Symbol *symbol, const TradeSummaryInfo &trade_summary)
Publishes one trade onto the instrument's public tape and records it in the symbol's recent-trade his...
void assignMatching(Symbol *symbol)
Points a new symbol at the venue's configured engine, creating the engine on first use,...
queue< OrderResponse > response_queue_
void onTradesUpdate(const nlohmann::json &msg) override
void onL2BookUpdate(const nlohmann::json &msg) override
void handleMdSubscription(const Request &request) override
void onHyperliquidDisconnected() override
void poll() override
One iteration of the exchange thread's loop, called continuously between start() and stop().
HyperliquidExchange(const nlohmann::json &config)
void handleMdUnsubscription(const Request &request) override
Helpers for a venue whose one config entry describes several independent exchange instances,...
HyperliquidChannel
The market-data channels the Hyperliquid adapter serves.
uint64_t nextOrderId() noexcept
constexpr uint64_t ONE_MILLISECOND_NS
constexpr Side opposite_side()
constexpr price_t to_price_t(double price)
Scales a decimal into the fixed-point representation, rounding to the nearest tick rather than trunca...
orderbook::Side to_book_side(Side side)
constexpr qty_t to_qty_t(double qty)
MDSubscriptionMessage md_subscription
void creditTradedQty(Side side, price_t price, qty_t phantom_consumed, time_t event_time)
Records that a trade print consumed phantom_consumed of the phantom liquidity resting at (side,...
engine::MatchingEngine * matching_engine_
std::vector< MDLevel > md_level_update_cache_
std::vector< MDOrder > md_order_update_cache_
std::shared_ptr< OrderBook > order_book_
std::atomic_uint16_t num_subscriptions_