Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
hyperliquid_exchange.cpp
Go to the documentation of this file.
1#include <slick/logger.hpp>
5#include <utils/timestamp.hpp>
6#include <utils/order.hpp>
8#include <algorithm>
9#include <chrono>
10#include <cstring>
13
14using namespace slick::sim;
15using namespace slick::sim::exch;
16using namespace slick::sim::order_gateway;
17using namespace slick::sim::md_publisher;
18
19namespace {
20 auto &sym_mgr = SymbolManager::instance();
21}
22
23HyperliquidExchange::HyperliquidExchange(const nlohmann::json &config)
24 : Exchange(Venue::HYPERLIQUID, config)
25{
26 md_publisher_ = std::make_unique<HyperliquidPublisher>(config["md_publisher"], request_queue_, md_queue_);
27
28 order_gateways_.emplace_back(
29 std::make_unique<HyperliquidRestOrderGateway>(config["order_gateway"], request_queue_, response_queue_)
30 );
31
32 if (!config.contains("md_feeds")) {
33 return;
34 }
35
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);
40 continue;
41 }
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>>();
48 }
49 auto feed = std::make_shared<md_feed::HyperliquidLiveWSFeed>(this, live_ws_base_url_, coins);
50 md_feeds_.emplace_back(feed);
51 for (const auto &coin : coins) {
52 map_coin_feed_.emplace(coin, feed);
53 }
54 }
55 }
56}
57
61
62Symbol* HyperliquidExchange::addSymbol(std::string_view coin) {
63 auto *symbol = sym_mgr.createSymbol(coin, Venue::HYPERLIQUID);
64 assert(symbol);
65 assignMatching(symbol); // FIFO: Hyperliquid never calls configureMatching
66 symbol->createOrderBook<OrderBookType::L2>();
67 return symbol;
68}
69
70// Called from hyperliquid WS thread — push into event queue.
71// `msg` is already the unwrapped payload from HyperliquidLiveWSFeed::on_l2:
72// either a full snapshot ({"coin","time","levels"}) or a decoded diff
73// ({"c","l","r","t"}) — processL2BookEvent sniffs which shape it got.
74void HyperliquidExchange::onL2BookUpdate(const nlohmann::json& msg) {
75 event_queue_.push_back({FeedEvent::Type::L2_BOOK, msg});
76}
77
78void HyperliquidExchange::onTradesUpdate(const nlohmann::json& msg) {
79 if (!msg.contains("data")) return;
80 event_queue_.push_back({FeedEvent::Type::TRADES, msg["data"]});
81}
82
84 LOG_WARN("Hyperliquid WebSocket feed disconnected");
85 // Mark all tracked symbols as pending so snapshots are re-sent on reconnect
86 for (auto &[coin, feed] : map_coin_feed_) {
87 auto *symbol = sym_mgr.getSymbol(coin, venue_);
88 if (symbol) {
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);
92 }
93 }
94}
95
96// Drain WS events onto the exchange thread
98 for (auto &feed : md_feeds_) {
99 reinterpret_pointer_cast<md_feed::HyperliquidLiveWSFeed>(feed)->getInfo()->dispatch(100);
100 }
101 for (auto &evt : event_queue_) {
102 if (evt.type == FeedEvent::Type::L2_BOOK) {
103 processL2BookEvent(evt.data);
104 } else {
105 processTradesEvent(evt.data);
106 }
107 }
108 event_queue_.clear();
109}
110
111// Dispatches to the snapshot or incremental-diff handler based on which
112// shape the (already-unwrapped, see onL2BookUpdate) payload has — the two
113// never share a top-level key.
114void HyperliquidExchange::processL2BookEvent(const nlohmann::json& data) {
115 if (data.contains("levels")) {
116 processL2Snapshot(data);
117 } else if (data.contains("l") && data.contains("r")) {
118 processL2Diff(data);
119 }
120}
121
122// Full order-book snapshot (documented l2Book shape, and also what
123// Hyperliquid's undocumented l2 channel sends as the very first message
124// after subscribing). The whole book is authoritative here, so it's safe —
125// and necessary, to re-validate crossing — to clear all phantom liquidity
126// and rebuild every level from scratch. Also resets the "r" index-resolution
127// mirror (l2_ref_levels_) from this snapshot's own (already-ordered) levels.
128void HyperliquidExchange::processL2Snapshot(const nlohmann::json& data) {
129 if (!data.contains("coin") || !data.contains("levels")) return;
130
131 const std::string coin = data["coin"].get<std::string>();
132
133 auto *symbol = sym_mgr.getSymbol(coin, venue_);
134 if (!symbol) {
135 symbol = addSymbol(coin);
136 }
137
138 // levels[0] = bids, levels[1] = asks
139 const auto& levels_arr = data["levels"];
140 if (levels_arr.size() < 2) return;
141
142 uint64_t event_time_ms = data.value("time", uint64_t{0});
143 uint64_t event_time_ns = event_time_ms * utils::ONE_MILLISECOND_NS;
144
145 symbol->order_book_->clearMDOrders();
146
147 auto &ref = l2_ref_levels_[symbol];
148 ref[0].clear();
149 ref[1].clear();
150
151 auto process_side = [&](const nlohmann::json& side_levels, Side side, std::vector<price_t>& ref_side) {
152 auto book_side = to_book_side(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>());
156 auto price = to_price_t(px);
157 auto qty = to_qty_t(sz);
158 if (qty <= 0) [[unlikely]] continue;
159 auto order_id = utils::nextOrderId();
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) {
164 publishTradeSummary(symbol, summary);
165 }
166 }
167 if (qty > 0) {
168 symbol->order_book_->addOrder(order_id, book_side, price, qty, event_time_ns, 0, 0, true);
169 }
170 // Snapshot levels already arrive best-first, so appending
171 // preserves the correct order.
172 ref_side.push_back(price);
173 }
174 };
175
176 process_side(levels_arr[0], Side::BUY, ref[0]);
177 process_side(levels_arr[1], Side::SELL, ref[1]);
178
179 symbol->order_book_->setLastUpdate(event_time_ns, 0);
180
181 finalizeL2Event(symbol);
182
183 symbol->md_level_update_cache_.clear();
184 symbol->md_order_update_cache_.clear();
185 LOG_TRACE("Hyperliquid l2 snapshot applied: {}", coin);
186}
187
188// Incremental diff from Hyperliquid's undocumented l2 channel: "l" gives the
189// new absolute quantity at changed/added price levels; "r" gives indices
190// into the *previous* per-side ordered price array (l2_ref_levels_) for
191// levels that were removed entirely. Only the touched levels are mutated —
192// everything else in the book is left exactly as it was.
193void HyperliquidExchange::processL2Diff(const nlohmann::json& data) {
194 if (!data.contains("c")) return;
195
196 const auto coin = data["c"].get<std::string_view>();
197
198 auto *symbol = sym_mgr.getSymbol(coin, venue_);
199 if (!symbol) {
200 symbol = addSymbol(coin);
201 }
202
203 // levels[0] = bids, levels[1] = asks
204 const auto& levels_arr = data["l"];
205 if (levels_arr.size() < 2) return;
206
207 uint64_t event_time_ms = data.value("t", uint64_t{0});
208 uint64_t event_time_ns = event_time_ms * utils::ONE_MILLISECOND_NS;
209
210 auto &ref = l2_ref_levels_[symbol];
211
212 auto apply_removals = [&](const nlohmann::json& indices, Side side, std::vector<price_t>& ref_side) {
213 // Resolve every index against the array as it stood *before* this
214 // event's mutations (removing while iterating would shift later
215 // indices), then apply.
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]);
222 } else {
223 LOG_WARN("Hyperliquid l2 diff: removed-level index {} out of range (have {}) for {}",
224 idx, ref_side.size(), coin);
225 }
226 }
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()) {
230 ref_side.erase(it);
231 }
232 }
233 };
234
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]);
238 }
239
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>());
244 auto price = to_price_t(px);
245 auto qty = to_qty_t(sz);
246
247 applyPhantomLevelUpdate(symbol, side, price, qty, event_time_ns);
248
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);
253 }
254 }
255 };
256
257 apply_changes(levels_arr[0], Side::BUY, ref[0]);
258 apply_changes(levels_arr[1], Side::SELL, ref[1]);
259
260 symbol->order_book_->setLastUpdate(event_time_ns, 0);
261
262 finalizeL2Event(symbol);
263
264 symbol->md_level_update_cache_.clear();
265 symbol->md_order_update_cache_.clear();
266 LOG_TRACE("Hyperliquid l2 diff applied: {}", coin);
267}
268
269// Sets the phantom (real-market-mirroring) liquidity at (side, price) to
270// exactly target_qty, without disturbing any other price level or any order
271// belonging to the simulator's own user (tracked separately via
272// Symbol::findOrder — phantom orders are never registered there). Mirrors
273// the established incremental-update pattern in
274// CoinbaseExchange::dispatchEvent (exch_coinbase.cpp).
275void HyperliquidExchange::applyPhantomLevelUpdate(
276 Symbol* symbol, Side side, price_t price, qty_t target_qty, uint64_t event_time_ns)
277{
278 auto book_side = to_book_side(side);
279 auto &book = *symbol->order_book_;
280 auto [level, index] = book.getLevel(book_side, price);
281
282 if (!level) {
283 // Brand-new price level — the full target quantity is the delta
284 // from an implicit zero, and this price hasn't been checked for
285 // crossing the opposing side yet.
286 if (target_qty <= 0) return;
287 qty_t qty = target_qty;
288 auto order_id = utils::nextOrderId();
289 if (symbol->matching_engine_) {
290 auto trade_summaries = symbol->matching_engine_->match(
291 side, order_id, price, qty, book, event_time_ns, 0);
292 for (const auto& summary : trade_summaries) {
293 publishTradeSummary(symbol, summary);
294 }
295 }
296 if (qty > 0) {
297 book.addOrder(order_id, book_side, price, qty, event_time_ns, 0, 0, true);
298 }
299 return;
300 }
301
302 // Existing level: already known non-crossing, so no need to re-match —
303 // just adjust the phantom-only quantity (getMDLevelQty excludes the
304 // user's own resting quantity at this price) toward the target.
305 reconcilePhantomQty(symbol, side, price, target_qty, event_time_ns, 0, true);
306}
307
308// Shared tail for both processL2Snapshot and processL2Diff: dispatches the
309// first (SUB_RESPONSE) or routine (BOOK_SNAPSHOT) downstream update for the
310// L2_BOOK/L2 channels. See the design note above pending_md_subscription_.
311void HyperliquidExchange::finalizeL2Event(Symbol* symbol) {
312 // L2_BOOK and L2 (undocumented, compressed-diff variant) are independent
313 // downstream channels over the same book data — a symbol can have a
314 // pending subscriber on one while already having an active subscriber on
315 // the other, so each channel's first-snapshot delivery is tracked
316 // separately.
317 bool l2book_was_pending = false;
318 bool l2_was_pending = false;
319
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;
326 }
327
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;
334 }
335
336 if (!l2book_was_pending || !l2_was_pending) {
337 // Routine update — the publisher filters/formats per actual subscribers.
338 symbol->order_book_->populateL2Snapshot(md_queue_);
339 }
340}
341
342void HyperliquidExchange::processTradesEvent(const nlohmann::json& data) {
343 if (!data.is_array() || data.empty()) return;
344
345 const std::string coin = data[0].value("coin", "");
346 if (coin.empty()) return;
347
348 auto *symbol = sym_mgr.getSymbol(coin, venue_);
349 if (!symbol) return;
350
351 auto &book = *symbol->order_book_;
352
353 for (const auto& trade : data) {
354 std::string side_str = trade.value("side", "B");
355 Side side = (side_str == "B") ? Side::BUY : Side::SELL;
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});
359 uint64_t event_time_ns = time_ms * utils::ONE_MILLISECOND_NS;
360
361 auto price = to_price_t(px);
362 auto book_side = to_book_side(side);
363 auto order_id = utils::nextOrderId();
364
365 // The venue's print is replayed as an incoming aggressor order: it takes
366 // liquidity from the book exactly as the real taker did, filling any
367 // simulator order that was ahead of the phantom liquidity it swept. Only
368 // the resulting fills are published - the print itself is never relayed.
369 qty_t qty = to_qty_t(sz);
370 if (!symbol->matching_engine_) {
371 continue;
372 }
373 auto trade_summaries = symbol->matching_engine_->match(
374 side, order_id, price, qty, book, event_time_ns, 0);
375
376 if (qty > 0) {
377 // Treated as an aggressor order, so the unfilled remainder rests. It
378 // cannot cross: a remainder exists precisely because nothing was
379 // still crossable at this limit.
380 book.addOrder(order_id, book_side, price, qty, event_time_ns, 0, 0, true);
381 }
382
383 for (const auto& summary : trade_summaries) {
384 // The venue will report the same reduction again in its level update
385 // for this trade; credit it so that update does not remove it twice.
386 symbol->creditTradedQty(opposite_side(side), summary.price,
387 summary.phantom_qty, event_time_ns);
388 publishTradeSummary(symbol, summary);
389 }
390 }
391
392 // The l2Book/l2 channels are snapshot-driven here, so republish the book to
393 // show the liquidity these trades consumed.
394 book.populateL2Snapshot(md_queue_);
395 symbol->md_level_update_cache_.clear();
396 symbol->md_order_update_cache_.clear();
397}
398
400 const auto &msg = request.md_subscription;
401 std::string coin = request.symbol;
402
403 auto *symbol = sym_mgr.getSymbol(coin, venue_);
404 bool is_new = false;
405 if (!symbol) {
406 symbol = addSymbol(coin);
407 is_new = true;
408 }
409
410 symbol->num_subscriptions_.fetch_add(1, std::memory_order_relaxed);
411
412 auto channel = static_cast<HyperliquidChannel>(msg.channel);
413
414 if (use_live_feed_) {
415 if (is_new) {
416 // Subscribe to live feed for this coin
417 auto it_feed = map_coin_feed_.find(coin);
418 if (it_feed == map_coin_feed_.end()) {
419 // No existing feed — use or create one
420 std::shared_ptr<md_feed::HyperliquidLiveWSFeed> live_feed;
421 if (!md_feeds_.empty()) {
422 live_feed = std::dynamic_pointer_cast<md_feed::HyperliquidLiveWSFeed>(md_feeds_.front());
423 }
424 if (!live_feed) {
425 auto new_feed = std::make_shared<md_feed::HyperliquidLiveWSFeed>(this, live_ws_base_url_);
426 md_feeds_.emplace_back(new_feed);
427 new_feed->start();
428 live_feed = new_feed;
429 }
430 live_feed->addCoin(coin);
431 map_coin_feed_.emplace(coin, live_feed);
432 } else {
433 auto live_feed = std::dynamic_pointer_cast<md_feed::HyperliquidLiveWSFeed>(it_feed->second);
434 if (live_feed) {
435 live_feed->addCoin(coin);
436 }
437 }
438 // Mark as pending — snapshot will arrive on the next l2Book WS message.
439 // The trades channel has no upstream snapshot to wait for; it is served
440 // from the tape history below, which also delivers the subscription
441 // confirmation the publisher only emits on a SUB_RESPONSE.
442 if (channel == HyperliquidChannel::TRADES) {
443 publishTradeSubscriptionResponse(symbol, static_cast<uint8_t>(channel));
444 } else {
445 pending_md_subscription_[static_cast<size_t>(channel)].emplace(symbol);
446 }
447 } else {
448 auto &pending = pending_md_subscription_[static_cast<size_t>(channel)];
449 if (pending.find(symbol) == pending.end()) {
450 // Already have a snapshot, send it immediately
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) {
455 publishTradeSubscriptionResponse(symbol, static_cast<uint8_t>(channel));
456 }
457 }
458 }
459 } else {
460 // No live feed — send snapshot from whatever is in the book
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) {
465 publishTradeSubscriptionResponse(symbol, static_cast<uint8_t>(channel));
466 }
467 }
468}
469
471 std::string coin = request.symbol;
472 auto *symbol = sym_mgr.getSymbol(coin, venue_);
473 if (!symbol) return;
474
475 if (symbol->num_subscriptions_.fetch_sub(1, std::memory_order_relaxed) == 1) {
476 auto it_feed = map_coin_feed_.find(coin);
477 if (it_feed != map_coin_feed_.end()) {
478 // Don't stop the feed entirely; just stop tracking this coin's subscription
479 map_coin_feed_.erase(it_feed);
480 }
481 }
482}
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_
Definition exchange.hpp:181
void publishTradeSubscriptionResponse(Symbol *symbol, uint8_t channel)
Frames the SUB_RESPONSE for a venue's trade channel from the symbol's recent-trade history,...
Definition exchange.cpp:646
queue< uint8_t > md_queue_
Definition exchange.hpp:183
std::vector< std::unique_ptr< order_gateway::OrderGateway > > order_gateways_
Definition exchange.hpp:195
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,...
Definition exchange.cpp:715
std::vector< std::shared_ptr< md_feed::MDFeed > > md_feeds_
Feeds owned by the exchange and managed by base start()/stop().
Definition exchange.hpp:189
Exchange(Venue venue, const nlohmann::json &config)
Definition exchange.cpp:21
std::unique_ptr< md_publisher::MarketDataPublisher > md_publisher_
Definition exchange.hpp:196
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...
Definition exchange.cpp:607
void assignMatching(Symbol *symbol)
Points a new symbol at the venue's configured engine, creating the engine on first use,...
Definition exchange.cpp:254
queue< OrderResponse > response_queue_
Definition exchange.hpp:182
void onTradesUpdate(const nlohmann::json &msg) override
void onL2BookUpdate(const nlohmann::json &msg) override
void handleMdSubscription(const Request &request) 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,...
Definition exchange.hpp:30
HyperliquidChannel
The market-data channels the Hyperliquid adapter serves.
uint64_t nextOrderId() noexcept
Definition order.hpp:10
constexpr uint64_t ONE_MILLISECOND_NS
constexpr Side opposite_side()
Definition order.hpp:39
@ HYPERLIQUID
Definition types.hpp:158
constexpr price_t to_price_t(double price)
Scales a decimal into the fixed-point representation, rounding to the nearest tick rather than trunca...
Definition types.hpp:42
orderbook::Side to_book_side(Side side)
int_fast64_t qty_t
Definition types.hpp:22
constexpr qty_t to_qty_t(double qty)
Definition types.hpp:50
int_fast64_t price_t
Definition types.hpp:21
MDSubscriptionMessage md_subscription
Definition messages.hpp:285
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,...
Definition symbol.hpp:116
engine::MatchingEngine * matching_engine_
Definition symbol.hpp:47
std::vector< MDLevel > md_level_update_cache_
Definition symbol.hpp:51
std::vector< MDOrder > md_order_update_cache_
Definition symbol.hpp:52
std::shared_ptr< OrderBook > order_book_
Definition symbol.hpp:48
std::atomic_uint16_t num_subscriptions_
Definition symbol.hpp:49