2#include <slick/logger.hpp>
3#include <slick/net/http.hpp>
15using Http = slick::net::Http;
19 slick::queue<Request>& request_queue,
20 slick::queue<OrderResponse>& response_queue)
22 , base_url_(config.value(
"base_url",
"https://api.hyperliquid.xyz"))
23 , default_wallet_(config.value(
"default_wallet",
"0x0000000000000000000000000000000000000001"))
24 , info_(base_url_, false)
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());
59std::string HyperliquidRestOrderGateway::coin_for_asset(
int asset_index)
const {
63 auto it = info_.name_to_coin.find(
"@" + std::to_string(asset_index));
64 if (it != info_.name_to_coin.end()) {
70std::string HyperliquidRestOrderGateway::extract_wallet(
const json& body, uWS::HttpRequest* req) {
72 std::string_view hdr = req->getHeader(
"x-wallet-address");
73 if (!hdr.empty())
return std::string(hdr);
75 if (body.contains(
"vaultAddress") && !body[
"vaultAddress"].is_null()) {
76 return body[
"vaultAddress"].get<std::string>();
79 return default_wallet_;
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);
108void HyperliquidRestOrderGateway::handle_exchange(
109 uWS::HttpResponse<false>* res, uWS::HttpRequest* req)
111 auto request_data = std::make_shared<PostRequestData>();
113 res->onAborted([request_data]() {
114 LOG_WARN(
"HyperliquidREST: POST /exchange aborted");
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;
122 json body = json::parse(request_data->body_buffer);
123 std::string user_id = extract_wallet(body, req);
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"})");
131 const auto& action = body[
"action"];
132 std::string
type = action.value(
"type",
"");
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);
143 res->writeStatus(
"400 Bad Request")
144 ->writeHeader(
"Content-Type",
"application/json")
145 ->end(std::format(R
"({{"status":"err","response":"unsupported action type: {}"}})", type));
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()));
155void HyperliquidRestOrderGateway::handle_info(
156 uWS::HttpResponse<false>* res, uWS::HttpRequest*)
161void HyperliquidRestOrderGateway::process_order_action(
162 uWS::HttpResponse<false>* res,
const json& action,
const std::string& user_id)
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"})");
171 json statuses = json::array();
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);
180 std::string coin = coin_for_asset(asset_idx);
183 if (order[
"a"].is_string()) {
184 coin = order[
"a"].get<std::string>();
186 statuses.push_back({{
"error", std::format(
"unknown asset index {}", asset_idx)}});
191 double price_d = std::stod(price_str);
192 double size_d = std::stod(size_str);
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");
206 }
else if (t.contains(
"trigger")) {
214 if (order.contains(
"c") && order[
"c"].is_string()) {
215 cloid = order[
"c"].get<std::string>();
223 uint64_t response_read_index =
response_queue_.initial_reading_index();
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;
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)));
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);
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;
260 while (std::chrono::steady_clock::now() < deadline) {
263 std::string_view(data->user_id) == stored_uid &&
264 std::string_view(data->client_order_id) == stored_cloid)
269 std::this_thread::sleep_for(poll_delay);
273 statuses.push_back({{
"error",
"timeout"}});
282 statuses.push_back({{
"resting", {{
"oid", oid_str.empty() ? 0 : std::stoll(oid_str)}}}});
290 {
"data", {{
"statuses", statuses}}}
293 res->writeHeader(
"Content-Type",
"application/json")->end(response.dump());
296void HyperliquidRestOrderGateway::process_cancel_action(
297 uWS::HttpResponse<false>* res,
const json& action,
const std::string& user_id)
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"})");
306 json statuses = json::array();
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};
312 std::string coin = coin_for_asset(asset_idx);
313 if (coin.empty() && cancel[
"a"].is_string()) {
314 coin = cancel[
"a"].get<std::string>();
317 statuses.push_back({{
"error",
"unknown asset"}});
321 std::string oid_str = std::to_string(oid);
333 statuses.push_back({{
"success", oid}});
340 {
"data", {{
"statuses", statuses}}}
343 res->writeHeader(
"Content-Type",
"application/json")->end(response.dump());
346void HyperliquidRestOrderGateway::process_cancel_by_cloid_action(
347 uWS::HttpResponse<false>* res,
const json& action,
const std::string& user_id)
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"})");
356 json statuses = json::array();
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",
"");
362 std::string coin = coin_for_asset(asset_idx);
363 if (coin.empty() && cancel[
"a"].is_string()) {
364 coin = cancel[
"a"].get<std::string>();
366 if (coin.empty() || cloid.empty()) {
367 statuses.push_back({{
"error",
"invalid cancel request"}});
381 statuses.push_back({{
"success", cloid}});
388 {
"data", {{
"statuses", statuses}}}
391 res->writeHeader(
"Content-Type",
"application/json")->end(response.dump());
394void HyperliquidRestOrderGateway::process_batch_modify_action(
395 uWS::HttpResponse<false>* res,
const json& action,
const std::string& user_id)
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"})");
404 json statuses = json::array();
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"}});
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");
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>();
422 statuses.push_back({{
"error",
"unknown asset"}});
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));
438 request->modify_order.new_price = new_price;
439 request->modify_order.new_qty = new_qty;
442 statuses.push_back({{
"success", oid}});
448 {
"type",
"batchModify"},
449 {
"data", {{
"statuses", statuses}}}
452 res->writeHeader(
"Content-Type",
"application/json")->end(response.dump());
HyperliquidRestOrderGateway(const json &config, slick::queue< Request > &request_queue, slick::queue< OrderResponse > &response_queue)
std::string_view type() const noexcept override
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)
Conversions between wire decimals with a constant exponent of -9 (CME PRICE9, ICE Decimal9) and the s...
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()
constexpr price_t NULL_PRICE
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...
constexpr const char * to_string(FeedState state) noexcept
constexpr qty_t to_qty_t(double qty)
OrdRejectReason reject_reason