Slick Sim 0.10.1
Exchange simulator that shadows real venues for risk-free strategy testing
Loading...
Searching...
No Matches
hyperliquid_rest_order_gateway.cpp
Go to the documentation of this file.
2#include <slick/logger.hpp>
3#include <slick/net/http.hpp>
6#include <utils/timestamp.hpp>
7#include <thread>
8#include <chrono>
9#include <cstring>
10#include <format>
11
12using namespace slick::sim::order_gateway;
13using namespace slick::sim;
14using namespace slick::sim::utils;
15using Http = slick::net::Http;
16
18 const json& config,
19 slick::queue<Request>& request_queue,
20 slick::queue<OrderResponse>& response_queue)
21 : RestWsOrderGateway(Venue::HYPERLIQUID, request_queue, response_queue, config.value("port", 4003))
22 , base_url_(config.value("base_url", "https://api.hyperliquid.xyz"))
23 , default_wallet_(config.value("default_wallet", "0x0000000000000000000000000000000000000001"))
24 , info_(base_url_, false)
25{
26 try {
27 info_.load_meta();
28 LOG_INFO("HyperliquidREST: loaded {} assets", info_.coin_to_asset.size());
29 } catch (const std::exception& e) {
30 LOG_WARN("HyperliquidREST: exception loading meta: {}", e.what());
31 }
32}
33
34// void HyperliquidRestOrderGateway::load_meta() {
35// try {
36// json meta_req = {{"type", "meta"}};
37// auto rsp = Http::post(base_url_ + "/info", meta_req.dump(), {{"Content-Type", "application/json"}});
38// if (!rsp.is_ok()) {
39// LOG_WARN("HyperliquidREST: failed to load meta: {}", rsp.result_text);
40// return;
41// }
42// auto meta = json::parse(rsp.result_text);
43// if (!meta.contains("universe")) return;
44// int idx = 0;
45// for (const auto& asset : meta["universe"]) {
46// std::string name = asset.value("name", "");
47// if (!name.empty()) {
48// asset_to_coin_[idx] = name;
49// coin_to_asset_[name] = idx;
50// }
51// ++idx;
52// }
53// LOG_INFO("HyperliquidREST: loaded {} assets", asset_to_coin_.size());
54// } catch (const std::exception& e) {
55// LOG_WARN("HyperliquidREST: exception loading meta: {}", e.what());
56// }
57// }
58
59std::string HyperliquidRestOrderGateway::coin_for_asset(int asset_index) const {
60 // auto it = asset_to_coin_.find(asset_index);
61 // if (it != asset_to_coin_.end()) return it->second;
62 // return {};
63 auto it = info_.name_to_coin.find("@" + std::to_string(asset_index));
64 if (it != info_.name_to_coin.end()) {
65 return it->second;
66 }
67 return {};
68}
69
70std::string HyperliquidRestOrderGateway::extract_wallet(const json& body, uWS::HttpRequest* req) {
71 // 1. X-Wallet-Address header
72 std::string_view hdr = req->getHeader("x-wallet-address");
73 if (!hdr.empty()) return std::string(hdr);
74 // 2. vaultAddress in body
75 if (body.contains("vaultAddress") && !body["vaultAddress"].is_null()) {
76 return body["vaultAddress"].get<std::string>();
77 }
78 // 3. Fallback: configured default
79 return default_wallet_;
80}
81
82// void HyperliquidRestOrderGateway::start() {
83// thread_ = std::thread([this]() {
84// auto app = uWS::App();
85// setup_routes(app);
86// app.listen(port_, [this](auto* listen_socket) {
87// listen_socket_ = listen_socket;
88// if (listen_socket) {
89// loop_ = uWS::Loop::get();
90// LOG_INFO("HyperliquidREST started on port {}", port_);
91// } else {
92// LOG_ERROR("HyperliquidREST failed to listen on port {}", port_);
93// }
94// }).run();
95// });
96// }
97
98void HyperliquidRestOrderGateway::setup_routes(uWS::App& app) {
99 app.post("/exchange", [this](auto* res, auto* req) {
100 handle_exchange(res, req);
101 }).post("/info", [this](auto* res, auto* req) {
102 handle_info(res, req);
103 }).get("/info", [this](auto* res, auto* req) {
104 handle_info(res, req);
105 });
106}
107
108void HyperliquidRestOrderGateway::handle_exchange(
109 uWS::HttpResponse<false>* res, uWS::HttpRequest* req)
110{
111 auto request_data = std::make_shared<PostRequestData>();
112
113 res->onAborted([request_data]() {
114 LOG_WARN("HyperliquidREST: POST /exchange aborted");
115 });
116
117 res->onData([this, res, req, request_data](std::string_view chunk, bool is_last) mutable {
118 request_data->body_buffer.append(chunk);
119 if (!is_last) return;
120
121 try {
122 json body = json::parse(request_data->body_buffer);
123 std::string user_id = extract_wallet(body, req);
124
125 if (!body.contains("action")) {
126 res->writeStatus("400 Bad Request")
127 ->writeHeader("Content-Type", "application/json")
128 ->end(R"({"status":"err","response":"missing action"})");
129 return;
130 }
131 const auto& action = body["action"];
132 std::string type = action.value("type", "");
133
134 if (type == "order") {
135 process_order_action(res, action, user_id);
136 } else if (type == "cancel") {
137 process_cancel_action(res, action, user_id);
138 } else if (type == "cancelByCloid") {
139 process_cancel_by_cloid_action(res, action, user_id);
140 } else if (type == "batchModify") {
141 process_batch_modify_action(res, action, user_id);
142 } else {
143 res->writeStatus("400 Bad Request")
144 ->writeHeader("Content-Type", "application/json")
145 ->end(std::format(R"({{"status":"err","response":"unsupported action type: {}"}})", type));
146 }
147 } catch (const std::exception& e) {
148 res->writeStatus("400 Bad Request")
149 ->writeHeader("Content-Type", "application/json")
150 ->end(std::format(R"({{"status":"err","response":"parse error: {}"}})", e.what()));
151 }
152 });
153}
154
155void HyperliquidRestOrderGateway::handle_info(
156 uWS::HttpResponse<false>* res, uWS::HttpRequest*)
157{
158 proxy_hyperliquid_info_request(res, base_url_);
159}
160
161void HyperliquidRestOrderGateway::process_order_action(
162 uWS::HttpResponse<false>* res, const json& action, const std::string& user_id)
163{
164 if (!action.contains("orders") || !action["orders"].is_array()) {
165 res->writeStatus("400 Bad Request")
166 ->writeHeader("Content-Type", "application/json")
167 ->end(R"({"status":"err","response":"missing orders array"})");
168 return;
169 }
170
171 json statuses = json::array();
172
173 for (const auto& order : action["orders"]) {
174 int asset_idx = order["a"].is_number() ? order["a"].get<int>() : -1;
175 bool is_buy = order.value("b", true);
176 std::string price_str = order.value("p", "0");
177 std::string size_str = order.value("s", "0");
178 [[maybe_unused]] bool reduce_only = order.value("r", false);
179
180 std::string coin = coin_for_asset(asset_idx);
181 if (coin.empty()) {
182 // Fall back: allow coin name as string in "a" if asset map is empty
183 if (order["a"].is_string()) {
184 coin = order["a"].get<std::string>();
185 } else {
186 statuses.push_back({{"error", std::format("unknown asset index {}", asset_idx)}});
187 continue;
188 }
189 }
190
191 double price_d = std::stod(price_str);
192 double size_d = std::stod(size_str);
193 auto price = to_price_t(price_d);
194 auto qty = to_qty_t(size_d);
195
196 // Parse order type
197 OrderType order_type = OrderType::LIMIT;
199 if (order.contains("t")) {
200 const auto& t = order["t"];
201 if (t.contains("limit")) {
202 std::string tif_str = t["limit"].value("tif", "Gtc");
203 if (tif_str == "Ioc") tif = TimeInForce::IMMEDIATE_OR_CANCEL;
204 else if (tif_str == "Alo") tif = TimeInForce::GOOD_TILL_CANCEL; // post-only
205 // Gtc is default
206 } else if (t.contains("trigger")) {
207 // Simplified: treat triggers as limit orders for the sim
208 order_type = OrderType::LIMIT;
209 }
210 }
211
212 // Generate a client order id from cloid field or nonce-based
213 std::string cloid;
214 if (order.contains("c") && order["c"].is_string()) {
215 cloid = order["c"].get<std::string>();
216 } else {
217 cloid = std::format("hl_{}", get_current_time_ns());
218 }
219
220 // Capture the response cursor before publishing the request. The exchange
221 // can publish PENDING_NEW before this thread runs again; taking the cursor
222 // afterwards could skip that response and time out an accepted order.
223 uint64_t response_read_index = response_queue_.initial_reading_index();
224
225 auto req_index = request_queue_.reserve();
226 auto* request = request_queue_[req_index];
227 request->time_stamp = get_current_time_ns();
228 utils::copy_wire_field(request->symbol, coin);
229 request->msg_type = MessageType::NEW_ORDER_SINGLE;
230
231 utils::copy_wire_field(request->add_order.user_id, user_id);
232 utils::copy_wire_field(request->add_order.client_order_id, cloid);
233
234 request->add_order.side = is_buy ? Side::BUY : Side::SELL;
235 request->add_order.type = order_type;
236 request->add_order.time_in_force = tif;
237 request->add_order.price = price;
238 request->add_order.qty = qty;
239 request->add_order.take_profit_price = NULL_PRICE;
240 request->add_order.stop_loss_price = NULL_PRICE;
241 request->add_order.expire_time = 0;
242
243 // Save stored uid/cloid (potentially truncated) before publish for response matching
244 std::string stored_uid(request->add_order.user_id,
245 strnlen(request->add_order.user_id, sizeof(request->add_order.user_id)));
246 std::string stored_cloid(request->add_order.client_order_id,
247 strnlen(request->add_order.client_order_id, sizeof(request->add_order.client_order_id)));
248
249 request_queue_.publish(req_index);
250
251 LOG_INFO("HyperliquidREST: order queued user={} coin={} side={} px={} sz={} cloid={}",
252 user_id, coin, is_buy ? "B" : "A", price_str, size_str, cloid);
253
254 // Poll for response
255 constexpr auto timeout = std::chrono::milliseconds(5000);
256 constexpr auto poll_delay = std::chrono::microseconds(100);
257 auto deadline = std::chrono::steady_clock::now() + timeout;
258 OrderResponse* resp = nullptr;
259
260 while (std::chrono::steady_clock::now() < deadline) {
261 auto [data, sz] = response_queue_.read(response_read_index);
262 if (data &&
263 std::string_view(data->user_id) == stored_uid &&
264 std::string_view(data->client_order_id) == stored_cloid)
265 {
266 resp = data;
267 break;
268 }
269 std::this_thread::sleep_for(poll_delay);
270 }
271
272 if (!resp) {
273 statuses.push_back({{"error", "timeout"}});
274 continue;
275 }
276
277 if (resp->order_status == OrderStatus::REJECTED) {
278 statuses.push_back({{"error", to_string(resp->reject_reason)}});
279 } else {
280 std::string oid_str(resp->order_id,
281 strnlen(resp->order_id, sizeof(resp->order_id)));
282 statuses.push_back({{"resting", {{"oid", oid_str.empty() ? 0 : std::stoll(oid_str)}}}});
283 }
284 }
285
286 json response = {
287 {"status", "ok"},
288 {"response", {
289 {"type", "order"},
290 {"data", {{"statuses", statuses}}}
291 }}
292 };
293 res->writeHeader("Content-Type", "application/json")->end(response.dump());
294}
295
296void HyperliquidRestOrderGateway::process_cancel_action(
297 uWS::HttpResponse<false>* res, const json& action, const std::string& user_id)
298{
299 if (!action.contains("cancels") || !action["cancels"].is_array()) {
300 res->writeStatus("400 Bad Request")
301 ->writeHeader("Content-Type", "application/json")
302 ->end(R"({"status":"err","response":"missing cancels array"})");
303 return;
304 }
305
306 json statuses = json::array();
307
308 for (const auto& cancel : action["cancels"]) {
309 int asset_idx = cancel["a"].is_number() ? cancel["a"].get<int>() : -1;
310 int64_t oid = cancel["o"].is_number() ? cancel["o"].get<int64_t>() : int64_t{0};
311
312 std::string coin = coin_for_asset(asset_idx);
313 if (coin.empty() && cancel["a"].is_string()) {
314 coin = cancel["a"].get<std::string>();
315 }
316 if (coin.empty()) {
317 statuses.push_back({{"error", "unknown asset"}});
318 continue;
319 }
320
321 std::string oid_str = std::to_string(oid);
322
323 auto req_index = request_queue_.reserve();
324 auto* request = request_queue_[req_index];
325 request->time_stamp = get_current_time_ns();
326 utils::copy_wire_field(request->symbol, coin);
327 request->msg_type = MessageType::ORDER_CANCEL_REQUEST;
328
329 utils::copy_wire_field(request->cancel_order.user_id, user_id);
330 utils::copy_wire_field(request->cancel_order.order_id, oid_str);
331
332 request_queue_.publish(req_index);
333 statuses.push_back({{"success", oid}});
334 }
335
336 json response = {
337 {"status", "ok"},
338 {"response", {
339 {"type", "cancel"},
340 {"data", {{"statuses", statuses}}}
341 }}
342 };
343 res->writeHeader("Content-Type", "application/json")->end(response.dump());
344}
345
346void HyperliquidRestOrderGateway::process_cancel_by_cloid_action(
347 uWS::HttpResponse<false>* res, const json& action, const std::string& user_id)
348{
349 if (!action.contains("cancels") || !action["cancels"].is_array()) {
350 res->writeStatus("400 Bad Request")
351 ->writeHeader("Content-Type", "application/json")
352 ->end(R"({"status":"err","response":"missing cancels array"})");
353 return;
354 }
355
356 json statuses = json::array();
357
358 for (const auto& cancel : action["cancels"]) {
359 int asset_idx = cancel["a"].is_number() ? cancel["a"].get<int>() : -1;
360 std::string cloid = cancel.value("c", "");
361
362 std::string coin = coin_for_asset(asset_idx);
363 if (coin.empty() && cancel["a"].is_string()) {
364 coin = cancel["a"].get<std::string>();
365 }
366 if (coin.empty() || cloid.empty()) {
367 statuses.push_back({{"error", "invalid cancel request"}});
368 continue;
369 }
370
371 auto req_index = request_queue_.reserve();
372 auto* request = request_queue_[req_index];
373 request->time_stamp = get_current_time_ns();
374 utils::copy_wire_field(request->symbol, coin);
375 request->msg_type = MessageType::ORDER_CANCEL_REQUEST;
376
377 utils::copy_wire_field(request->cancel_order.user_id, user_id);
378 utils::copy_wire_field(request->cancel_order.client_order_id, cloid);
379
380 request_queue_.publish(req_index);
381 statuses.push_back({{"success", cloid}});
382 }
383
384 json response = {
385 {"status", "ok"},
386 {"response", {
387 {"type", "cancel"},
388 {"data", {{"statuses", statuses}}}
389 }}
390 };
391 res->writeHeader("Content-Type", "application/json")->end(response.dump());
392}
393
394void HyperliquidRestOrderGateway::process_batch_modify_action(
395 uWS::HttpResponse<false>* res, const json& action, const std::string& user_id)
396{
397 if (!action.contains("modifies") || !action["modifies"].is_array()) {
398 res->writeStatus("400 Bad Request")
399 ->writeHeader("Content-Type", "application/json")
400 ->end(R"({"status":"err","response":"missing modifies array"})");
401 return;
402 }
403
404 json statuses = json::array();
405
406 for (const auto& mod : action["modifies"]) {
407 int64_t oid = mod.value("oid", int64_t{0});
408 if (!mod.contains("order")) {
409 statuses.push_back({{"error", "missing order in modify"}});
410 continue;
411 }
412 const auto& order = mod["order"];
413 int asset_idx = order["a"].is_number() ? order["a"].get<int>() : -1;
414 std::string price_str = order.value("p", "0");
415 std::string size_str = order.value("s", "0");
416
417 std::string coin = coin_for_asset(asset_idx);
418 if (coin.empty() && order.contains("a") && order["a"].is_string()) {
419 coin = order["a"].get<std::string>();
420 }
421 if (coin.empty()) {
422 statuses.push_back({{"error", "unknown asset"}});
423 continue;
424 }
425
426 std::string oid_str = std::to_string(oid);
427 auto new_price = to_price_t(std::stod(price_str));
428 auto new_qty = to_qty_t(std::stod(size_str));
429
430 auto req_index = request_queue_.reserve();
431 auto* request = request_queue_[req_index];
432 request->time_stamp = get_current_time_ns();
433 utils::copy_wire_field(request->symbol, coin);
434 request->msg_type = MessageType::ORDER_REPLACE_REQUEST;
435
436 utils::copy_wire_field(request->modify_order.user_id, user_id);
437 utils::copy_wire_field(request->modify_order.order_id, oid_str);
438 request->modify_order.new_price = new_price;
439 request->modify_order.new_qty = new_qty;
440
441 request_queue_.publish(req_index);
442 statuses.push_back({{"success", oid}});
443 }
444
445 json response = {
446 {"status", "ok"},
447 {"response", {
448 {"type", "batchModify"},
449 {"data", {{"statuses", statuses}}}
450 }}
451 };
452 res->writeHeader("Content-Type", "application/json")->end(response.dump());
453}
HyperliquidRestOrderGateway(const json &config, slick::queue< Request > &request_queue, slick::queue< OrderResponse > &response_queue)
slick::queue< Request > & request_queue_
slick::queue< OrderResponse > & response_queue_
RestWsOrderGateway(Venue venue, slick::queue< Request > &request_queue, slick::queue< OrderResponse > &response_queue, uint32_t port)
slick::net::Http Http
nlohmann::json json
Definition order.hpp:16
Conversions between wire decimals with a constant exponent of -9 (CME PRICE9, ICE Decimal9) and the s...
Definition decimal.hpp:9
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()
Definition timestamp.hpp:93
constexpr price_t NULL_PRICE
Definition types.hpp:28
@ HYPERLIQUID
Definition types.hpp:158
void proxy_hyperliquid_info_request(uWS::HttpResponse< false > *res, const std::string &upstream_base_url)
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
constexpr const char * to_string(FeedState state) noexcept
constexpr qty_t to_qty_t(double qty)
Definition types.hpp:50
OrdRejectReason reject_reason
Definition messages.hpp:312