Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
hyperliquid_live_ws_feed.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <md_feed/md_feed.hpp>
4#include <hyperliquid/info.hpp>
5#include <hyperliquid/utils/l2_diff.hpp>
6#include <nlohmann/json.hpp>
7#include <memory>
8#include <string>
9#include <vector>
10#include <unordered_map>
11#include <utility>
12
13namespace slick::sim::md_feed {
14
16 virtual void onL2BookUpdate(const nlohmann::json& msg) = 0;
17 virtual void onTradesUpdate(const nlohmann::json& msg) = 0;
18 virtual void onHyperliquidDisconnected() = 0;
19 virtual ~HyperliquidFeedCallbacks() = default;
20};
21
23 std::shared_ptr<hyperliquid::Info> info_;
24 std::vector<std::string> coins_;
25 // coin -> {l2Book sub_id, trades sub_id}
26 std::unordered_map<std::string, std::pair<int, int>> sub_ids_;
27 HyperliquidFeedCallbacks* callbacks_;
28 bool started_ = false;
29
30public:
32 std::string_view base_url,
33 const std::vector<std::string>& coins = {})
34 : info_(std::make_shared<hyperliquid::Info>(base_url, /*skip_ws=*/false, /*user_thread_dispatch=*/true))
35 , coins_(coins)
36 , callbacks_(callbacks)
37 {}
38
39 ~HyperliquidLiveWSFeed() override = default;
40
41 void start() override {
42 started_ = true;
43 for (const auto& coin : coins_) {
44 subscribeCoin(coin);
45 }
46 }
47
48 void stop() override {
49 for (auto& [coin, ids] : sub_ids_) {
50 info_->unsubscribe({{"type", "l2"}, {"c", coin}}, ids.first);
51 info_->unsubscribe({{"type", "trades"}, {"coin", coin}}, ids.second);
52 }
53 sub_ids_.clear();
54 started_ = false;
55 }
56
57 // Add a coin subscription at runtime (called by the exchange when a new symbol is subscribed)
58 void addCoin(const std::string& coin) {
59 if (std::find(coins_.begin(), coins_.end(), coin) == coins_.end()) {
60 coins_.push_back(coin);
61 }
62 if (started_ && sub_ids_.find(coin) == sub_ids_.end()) {
63 subscribeCoin(coin);
64 }
65 }
66
67 hyperliquid::Info* getInfo() const { return info_.get(); }
68
69private:
70 void subscribeCoin(const std::string& coin) {
71 int l2_id = info_->subscribe(
72 {{"type", "l2"}, {"c", coin}},
73 [this](const nlohmann::json& msg) {
74 this->on_l2(msg);
75 }
76 );
77 int trades_id = info_->subscribe(
78 {{"type", "trades"}, {"coin", coin}},
79 [this](const nlohmann::json& msg) { callbacks_->onTradesUpdate(msg); }
80 );
81 sub_ids_[coin] = {l2_id, trades_id};
82 }
83
84 void on_l2(const nlohmann::json& msg);
85};
86
87} // end namespace slick::sim::md_feed
HyperliquidLiveWSFeed(HyperliquidFeedCallbacks *callbacks, std::string_view base_url, const std::vector< std::string > &coins={})
virtual void onL2BookUpdate(const nlohmann::json &msg)=0
virtual void onTradesUpdate(const nlohmann::json &msg)=0