// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
pub struct HyperliquidCore {
pub exchange: crate::exchange::Exchange,
}
impl HyperliquidCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { exchange: crate::exchange::Exchange::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = HyperliquidCore::describe(self);
self.initialize_properties(described);
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for HyperliquidCore {
fn nonce(&self, ) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::nonce(self, )
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_order(self, order, &[market])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_funding_rate(self, rate, &[market])
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_ledger_entry(self, entry, &[currency])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_transfer(self, transfer, &[currency])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_currency(self, currency)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_open_interest(self, interest, &[market])
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_margin_modification(self, data, &[market])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_transaction(self, transaction, &[currency])
}
fn parse_income(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_income(self, info, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::sign(self, path, &[api, method, params, headers, body])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for HyperliquidCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"action_hash" => self.action_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]),
"add_margin" => self.add_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"amount_to_precision" => self.amount_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"approve_builder_fee" => self.approve_builder_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"build_approve_builder_fee_sig" => self.build_approve_builder_fee_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"build_usd_class_send_sig" => self.build_usd_class_send_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"build_usd_send_sig" => self.build_usd_send_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"build_user_abstraction_sig" => self.build_user_abstraction_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"build_user_dex_abstraction_sig" => self.build_user_dex_abstraction_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"build_withdraw_sig" => self.build_withdraw_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"calculate_price_precision" => self.calculate_price_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null)),
"calculate_rate_limiter_cost" => self.calculate_rate_limiter_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"cancel_all_orders_after" => self.cancel_all_orders_after(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders_for_symbols" => self.cancel_orders_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders_request" => self.cancel_orders_request(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"cancel_twap_order" => self.cancel_twap_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"construct_phantom_agent" => self.construct_phantom_agent(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_order_request" => self.create_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_orders_request" => self.create_orders_request(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"create_sub_account" => self.create_sub_account(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_twap_order" => self.create_twap_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_vault" => self.create_vault(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"edit_orders" => self.edit_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"edit_orders_request" => self.edit_orders_request(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"enable_user_dex_abstraction" => self.enable_user_dex_abstraction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"extract_type_from_delta" => self.extract_type_from_delta(&args[..]),
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_canceled_and_closed_orders" => self.fetch_canceled_and_closed_orders(&args[..]).await,
"fetch_canceled_orders" => self.fetch_canceled_orders(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_currencies" => self.fetch_currencies(&args[..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_funding_history" => self.fetch_funding_history(&args[..]).await,
"fetch_funding_rate" => self.fetch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&args[..]).await,
"fetch_funding_rates" => self.fetch_funding_rates(&args[..]).await,
"fetch_hip3_markets" => self.fetch_hip3_markets(&args[..]).await,
"fetch_ledger" => self.fetch_ledger(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interests" => self.fetch_open_interests(&args[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders" => self.fetch_orders(&args[..]).await,
"fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_spot_markets" => self.fetch_spot_markets(&args[..]).await,
"fetch_status" => self.fetch_status(&args[..]).await,
"fetch_swap_markets" => self.fetch_swap_markets(&args[..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_time" => self.fetch_time(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_trading_fee" => self.fetch_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"get_dex_from_hip3_symbol" => self.get_dex_from_hip3_symbol(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_dex_from_symbols" => self.get_dex_from_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"handle_builder_fee_approval" => self.handle_builder_fee_approval().await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"handle_public_address" => self.handle_public_address(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"hash_message" => self.hash_message(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"initialize_client" => self.initialize_client().await,
"is_unified_enabled" => self.is_unified_enabled(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"market" => self.market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"modify_margin_helper" => self.modify_margin_helper(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"nonce" => self.nonce(),
"parse_create_edit_order_args" => self.parse_create_edit_order_args(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), &args[5.min(args.len())..]),
"parse_currency" => self.parse_currency(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_funding_rate" => self.parse_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_income" => self.parse_income(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ledger_entry" => self.parse_ledger_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_margin_modification" => self.parse_margin_modification(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_open_interest" => self.parse_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trading_fee" => self.parse_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"price_to_precision" => self.price_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"reduce_margin" => self.reduce_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"reserve_request_weight" => self.reserve_request_weight(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_agent_abstraction" => self.set_agent_abstraction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_margin_mode" => self.set_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_ref" => self.set_ref().await,
"set_user_abstraction" => self.set_user_abstraction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"sign_hash" => self.sign_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_l1_action" => self.sign_l1_action(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]),
"sign_message" => self.sign_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_user_signed_action" => self.sign_user_signed_action(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"transfer" => self.transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"update_spot_currency_code" => self.update_spot_currency_code(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"withdraw" => self.withdraw(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for HyperliquidCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for HyperliquidCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl HyperliquidCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.super_describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("hyperliquid".into()));
m.insert("name".to_string(), Value::Str("Hyperliquid".into()));
m.insert("countries".to_string(), Value::from(vec![]));
m.insert("version".to_string(), Value::Str("v1".into()));
m.insert("rateLimit".to_string(), Value::Int(50));
m.insert("certified".to_string(), Value::Bool(true));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("dex".to_string(), Value::Bool(true));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".to_string(), Value::Bool(true));
m.insert("borrowCrossMargin".to_string(), Value::Bool(false));
m.insert("borrowIsolatedMargin".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(false));
m.insert("cancelAllOrdersAfter".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("cancelOrdersForSymbols".to_string(), Value::Bool(true));
m.insert("closeAllPositions".to_string(), Value::Bool(false));
m.insert("closePosition".to_string(), Value::Bool(false));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketSellOrderWithCost".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(true));
m.insert("createOrderWithTakeProfitAndStopLoss".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("createStopOrder".to_string(), Value::Bool(true));
m.insert("createTriggerOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("editOrders".to_string(), Value::Bool(true));
m.insert("fetchAccounts".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBorrowInterest".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(false));
m.insert("fetchCanceledAndClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(true));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDepositAddress".to_string(), Value::Bool(false));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchDepositWithdrawFee".to_string(), Value::Str("emulated".into()));
m.insert("fetchDepositWithdrawFees".to_string(), Value::Bool(false));
m.insert("fetchFundingHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(true));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(true));
m.insert("fetchLeverage".to_string(), Value::Bool(false));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchLiquidations".to_string(), Value::Bool(false));
m.insert("fetchMarginMode".to_string(), Value::Null);
m.insert("fetchMarketLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(false));
m.insert("fetchMyLiquidations".to_string(), Value::Bool(false));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("fetchOpenInterestHistory".to_string(), Value::Bool(false));
m.insert("fetchOpenInterests".to_string(), Value::Bool(true));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchOrderTrades".to_string(), Value::Bool(false));
m.insert("fetchPosition".to_string(), Value::Bool(true));
m.insert("fetchPositionMode".to_string(), Value::Bool(false));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsRisk".to_string(), Value::Bool(false));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchStatus".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Str("emulated".into()));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTime".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(true));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchTransfer".to_string(), Value::Bool(false));
m.insert("fetchTransfers".to_string(), Value::Bool(false));
m.insert("fetchWithdrawal".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("reduceMargin".to_string(), Value::Bool(true));
m.insert("repayCrossMargin".to_string(), Value::Bool(false));
m.insert("repayIsolatedMargin".to_string(), Value::Bool(false));
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("setLeverage".to_string(), Value::Bool(true));
m.insert("setMarginMode".to_string(), Value::Bool(true));
m.insert("setPositionMode".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(true));
m.insert("withdraw".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".into()));
m.insert("3m".to_string(), Value::Str("3m".into()));
m.insert("5m".to_string(), Value::Str("5m".into()));
m.insert("15m".to_string(), Value::Str("15m".into()));
m.insert("30m".to_string(), Value::Str("30m".into()));
m.insert("1h".to_string(), Value::Str("1h".into()));
m.insert("2h".to_string(), Value::Str("2h".into()));
m.insert("4h".to_string(), Value::Str("4h".into()));
m.insert("8h".to_string(), Value::Str("8h".into()));
m.insert("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m.insert("3d".to_string(), Value::Str("3d".into()));
m.insert("1w".to_string(), Value::Str("1w".into()));
m.insert("1M".to_string(), Value::Str("1M".into()));
m
}));
m.insert("hostname".to_string(), Value::Str("hyperliquid.xyz".into()));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/550769b3-d270-461e-9e02-8e8b8c0210b8".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://api.{hostname}".into()));
m.insert("private".to_string(), Value::Str("https://api.{hostname}".into()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://api.hyperliquid-testnet.xyz".into()));
m.insert("private".to_string(), Value::Str("https://api.hyperliquid-testnet.xyz".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://hyperliquid.xyz".into()));
m.insert("doc".to_string(), Value::Str("https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api".into()));
m.insert("fees".to_string(), Value::Str("https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees".into()));
m.insert("referral".to_string(), Value::Str("https://app.hyperliquid.xyz/".into()));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m.insert("byType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("l2Book".to_string(), Value::Int(2));
m.insert("allMids".to_string(), Value::Int(2));
m.insert("clearinghouseState".to_string(), Value::Int(2));
m.insert("orderStatus".to_string(), Value::Int(2));
m.insert("spotClearinghouseState".to_string(), Value::Int(2));
m.insert("exchangeStatus".to_string(), Value::Int(2));
m.insert("candleSnapshot".to_string(), Value::Int(4));
m
}));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exchange".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), self.parse_number(Value::Str("0.00045".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.00015".into()), &[]));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), self.parse_number(Value::Str("0.0007".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.0004".into()), &[]));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(false));
m.insert("secret".to_string(), Value::Bool(false));
m.insert("walletAddress".to_string(), Value::Bool(true));
m.insert("privateKey".to_string(), Value::Bool(true));
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Price must be divisible by tick size.".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("Order must have minimum value of $10".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("Insufficient margin to place order.".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("Reduce only order would increase position.".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("Post only order would have immediately matched,".to_string(), Value::Str("InvalidOrder".into()));
m.insert("Order could not immediately match against any resting orders.".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("Invalid TP/SL price.".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("No liquidity available for market order.".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("Order was never placed, already canceled, or filled.".to_string(), Value::Str("OrderNotFound".into()));
m.insert("User or API Wallet ".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("Order has invalid size".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("Order price cannot be more than 80% away from the reference price".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("Order has zero size.".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("Insufficient spot balance asset".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("Insufficient balance for withdrawal".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("Insufficient balance for token transfer".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("TWAP order value too small. Min is $1200, which is $10 per minute.".to_string(), Value::Str("InvalidOrder".into()));
m.insert("TWAP was never placed, already canceled, or filled.".to_string(), Value::Str("OrderNotFound".into()));
m.insert("Too many cumulative requests sent".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m
}));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultType".to_string(), Value::Str("swap".into()));
m.insert("sandboxMode".to_string(), Value::Bool(false));
m.insert("builderFee".to_string(), Value::Bool(true));
m.insert("defaultSlippage".to_string(), Value::Float(0.05));
m.insert("marketHelperProps".to_string(), Value::from(vec![Value::Str("hip3TokensByName".into()), Value::Str("cachedCurrenciesById".into())]));
m.insert("zeroAddress".to_string(), Value::Str("0x0000000000000000000000000000000000000000".into()));
m.insert("spotCurrencyMapping".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("UDZ".to_string(), Value::Str("2Z".into()));
m.insert("UBONK".to_string(), Value::Str("BONK".into()));
m.insert("UBTC".to_string(), Value::Str("BTC".into()));
m.insert("UETH".to_string(), Value::Str("ETH".into()));
m.insert("UFART".to_string(), Value::Str("FARTCOIN".into()));
m.insert("HPENGU".to_string(), Value::Str("PENGU".into()));
m.insert("UPUMP".to_string(), Value::Str("PUMP".into()));
m.insert("USOL".to_string(), Value::Str("SOL".into()));
m.insert("UUUSPX".to_string(), Value::Str("SPX".into()));
m.insert("USDT0".to_string(), Value::Str("USDT".into()));
m.insert("XAUT0".to_string(), Value::Str("XAUT".into()));
m.insert("UXPL".to_string(), Value::Str("XPL".into()));
m
}));
m.insert("fetchMarkets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("types".to_string(), Value::from(vec![Value::Str("spot".into()), Value::Str("swap".into()), Value::Str("hip3".into())]));
m.insert("hip3".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(10));
m.insert("dexes".to_string(), Value::from(vec![]));
m
}));
m
}));
m
}));
m.insert("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("default".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("triggerPrice".to_string(), Value::Bool(false));
m.insert("triggerPriceType".to_string(), Value::Null);
m.insert("triggerDirection".to_string(), Value::Bool(false));
m.insert("stopLossPrice".to_string(), Value::Bool(false));
m.insert("takeProfitPrice".to_string(), Value::Bool(false));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("last".to_string(), Value::Bool(false));
m.insert("mark".to_string(), Value::Bool(false));
m.insert("index".to_string(), Value::Bool(false));
m
}));
m.insert("triggerPrice".to_string(), Value::Bool(true));
m.insert("type".to_string(), Value::Bool(true));
m.insert("price".to_string(), Value::Bool(true));
m
}));
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("IOC".to_string(), Value::Bool(true));
m.insert("FOK".to_string(), Value::Bool(false));
m.insert("PO".to_string(), Value::Bool(true));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("iceberg".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("max".to_string(), Value::Int(1000));
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(2000));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(2000));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(2000));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(2000));
m.insert("daysBack".to_string(), Value::Null);
m.insert("daysBackCanceled".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(5000));
m
}));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m.insert("forPerps".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stopLossPrice".to_string(), Value::Bool(true));
m.insert("takeProfitPrice".to_string(), Value::Bool(true));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Null);
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forPerps".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forPerps".into()));
m
}));
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forPerps".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forPerps".into()));
m
}));
m
}));
m
}));
m.insert("rollingWindowSize".to_string(), Value::Int(0));
m
})]);
Value::Null
}
pub fn set_sandbox_mode(&mut self, mut enabled: Value) {
self.super_set_sandbox_mode(enabled.clone());
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("sandboxMode".into(), enabled); }
}
pub fn nonce(&self) -> Value {
return self.milliseconds();
Value::Null
}
pub fn market(&self, mut symbol: Value) -> Value {
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" market() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" markets not loaded".into()))));
}
if (symbol != Value::Null) && !(in_op(&self.markets, &symbol)) {
let mut symbolParts: Value = split(&symbol, &Value::Str("/".into()));
let mut baseName: Value = self.safe_string(symbolParts.clone(), Value::Int(0), &[]);
let mut spotCurrencyMapping: Value = self.safe_dict_k(self.options.clone(), "spotCurrencyMapping", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (in_op(&spotCurrencyMapping, &baseName)) {
let mut unifiedBaseName: Value = self.safe_string(spotCurrencyMapping.clone(), baseName.clone(), &[]);
let mut quote: Value = self.safe_string(symbolParts, Value::Int(1), &[]);
let mut newSymbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.safe_currency_code(unifiedBaseName, &[]), Value::Str("/".into())).into()), quote).into());
if (in_op(&self.markets, &newSymbol)) {
return get_value(&self.markets, &newSymbol);
}
}
}
return self.super_market(symbol);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchStatus
* @description the latest known information on the availability of the exchange API
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [status structure]{@link https://docs.ccxt.com/?id=exchange-status-structure}
*/
pub async fn fetch_status(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("exchangeStatus".into()));
m
});
let __ws_arg_0 = self.extend(request, &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_0]).await;
//
// {
// "status": "ok"
// }
//
let mut status: Option<String> = self.safe_string_k(response.clone(), "specialStatuses", &[]).as_str().map(str::to_owned);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), (if (status.is_none()) { Value::Str("ok".into()) } else { Value::Str("maintenance".into()) }));
m.insert("updated".to_string(), self.safe_integer_k(response.clone(), "time", &[]));
m.insert("eta".to_string(), Value::Null);
m.insert("url".to_string(), Value::Null);
m.insert("info".to_string(), response);
m
});
Value::Null
}
/*
* @method
* @name hyperliquid#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int} the current integer timestamp in milliseconds from the exchange server
*/
pub async fn fetch_time(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("exchangeStatus".into()));
m
});
let __ws_arg_1 = self.extend(request, &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_1]).await;
return self.safe_integer_k(response, "time", &[]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-metadata
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
pub async fn fetch_currencies(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if self.check_required_credentials(&[Value::Bool(false)]).as_bool() == Some(true) {
self.initialize_client().await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("spotMeta".into()));
m
});
let __ws_arg_2 = self.extend(request, &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_2]).await;
//
// [
// {
// "universe": [
// {
// "maxLeverage": 50,
// "name": "SOL",
// "onlyIsolated": false,
// "szDecimals": 2
// }
// ]
// }
// ]
//
// const spotMeta = await this.publicPostInfo ({ 'type': 'spotMeta' });
let mut tokens: Value = self.safe_list_k(response, "tokens", &[Value::from(vec![])]);
// const meta = this.safeList (response, 'universe', []);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("cachedCurrenciesById".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})); }; // used to map hip3 markets
return self.parse_currencies(tokens);
Value::Null
}
pub fn parse_currency(&self, mut rawCurrency: Value) -> Value {
// const id = i;
let mut id: Value = self.safe_string_k(rawCurrency.clone(), "index", &[]);
let mut name: Value = self.safe_string_k(rawCurrency.clone(), "name", &[]);
let mut code: Value = self.safe_currency_code(name.clone(), &[]);
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("cachedCurrenciesById".into())), &id, name.clone());
let mut result: Value = self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("name".to_string(), name.clone());
m.insert("code".to_string(), code.clone());
m.insert("precision".to_string(), self.parse_precision(&[self.safe_string_k(rawCurrency.clone(), "weiDecimals", &[])]));
m.insert("info".to_string(), rawCurrency.clone());
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), Value::Null);
m.insert("withdraw".to_string(), Value::Null);
m.insert("networks".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("crypto".into()));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m
}));
// add in wrapped map
let mut fullName: Value = self.safe_string_k(rawCurrency, "fullName", &[]);
if (fullName != Value::Null) && (name != Value::Null) {
let mut isWrapped: bool = (starts_with(&fullName, &Value::Str("Unit ".into()))) && (starts_with(&name, &Value::Str("U".into())));
if isWrapped {
let mut parts: Value = split(&name, &Value::Str("U".into()));
let mut nameWithoutU: Value = Value::Str("".into());
{
let mut j: Value = Value::Int(0);
let mut __for_first_793: bool = true;
while { if !__for_first_793 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_793 = false; j.as_f64().unwrap_or(f64::NAN) < ((parts.len() as i64) as f64) } {
nameWithoutU = Value::Str(format!("{}{}", nameWithoutU, parts.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null)).into());
}
}
let mut baseCode: Value = self.safe_currency_code(nameWithoutU, &[]);
if (code != Value::Null) {
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("spotCurrencyMapping".into())), &code, baseCode);
}
}
}
return result;
Value::Null
}
/*
* @method
* @name hyperliquid#fetchMarkets
* @description retrieves data on all markets for hyperliquid
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-spot-asset-contexts
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut options: Value = self.safe_dict_k(self.options.clone(), "fetchMarkets", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut types: Value = self.safe_list_k(options, "types", &[Value::from(vec![])]);
let mut rawPromises: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_794: bool = true;
while { if !__for_first_794 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_794 = false; i.as_f64().unwrap_or(f64::NAN) < ((types.len() as i64) as f64) } {
let mut marketType: Option<String> = self.safe_string(types.clone(), i.clone(), &[]).as_str().map(str::to_owned);
if (marketType.as_deref() == Some("swap")) {
append_to_array(&mut rawPromises, self.fetch_swap_markets(&[params.clone()]).await);
} else if (marketType.as_deref() == Some("spot")) {
append_to_array(&mut rawPromises, self.fetch_spot_markets(&[params.clone()]).await);
} else if (marketType.as_deref() == Some("hip3")) {
append_to_array(&mut rawPromises, self.fetch_hip3_markets(&[params.clone()]).await);
}
}
}
let mut promises: Value = promise_all(&rawPromises).await;
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_795: bool = true;
while { if !__for_first_795 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_795 = false; i.as_f64().unwrap_or(f64::NAN) < ((promises.len() as i64) as f64) } {
result = self.array_concat(result.clone(), promises.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
}
}
return result;
Value::Null
}
/*
* @method
* @name hyperliquid#fetchHip3Markets
* @description retrieves data on all hip3 markets for hyperliquid
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-all-perpetual-dexs
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_hip3_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut fetchDexes: Value = self.public_post_info(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("perpDexs".into()));
m
})]).await;
//
// [
// null,
// {
// "name": "xyz",
// "fullName": "XYZ",
// "deployer": "0x88806a71d74ad0a510b350545c9ae490912f0888",
// "oracleUpdater": "0x1234567890545d1df9ee64b35fdd16966e08acec",
// "feeRecipient": "0x79c0650064b10f73649b7b64c5ebf0b319606140",
// "assetToStreamingOiCap": [
// [
// "xyz:XYZ100",
// "100000000.0"
// ]
// ]
// }
// ]
//
let mut perpDexesOffset: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(1);
let mut __for_first_796: bool = true;
while { if !__for_first_796 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_796 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&fetchDexes).as_f64().unwrap_or(f64::NAN) } {
// builder-deployed perp dexs start at 110000
let mut dex: Value = self.safe_dict(fetchDexes.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut secondPart: Value = (match (&(((match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }))), &(Value::Int(10000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
let mut offset: Value = self.sum(&[Value::Int(110000), secondPart]);
add_element_to_object(&mut perpDexesOffset, &dex.as_map().and_then(|__m| __m.get("name")).cloned().unwrap_or(Value::Null), offset.clone());
}
}
let mut fetchDexesList: Value = Value::from(vec![]);
let mut options: Value = self.safe_dict_k(self.options.clone(), "fetchMarkets", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut hip3: Value = self.safe_dict_k(options.clone(), "hip3", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut dexesProvided: Value = self.safe_list_k(hip3.clone(), "dexes", &[Value::from(vec![])]); // let users provide their own list of dexes to load
let mut maxLimit: Value = self.safe_integer_k(hip3, "limit", &[Value::Int(10)]);
let mut userProvidedDexesLength: f64 = ((dexesProvided.len() as i64) as f64);
if userProvidedDexesLength > ((0i64) as f64) {
if userProvidedDexesLength > ((0i64) as f64) {
fetchDexesList = dexesProvided;
}
} else {
let mut fetchDexesLength: Value = get_array_length(&fetchDexes);
// index 0 is the null main dex, so the loop runs 1..maxLimit to load
// exactly maxLimit dexes. do NOT rewrite this as `i <= maxLimit`: the
// python transpiler collapses every for-loop bound to an exclusive
// range(), so `<=` silently emits range(1, maxLimit) and loads one dex
// too few (build/transpile.ts treats <, <=, > and >= identically)
let mut maxIteration: Value = self.sum(&[maxLimit, Value::Int(1)]);
{
let mut i: Value = Value::Int(1);
let mut __for_first_797: bool = true;
while { if !__for_first_797 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_797 = false; i.as_f64().unwrap_or(f64::NAN) < maxIteration.as_f64().unwrap_or(f64::NAN) } {
if is_greater_than_or_equal(&i, &fetchDexesLength) {
break;
}
let mut dex: Value = self.safe_dict(fetchDexes.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (dex == Value::Null) {
continue;
}
let mut dexName: Value = self.safe_string_k(dex, "name", &[]);
append_to_array(&mut fetchDexesList, dexName.clone());
}
}
}
let mut rawPromises: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_798: bool = true;
while { if !__for_first_798 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_798 = false; i.as_f64().unwrap_or(f64::NAN) < ((fetchDexesList.len() as i64) as f64) } {
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("metaAndAssetCtxs".into()));
m.insert("dex".to_string(), self.safe_string(fetchDexesList.clone(), i.clone(), &[]));
m
});
let __ws_arg_3 = self.extend(request, &[params.clone()]);
append_to_array(&mut rawPromises, self.public_post_info(&[__ws_arg_3]).await);
}
}
let mut promises: Value = promise_all(&rawPromises).await;
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("hip3TokensByName".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})); }
let mut markets: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_800: bool = true;
while { if !__for_first_800 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_800 = false; i.as_f64().unwrap_or(f64::NAN) < ((promises.len() as i64) as f64) } {
let mut dexName: Value = fetchDexesList.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut offset: Value = get_value(&perpDexesOffset, &dexName);
let mut offset: Value = get_value(&perpDexesOffset, &dexName);
let mut response: Value = self.safe_list(promises.clone(), i.clone(), &[]);
let mut meta: Value = self.safe_dict(response.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut collateralToken: Value = self.safe_string_k(meta.clone(), "collateralToken", &[]);
let mut universe: Value = self.safe_list_k(meta, "universe", &[Value::from(vec![])]);
let mut assetCtxs: Value = self.safe_list(response, Value::Int(1), &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_799: bool = true;
while { if !__for_first_799 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_799 = false; j.as_f64().unwrap_or(f64::NAN) < ((universe.len() as i64) as f64) } {
let __ws_arg_4 = self.safe_dict(universe.clone(), j.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let __ws_arg_5 = self.safe_dict(assetCtxs.clone(), j.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.extend(__ws_arg_4, &[__ws_arg_5]);
add_element_to_object(&mut data, &Value::Str("baseId".into()), self.sum(&[j.clone(), offset.clone()]));
add_element_to_object(&mut data, &Value::Str("collateralToken".into()), collateralToken.clone());
add_element_to_object(&mut data, &Value::Str("hip3".into()), Value::Bool(true));
add_element_to_object(&mut data, &Value::Str("dex".into()), dexName.clone());
let mut cachedCurrencies: Value = self.safe_dict_k(self.options.clone(), "cachedCurrenciesById", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
// injecting collateral token name for further usage in parseMarket, already converted from like '0' to 'USDC', etc
if (in_op(&cachedCurrencies, &collateralToken)) {
let mut name: Value = self.safe_string_k(data.clone(), "name", &[]);
let mut collateralTokenCode: Value = self.safe_string(cachedCurrencies.clone(), collateralToken.clone(), &[]);
add_element_to_object(&mut data, &Value::Str("collateralTokenName".into()), collateralTokenCode.clone());
// eg: 'flx:crcl' => {'quote': 'USDC', 'code': 'FLX-CRCL'}
let mut safeCode: Value = self.safe_currency_code(name.clone(), &[]);
let mut hip3Code: Value = (if (safeCode == Value::Null) { name.clone() } else { replace_str(&safeCode, &Value::Str(":".into()), &Value::Str("-".into())) });
add_element_to_object(get_value_mut(&mut self.options, &Value::Str("hip3TokensByName".into())), &name, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("quote".to_string(), collateralTokenCode);
m.insert("code".to_string(), hip3Code);
m
}));
}
append_to_array(&mut result, data);
}
}
markets = self.array_concat(markets.clone(), self.parse_markets(result));
}
}
return markets;
Value::Null
}
/*
* @method
* @name hyperliquid#fetchSwapMarkets
* @description retrieves data on all swap markets for hyperliquid
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_swap_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("metaAndAssetCtxs".into()));
m
});
let __ws_arg_6 = self.extend(request, &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_6]).await;
//
// [
// {
// "universe": [
// {
// "maxLeverage": 50,
// "name": "SOL",
// "onlyIsolated": false,
// "szDecimals": 2
// }
// ]
// },
// [
// {
// "dayNtlVlm": "9450588.2273",
// "funding": "0.0000198",
// "impactPxs": [
// "108.04",
// "108.06"
// ],
// "markPx": "108.04",
// "midPx": "108.05",
// "openInterest": "10764.48",
// "oraclePx": "107.99",
// "premium": "0.00055561",
// "prevDayPx": "111.81"
// }
// ]
// ]
//
//
let mut meta: Value = self.safe_dict(response.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut universe: Value = self.safe_list_k(meta, "universe", &[Value::from(vec![])]);
let mut assetCtxs: Value = self.safe_list(response, Value::Int(1), &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_801: bool = true;
while { if !__for_first_801 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_801 = false; i.as_f64().unwrap_or(f64::NAN) < ((universe.len() as i64) as f64) } {
let __ws_arg_7 = self.safe_dict(universe.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let __ws_arg_8 = self.safe_dict(assetCtxs.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.extend(__ws_arg_7, &[__ws_arg_8]);
add_element_to_object(&mut data, &Value::Str("baseId".into()), i.clone());
append_to_array(&mut result, data);
}
}
return self.parse_markets(result);
Value::Null
}
/*
* @method
* @name hyperliquid#calculatePricePrecision
* @description Helper function to calculate the Hyperliquid Value::Int(crate::runtime::DECIMAL_PLACES) price precision
* @param {float} price the price to use in the calculation
* @param {int} amountPrecision the amountPrecision to use in the calculation
* @param {int} maxDecimals the maxDecimals to use in the calculation
* @returns {int} The calculated price precision
*/
pub fn calculate_price_precision(&self, mut price: Value, mut amountPrecision: Value, mut maxDecimals: Value) -> Value {
let mut pricePrecision: Value = Value::Int(0);
let mut priceStr: Value = self.number_to_string(price);
if (priceStr == Value::Null) {
return Value::Int(0);
}
let mut priceSplitted: Value = split(&priceStr, &Value::Str(".".into()));
if is_true(&crate::precise::Precise::stringEq(&priceStr, &Value::Str("0".into()))) {
// Significant digits is always 5 in this case
let mut significantDigits: Value = Value::Int(5);
// Integer digits is always 0 in this case (0 doesn't count)
let mut integerDigits: Value = Value::Int(0);
// Calculate the price precision
pricePrecision = crate::runtime::Math::min(&(match (&(maxDecimals), &(amountPrecision)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }), &(match (&(significantDigits), &(integerDigits)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }));
} else if is_true(&crate::precise::Precise::stringGt(&priceStr, &Value::Str("0".into()))) && is_true(&crate::precise::Precise::stringLt(&priceStr, &Value::Str("1".into()))) {
// Significant digits, always 5 in this case
let mut significantDigits: Value = Value::Int(5);
// Get the part after the decimal separator
let mut decimalPart: Value = self.safe_string(priceSplitted.clone(), Value::Int(1), &[Value::Str("".into())]);
// Count the number of leading zeros in the decimal part
let mut leadingZeros: Value = Value::Int(0);
while (leadingZeros.as_f64().unwrap_or(f64::NAN) <= ((decimalPart.len() as i64) as f64)) && (get_value(&decimalPart, &leadingZeros).as_str() == Some("0")) {
leadingZeros = (match (&(leadingZeros), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null });
}
// Calculate price precision based on leading zeros and significant digits
pricePrecision = (match (&(leadingZeros), &(significantDigits)) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null });
// Calculate the price precision based on maxDecimals - szDecimals and the calculated price precision from the previous step
pricePrecision = crate::runtime::Math::min(&(match (&(maxDecimals), &(amountPrecision)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }), &pricePrecision);
} else {
// Count the numbers before the decimal separator
let mut integerPart: Value = self.safe_string(priceSplitted, Value::Int(0), &[Value::Str("".into())]);
// Get significant digits, take the max() of 5 and the integer digits count
let mut significantDigits: Value = crate::runtime::Math::max(&Value::Int(5), &Value::Int(integerPart.len() as i64));
// Calculate price precision based on maxDecimals - szDecimals and significantDigits - integerPart.length
pricePrecision = crate::runtime::Math::min(&(match (&(maxDecimals), &(amountPrecision)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }), &(match (&(significantDigits), &(Value::Int(integerPart.len() as i64))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }));
}
return self.parse_to_int(pricePrecision);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchSpotMarkets
* @description retrieves data on all spot markets for hyperliquid
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-spot-asset-contexts
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_spot_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("spotMetaAndAssetCtxs".into()));
m
});
let __ws_arg_9 = self.extend(request, &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_9]).await;
//
// [
// {
// "tokens": [
// {
// "name": "USDC",
// "szDecimals": 8,
// "weiDecimals" 8,
// "index": 0,
// "tokenId": "0x6d1e7cde53ba9467b783cb7c530ce054",
// "isCanonical": true,
// "evmContract":null,
// "fullName":null
// },
// {
// "name": "PURR",
// "szDecimals": 0,
// "weiDecimals": 5,
// "index": 1,
// "tokenId": "0xc1fb593aeffbeb02f85e0308e9956a90",
// "isCanonical": true,
// "evmContract":null,
// "fullName":null
// }
// ],
// "universe": [
// {
// "name": "PURR/USDC",
// "tokens": [1, 0],
// "index": 0,
// "isCanonical": true
// }
// ]
// },
// [
// {
// "dayNtlVlm":"8906.0",
// "markPx":"0.14",
// "midPx":"0.209265",
// "prevDayPx":"0.20432"
// }
// ]
// ]
//
let mut first: Value = self.safe_dict(response.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut second: Value = self.safe_list(response, Value::Int(1), &[Value::from(vec![])]);
let mut meta: Value = self.safe_list_k(first.clone(), "universe", &[Value::from(vec![])]);
let mut tokens: Value = self.safe_list_k(first, "tokens", &[Value::from(vec![])]);
let mut markets: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_802: bool = true;
while { if !__for_first_802 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_802 = false; i.as_f64().unwrap_or(f64::NAN) < ((meta.len() as i64) as f64) } {
let mut market: Value = self.safe_dict(meta.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut index: Value = self.safe_integer_k(market.clone(), "index", &[]);
let mut extraData: Value = self.safe_dict(second.clone(), index.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketName: Value = self.safe_string_k(market.clone(), "name", &[]);
// if (marketName.indexOf ('/') < 0) {
// // there are some weird spot markets in testnet, eg @2
// continue;
// }
// const marketParts = marketName.split ('/');
// const baseName = this.safeString (marketParts, 0);
// const quoteId = this.safeString (marketParts, 1);
let mut fees: Value = self.safe_dict_k(self.fees.clone(), "spot", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut taker: Value = self.safe_number_k(fees.clone(), "taker", &[]);
let mut maker: Value = self.safe_number_k(fees, "maker", &[]);
let mut tokensPos: Value = self.safe_list_k(market.clone(), "tokens", &[Value::from(vec![])]);
let mut baseTokenPos: Value = self.safe_integer(tokensPos.clone(), Value::Int(0), &[]);
let mut quoteTokenPos: Value = self.safe_integer(tokensPos, Value::Int(1), &[]);
let mut baseTokenInfo: Value = self.safe_dict(tokens.clone(), baseTokenPos, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut quoteTokenInfo: Value = self.safe_dict(tokens.clone(), quoteTokenPos, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut baseName: Value = self.safe_string_k(baseTokenInfo.clone(), "name", &[]);
let mut quoteId: Value = self.safe_string_k(quoteTokenInfo, "name", &[]);
if (baseName == Value::Null) || (quoteId == Value::Null) {
continue;
}
// do spot currency mapping
let mut spotCurrencyMapping: Value = self.safe_dict_k(self.options.clone(), "spotCurrencyMapping", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut mappedBaseName: Value = self.safe_string(spotCurrencyMapping.clone(), baseName.clone(), &[baseName.clone()]);
let mut mappedQuoteId: Value = self.safe_string(spotCurrencyMapping, quoteId.clone(), &[quoteId.clone()]);
let mut mappedBase: Value = self.safe_currency_code(mappedBaseName, &[]);
let mut mappedQuote: Value = self.safe_currency_code(mappedQuoteId, &[]);
let mut mappedSymbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", mappedBase, Value::Str("/".into())).into()), mappedQuote).into());
let mut innerBaseTokenInfo: Value = self.safe_dict_k(baseTokenInfo.clone(), "spec", &[baseTokenInfo.clone()]);
// const innerQuoteTokenInfo = this.safeDict (quoteTokenInfo, 'spec', quoteTokenInfo);
let mut amountPrecisionStr: Value = self.safe_string_k(innerBaseTokenInfo, "szDecimals", &[]);
let mut amountPrecision: Value = (match &amountPrecisionStr { Value::Str(__parse_s) => __parse_s.trim().parse::<i64>().map(Value::Int).unwrap_or(Value::Null), Value::Int(__parse_n) => Value::Int(*__parse_n), Value::Float(__parse_f) => Value::Int(*__parse_f as i64), _ => Value::Null });
let mut price: Value = self.safe_number_k(extraData.clone(), "midPx", &[]);
let mut pricePrecision: Value = Value::Int(0);
if (price != Value::Null) {
pricePrecision = self.calculate_price_precision(price, amountPrecision, Value::Int(8));
}
let mut pricePrecisionStr: Value = self.number_to_string(pricePrecision);
// const quotePrecision = this.parseNumber (this.parsePrecision (this.safeString (innerQuoteTokenInfo, 'szDecimals')));
let mut baseId: Value = self.number_to_string((match (&(index), &(Value::Int(10000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }));
let mut entry: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketName);
m.insert("symbol".to_string(), mappedSymbol);
m.insert("base".to_string(), mappedBase);
m.insert("quote".to_string(), mappedQuote);
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId);
m.insert("baseName".to_string(), baseName);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("spot".into()));
m.insert("spot".to_string(), Value::Bool(true));
m.insert("subType".to_string(), Value::Null);
m.insert("margin".to_string(), Value::Null);
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Bool(true));
m.insert("contract".to_string(), Value::Bool(false));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("taker".to_string(), taker);
m.insert("maker".to_string(), maker);
m.insert("contractSize".to_string(), Value::Null);
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.parse_number(self.parse_precision(&[amountPrecisionStr]), &[]));
m.insert("price".to_string(), self.parse_number(self.parse_precision(&[pricePrecisionStr]), &[]));
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.parse_number(Value::Str("10".into()), &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), self.extend(extraData, &[market]));
m
});
append_to_array(&mut markets, self.safe_market_structure(&[entry]));
}
}
return markets;
Value::Null
}
pub fn parse_market(&self, mut market: Value) -> Value {
//
// {
// "maxLeverage": "50",
// "name": "ETH",
// "onlyIsolated": false,
// "szDecimals": "4",
// "dayNtlVlm": "1709813.11535",
// "funding": "0.00004807",
// "impactPxs": [
// "2369.3",
// "2369.6"
// ],
// "markPx": "2369.6",
// "midPx": "2369.45",
// "openInterest": "1815.4712",
// "oraclePx": "2367.3",
// "premium": "0.00090821",
// "prevDayPx": "2381.5"
// "collateralToken": "0" hip3 tokens only
// }
//
let mut collateralTokenCode: Value = self.safe_string_k(market.clone(), "collateralTokenName", &[]);
let mut quoteId: Value = collateralTokenCode.clone();
if (collateralTokenCode == Value::Null) {
quoteId = Value::Str("USDC".into());
}
let mut settleId: Value = collateralTokenCode.clone();
if (collateralTokenCode == Value::Null) {
settleId = Value::Str("USDC".into());
}
let mut baseName: Value = self.safe_string_k(market.clone(), "name", &[]);
let mut base: Value = self.safe_currency_code(baseName.clone(), &[]);
if (base == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" parseMarket() missing base currency".into()))));
}
base = replace_str(&base, &Value::Str(":".into()), &Value::Str("-".into())); // handle hip3 tokens and converts from like flx:crcl to FLX-CRCL
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
if (quote == Value::Null) {
return Value::Null;
}
let mut baseId: Value = self.safe_string_k(market.clone(), "baseId", &[]);
let mut settle: Value = self.safe_currency_code(settleId.clone(), &[]);
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
let mut contract: Value = Value::Bool(true);
let mut swap: Value = Value::Bool(true);
if matches!(&contract, Value::Bool(true)) {
if matches!(&swap, Value::Bool(true)) {
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbol, Value::Str(":".into())).into()), settle).into());
}
}
let mut fees: Value = self.safe_dict_k(self.fees.clone(), "swap", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut taker: Value = self.safe_number_k(fees.clone(), "taker", &[]);
let mut maker: Value = self.safe_number_k(fees, "maker", &[]);
let mut amountPrecisionStr: Value = self.safe_string_k(market.clone(), "szDecimals", &[]);
let mut amountPrecision: Value = (match &amountPrecisionStr { Value::Str(__parse_s) => __parse_s.trim().parse::<i64>().map(Value::Int).unwrap_or(Value::Null), Value::Int(__parse_n) => Value::Int(*__parse_n), Value::Float(__parse_f) => Value::Int(*__parse_f as i64), _ => Value::Null });
let mut price: Value = self.safe_number_k(market.clone(), "markPx", &[Value::Int(0)]);
let mut pricePrecision: Value = Value::Int(0);
if (price != Value::Null) {
pricePrecision = self.calculate_price_precision(price, amountPrecision, Value::Int(6));
}
let mut pricePrecisionStr: Value = self.number_to_string(pricePrecision);
let mut isDelisted: Value = self.safe_bool_k(market.clone(), "isDelisted", &[]);
let mut active: Value = Value::Bool(true);
if (isDelisted != Value::Null) {
active = Value::Bool(!(isDelisted.as_bool() == Some(true)));
}
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), baseId.clone());
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), settle);
m.insert("baseId".to_string(), baseId);
m.insert("baseName".to_string(), baseName);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), settleId);
m.insert("type".to_string(), Value::Str("swap".into()));
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Null);
m.insert("swap".to_string(), swap);
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), active);
m.insert("contract".to_string(), contract);
m.insert("linear".to_string(), Value::Bool(true));
m.insert("inverse".to_string(), Value::Bool(false));
m.insert("taker".to_string(), taker);
m.insert("maker".to_string(), maker);
m.insert("contractSize".to_string(), self.parse_number(Value::Str("1".into()), &[]));
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.parse_number(self.parse_precision(&[amountPrecisionStr]), &[]));
m.insert("price".to_string(), self.parse_number(self.parse_precision(&[pricePrecisionStr]), &[]));
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), self.safe_integer_k(market.clone(), "maxLeverage", &[]));
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.parse_number(Value::Str("10".into()), &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), market);
m
})]);
Value::Null
}
pub fn update_spot_currency_code(&self, mut code: Value) -> Value {
if (code == Value::Null) {
return code;
}
let mut spotCurrencyMapping: Value = self.safe_dict_k(self.options.clone(), "spotCurrencyMapping", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_string(spotCurrencyMapping, code.clone(), &[code.clone()]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-a-users-token-balances
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-users-perpetuals-account-summary
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] user address, will default to this.walletAddress if not provided
* @param {string} [params.type] wallet type, ['spot', 'swap'], defaults to swap
* @param {string} [params.marginMode] 'cross' or 'isolated', for margin trading, uses this.options.defaultMarginMode if not passed, defaults to undefined/None/null
* @param {string} [params.dex] for hip3 markets, the dex name, eg: 'xyz'
* @param {string} [params.subAccountAddress] sub account user address
* @param {boolean} [params.enableUnifiedMargin] enable unified margin, CCXT tries to auto-detects this value but you can override it
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// if user provides a different address in params and does not provide the enableUnifiedMargin we assume we need to request the info again
let mut shouldRefresh: Value = Value::Bool((self.safe_string2(params.clone(), Value::Str("user".into()), Value::Str("address".into()), &[]) != Value::Null) && (self.safe_bool_k(params.clone(), "enableUnifiedMargin", &[]) == Value::Null));
let mut userAddressparamsPublicAddressVariable = self.handle_public_address(Value::Str("fetchBalance".into()), params);
let mut userAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPublicAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchBalance".into()), &[Value::Null, paramsPublicAddress]);
let mut type_var: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut marginModeparamsMarginModeVariable = self.handle_margin_mode_and_params(Value::Str("fetchBalance".into()), &[paramsMarketType]);
let mut marginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut isUnifiedEnabledparamsValueVariable = self.is_unified_enabled(Value::Str("fetchBalance".into()), &[userAddress.clone(), shouldRefresh, paramsMarginMode]).await;
let mut isUnifiedEnabled: Value = isUnifiedEnabledparamsValueVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsValue: Value = isUnifiedEnabledparamsValueVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut dex: Option<String> = self.safe_string_k(paramsValue.clone(), "dex", &[]).as_str().map(str::to_owned);
let mut isSpot: bool = ((type_var.as_str() == Some("spot")) || (isUnifiedEnabled.as_bool() == Some(true))) && (dex.is_none());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), (if (isSpot) { Value::Str("spotClearinghouseState".into()) } else { Value::Str("clearinghouseState".into()) }));
m.insert("user".to_string(), userAddress);
m
});
let __ws_arg_10 = self.extend(request, &[paramsValue]);
let mut response: Value = self.public_post_info(&[__ws_arg_10]).await;
//
// {
// "assetPositions": [],
// "crossMaintenanceMarginUsed": "0.0",
// "crossMarginSummary": {
// "accountValue": "100.0",
// "totalMarginUsed": "0.0",
// "totalNtlPos": "0.0",
// "totalRawUsd": "100.0"
// },
// "marginSummary": {
// "accountValue": "100.0",
// "totalMarginUsed": "0.0",
// "totalNtlPos": "0.0",
// "totalRawUsd": "100.0"
// },
// "time": "1704261007014",
// "withdrawable": "100.0"
// }
// spot
//
// {
// "balances":[
// {
// "coin":"USDC",
// "hold":"0.0",
// "total":"1481.844"
// },
// {
// "coin":"PURR",
// "hold":"0.0",
// "total":"999.65004"
// }
// }
//
let mut balances: Value = self.safe_list_k(response.clone(), "balances", &[]);
if (balances != Value::Null) {
let mut spotBalances: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_803: bool = true;
while { if !__for_first_803 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_803 = false; i.as_f64().unwrap_or(f64::NAN) < ((balances.len() as i64) as f64) } {
let mut balance: Value = self.safe_dict(balances.clone(), i.clone(), &[]);
let mut unifiedCode: Value = self.safe_currency_code(self.safe_string_k(balance.clone(), "coin", &[]), &[]);
let mut code: Value = (if (isSpot) { self.update_spot_currency_code(unifiedCode.clone()) } else { unifiedCode });
let mut account: Value = self.account();
let mut total: Value = self.safe_string_k(balance.clone(), "total", &[]);
let mut used: Value = self.safe_string_k(balance, "hold", &[]);
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), total); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), used); }
if (code != Value::Null) {
if let Value::Dict(__d) = &mut spotBalances { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
}
}
return self.safe_balance(spotBalances);
}
let mut data: Value = self.safe_dict_k(response.clone(), "marginSummary", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut usdcBalance: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("total".to_string(), self.safe_number_k(data.clone(), "accountValue", &[]));
m
});
if (marginMode != Value::Null) && (marginMode.as_str() == Some("isolated")) {
if let Value::Dict(__d) = &mut usdcBalance { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_number_k(response.clone(), "withdrawable", &[])); }
} else {
if let Value::Dict(__d) = &mut usdcBalance { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_number_k(data, "totalMarginUsed", &[])); }
}
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m.insert("USDC".to_string(), usdcBalance);
m
});
let mut timestamp: Value = self.safe_integer_k(response, "time", &[]);
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("timestamp".into(), timestamp.clone()); }
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("datetime".into(), self.iso8601(timestamp)); }
return self.safe_balance(result);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#l2-book-snapshot
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn fetch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("l2Book".into()));
m.insert("coin".to_string(), (if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { self.safe_string_k(market.clone(), "baseName", &[]) } else { market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null) }));
m
});
let __ws_arg_11 = self.extend(request, &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_11]).await;
//
// {
// "coin": "ETH",
// "levels": [
// [
// {
// "n": "2",
// "px": "2216.2",
// "sz": "74.0637"
// }
// ],
// [
// {
// "n": "2",
// "px": "2216.5",
// "sz": "70.5893"
// }
// ]
// ],
// "time": "1704290104840"
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "levels", &[Value::from(vec![])]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("bids".to_string(), self.safe_list(data.clone(), Value::Int(0), &[Value::from(vec![])]));
m.insert("asks".to_string(), self.safe_list(data, Value::Int(1), &[Value::from(vec![])]));
m
});
let mut timestamp: Value = self.safe_integer_k(response, "time", &[]);
return self.parse_order_book(result, market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[timestamp, Value::Str("bids".into()), Value::Str("asks".into()), Value::Str("px".into()), Value::Str("sz".into())]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-spot-asset-contexts
* @param {string[]} [symbols] unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] 'spot' or 'swap', by default fetches both
* @param {boolean} [params.hip3] set to true to fetch hip3 markets only
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
// at this stage, to get tickers data, we use fetchMarkets endpoints
let mut response: Value = Value::from(vec![]);
let mut type_var: Option<String> = self.safe_string_k(params.clone(), "type", &[]).as_str().map(str::to_owned);
let mut paramsOmitted: Value = self.omit(params, Value::Str("type".into()), &[]);
let mut hip3OptionparamsHip3Variable = self.handle_option_bool_and_params(paramsOmitted, Value::Str("fetchTickers".into()), Value::Str("hip3".into()), &[Value::Bool(false)]);
let mut hip3Option: Value = hip3OptionparamsHip3Variable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsHip3: Value = hip3OptionparamsHip3Variable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut hip3: Value = hip3Option;
if (symbolsNormalized != Value::Null) {
// infer from first symbol
let mut firstSymbol: Value = self.safe_string(symbolsNormalized.clone(), Value::Int(0), &[]);
if (firstSymbol != Value::Null) {
let mut market: Value = self.market(firstSymbol);
if matches!(self.safe_bool(self.safe_dict_k(market.clone(), "info", &[]), Value::Str("hip3".into()), &[Value::Bool(false)]), Value::Bool(true)) {
hip3 = Value::Bool(true);
}
}
}
if is_true(&hip3) {
response = self.fetch_hip3_markets(&[self.omit(paramsHip3.clone(), Value::Str("hip3".into()), &[])]).await;
} else if (type_var.as_deref() == Some("spot")) {
response = self.fetch_spot_markets(&[paramsHip3.clone()]).await;
} else if (type_var.as_deref() == Some("swap")) {
response = self.fetch_swap_markets(&[paramsHip3.clone()]).await;
} else {
response = self.fetch_markets(&[paramsHip3]).await;
}
// same response as under "fetchMarkets"
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_804: bool = true;
while { if !__for_first_804 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_804 = false; i.as_f64().unwrap_or(f64::NAN) < ((response.len() as i64) as f64) } {
let mut market: Value = response.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut info: Value = crate::value::get_value_k(&market, "info");
let mut ticker: Value = self.parse_ticker(info, &[market]);
let mut symbol: Value = self.safe_string_k(ticker.clone(), "symbol", &[]);
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker); }
}
}
return self.filter_by_array_tickers(result, Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchFundingRate
* @description fetch the current funding rate for a symbol - hyperliquid only offers a bulk endpoint, so this filters the result of fetchFundingRates
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/#/?id=funding-rate-structure}
*/
pub async fn fetch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol.clone());
let mut rates: Value = self.fetch_funding_rates(&[Value::from(vec![market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)]), params]).await;
let mut rate: Value = self.safe_dict(rates, market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[]);
if (rate == Value::Null) {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRate() could not find a funding rate for ".into())).into()), symbol)));
}
return rate;
Value::Null
}
/*
* @method
* @name hyperliquid#fetchFundingRates
* @description retrieves data on all swap markets for hyperliquid
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_funding_rates(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("metaAndAssetCtxs".into()));
m
});
let __ws_arg_12 = self.extend(request, &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_12]).await;
//
// [
// {
// "universe": [
// {
// "maxLeverage": 50,
// "name": "SOL",
// "onlyIsolated": false,
// "szDecimals": 2
// }
// ]
// },
// [
// {
// "dayNtlVlm": "9450588.2273",
// "funding": "0.0000198",
// "impactPxs": [
// "108.04",
// "108.06"
// ],
// "markPx": "108.04",
// "midPx": "108.05",
// "openInterest": "10764.48",
// "oraclePx": "107.99",
// "premium": "0.00055561",
// "prevDayPx": "111.81"
// }
// ]
// ]
//
//
let mut meta: Value = self.safe_dict(response.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut universe: Value = self.safe_list_k(meta, "universe", &[Value::from(vec![])]);
let mut assetCtxs: Value = self.safe_list(response, Value::Int(1), &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_805: bool = true;
while { if !__for_first_805 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_805 = false; i.as_f64().unwrap_or(f64::NAN) < ((universe.len() as i64) as f64) } {
let __ws_arg_13 = self.safe_dict(universe.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let __ws_arg_14 = self.safe_dict(assetCtxs.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.extend(__ws_arg_13, &[__ws_arg_14]);
append_to_array(&mut result, data);
}
}
return self.parse_funding_rates(result, &[symbols]);
Value::Null
}
pub fn parse_funding_rate(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "maxLeverage": "50",
// "name": "ETH",
// "onlyIsolated": false,
// "szDecimals": "4",
// "dayNtlVlm": "1709813.11535",
// "funding": "0.00004807",
// "impactPxs": [
// "2369.3",
// "2369.6"
// ],
// "markPx": "2369.6",
// "midPx": "2369.45",
// "openInterest": "1815.4712",
// "oraclePx": "2367.3",
// "premium": "0.00090821",
// "prevDayPx": "2381.5"
// }
//
let mut base: Value = self.safe_string_k(info.clone(), "name", &[]);
let mut marketId: Value = self.coin_to_market_id(base).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut symbol: Value = self.safe_symbol(marketId, &[market]);
let mut funding: Value = self.safe_number_k(info.clone(), "funding", &[]);
let mut markPx: Value = self.safe_number_k(info.clone(), "markPx", &[]);
let mut oraclePx: Value = self.safe_number_k(info.clone(), "oraclePx", &[]);
let mut fundingTimestamp: Value = (match (&((match (&((match (&(((match (&(math_floor(&(match (((match (((match ((self.milliseconds()).as_f64(), (Value::Int(60)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64(), (Value::Int(60)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }))), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }))), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), info);
m.insert("symbol".to_string(), symbol);
m.insert("markPrice".to_string(), markPx);
m.insert("indexPrice".to_string(), oraclePx);
m.insert("interestRate".to_string(), Value::Null);
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("fundingRate".to_string(), funding);
m.insert("fundingTimestamp".to_string(), fundingTimestamp.clone());
m.insert("fundingDatetime".to_string(), self.iso8601(fundingTimestamp));
m.insert("nextFundingRate".to_string(), Value::Null);
m.insert("nextFundingTimestamp".to_string(), Value::Null);
m.insert("nextFundingDatetime".to_string(), Value::Null);
m.insert("previousFundingRate".to_string(), Value::Null);
m.insert("previousFundingTimestamp".to_string(), Value::Null);
m.insert("previousFundingDatetime".to_string(), Value::Null);
m.insert("interval".to_string(), Value::Str("1h".into()));
m
});
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "prevDayPx": "3400.5",
// "dayNtlVlm": "511297257.47936022",
// "markPx": "3464.7",
// "midPx": "3465.05",
// "oraclePx": "3460.1", // only in swap
// "openInterest": "64638.1108", // only in swap
// "premium": "0.00141614", // only in swap
// "funding": "0.00008727", // only in swap
// "impactPxs": [ "3465.0", "3465.1" ], // only in swap
// "coin": "PURR", // only in spot
// "circulatingSupply": "998949190.03400207", // only in spot
// },
//
let mut name: Value = self.safe_string_k(ticker.clone(), "name", &[]);
let mut marketId: Value = self.coin_to_market_id(name).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut bidAsk: Value = self.safe_list_k(ticker.clone(), "impactPxs", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("previousClose".to_string(), self.safe_number_k(ticker.clone(), "prevDayPx", &[]));
m.insert("close".to_string(), self.safe_number_k(ticker.clone(), "midPx", &[]));
m.insert("last".to_string(), self.safe_number_k(ticker.clone(), "price", &[]));
m.insert("bid".to_string(), self.safe_number(bidAsk.clone(), Value::Int(0), &[]));
m.insert("ask".to_string(), self.safe_number(bidAsk, Value::Int(1), &[]));
m.insert("quoteVolume".to_string(), self.safe_number_k(ticker.clone(), "dayNtlVlm", &[]));
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#candle-snapshot
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents, support '1m', '15m', '1h', '1d'
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest candle to fetch
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[self.milliseconds()]);
let mut useTail: Value = Value::Bool(since == Value::Null);
let mut originalSince: Value = since.clone();
let mut startTime: Value = since.clone();
if (since == Value::Null) {
if (limit != Value::Null) {
// optimization if limit is provided
let mut timeframeInMilliseconds: Value = (match (&(self.parse_timeframe(timeframe.clone())), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
startTime = self.sum(&[until.clone(), (match (&((match (&(timeframeInMilliseconds), &(limit)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(-1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })]);
if startTime.as_f64().unwrap_or(f64::NAN) < ((0i64) as f64) {
startTime = Value::Int(0);
}
useTail = Value::Bool(false);
} else {
startTime = Value::Int(0);
}
}
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("until".into())]), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("candleSnapshot".into()));
m.insert("req".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("coin".to_string(), (if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { self.safe_string_k(market.clone(), "baseName", &[]) } else { market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null) }));
m.insert("interval".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m.insert("startTime".to_string(), startTime);
m.insert("endTime".to_string(), until);
m
}));
m
});
let __ws_arg_15 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.public_post_info(&[__ws_arg_15]).await;
//
// [
// {
// "T": 1704287699999,
// "c": "2226.4",
// "h": "2247.9",
// "i": "15m",
// "l": "2224.6",
// "n": 46,
// "o": "2247.9",
// "s": "ETH",
// "t": 1704286800000,
// "v": "591.6427"
// }
// ]
//
let mut candles: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
candles = response.clone();
}
return self.parse_ohlc_vs(candles, &[market, timeframe, originalSince, limit, useTail]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::from(vec![self.safe_integer_k(ohlcv.clone(), "t", &[]), self.safe_number_k(ohlcv.clone(), "o", &[]), self.safe_number_k(ohlcv.clone(), "h", &[]), self.safe_number_k(ohlcv.clone(), "l", &[]), self.safe_number_k(ohlcv.clone(), "c", &[]), self.safe_number_k(ohlcv, "v", &[])]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills-by-time
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest trade
* @param {string} [params.address] wallet address that made trades
* @param {string} [params.user] wallet address that made trades
* @param {string} [params.subAccountAddress] sub account user address
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddressparamsPublicAddressVariable = self.handle_public_address(Value::Str("fetchTrades".into()), params);
let mut userAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPublicAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("user".to_string(), userAddress);
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("userFillsByTime".into())); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("userFills".into())); }
}
let mut until: Value = self.safe_integer_k(paramsPublicAddress.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(paramsPublicAddress, Value::Str("until".into()), &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
}
let __ws_arg_16 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.public_post_info(&[__ws_arg_16]).await;
//
// [
// {
// "closedPnl": "0.19343",
// "coin": "ETH",
// "crossed": true,
// "dir": "Close Long",
// "fee": "0.050062",
// "hash": "0x09d77c96791e98b5775a04092584ab010d009445119c71e4005c0d634ea322bc",
// "liquidationMarkPx": null,
// "oid": 3929354691,
// "px": "2381.1",
// "side": "A",
// "startPosition": "0.0841",
// "sz": "0.0841",
// "tid": 128423918764978,
// "time": 1704262888911
// }
// ]
//
let mut fills: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
fills = response.clone();
}
return self.parse_trades(fills, &[market, since, limit]);
Value::Null
}
pub fn amount_to_precision(&self, mut symbol: Value, mut amount: Value) -> Value {
let mut market: Value = self.market(symbol);
let mut result: Value = self.decimal_to_precision(amount.clone(), Value::Int(crate::runtime::ROUND), market.as_map().and_then(|__m| __m.get("precision")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("amount")).cloned().unwrap_or(Value::Null), &[self.precisionMode.clone(), self.paddingMode.clone()]);
// a size of zero is meaningful to hyperliquid, a whole position tp/sl order is sent
// with grouping positionTpsl and size 0, so only reject a positive amount that
// became zero after rounding, never an explicitly requested zero
if is_true(&crate::precise::Precise::stringEq(&result, &Value::Str("0".into()))) && is_true(&crate::precise::Precise::stringGt(&self.number_to_string(amount), &Value::Str("0".into()))) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" amount of ".into())).into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into()), Value::Str(" must be greater than minimum amount precision of ".into())).into()), self.number_to_string(market.as_map().and_then(|__m| __m.get("precision")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("amount")).cloned().unwrap_or(Value::Null)))));
}
return result;
Value::Null
}
pub fn price_to_precision(&self, mut symbol: Value, mut price: Value) -> Value {
let mut market: Value = self.market(symbol);
let mut priceStr: Value = self.number_to_string(price.clone());
let mut integerPart: Value = split(&priceStr, &Value::Str(".".into())).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut significantDigits: Value = crate::runtime::Math::max(&Value::Int(5), &Value::Int(integerPart.len() as i64));
let mut result: Value = self.decimal_to_precision(price, Value::Int(crate::runtime::ROUND), significantDigits, &[Value::Int(crate::runtime::SIGNIFICANT_DIGITS), self.paddingMode.clone()]);
let mut maxDecimals: Value = (if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { Value::Int(8) } else { Value::Int(6) });
let mut subtractedValue: Value = (match (&(maxDecimals), &(self.precision_from_string(self.safe_string(market.as_map().and_then(|__m| __m.get("precision")).cloned().unwrap_or(Value::Null), Value::Str("amount".into()), &[])))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
return self.decimal_to_precision(result, Value::Int(crate::runtime::ROUND), subtractedValue, &[Value::Int(crate::runtime::DECIMAL_PLACES), self.paddingMode.clone()]);
Value::Null
}
pub fn hash_message(&self, mut message: Value) -> Value {
return Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(message, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into());
Value::Null
}
pub fn sign_hash(&self, mut hash: Value, mut privateKey: Value) -> Value {
let mut signature: Value = ecdsa(hash.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null), privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null), Value::Str("secp256k1".into()), Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("r".to_string(), Value::Str(format!("{}{}", Value::Str("0x".into()), signature.as_map().and_then(|__m| __m.get("r")).cloned().unwrap_or(Value::Null)).into()));
m.insert("s".to_string(), Value::Str(format!("{}{}", Value::Str("0x".into()), signature.as_map().and_then(|__m| __m.get("s")).cloned().unwrap_or(Value::Null)).into()));
m.insert("v".to_string(), self.sum(&[Value::Int(27), signature.as_map().and_then(|__m| __m.get("v")).cloned().unwrap_or(Value::Null)]));
m
});
Value::Null
}
pub fn sign_message(&self, mut message: Value, mut privateKey: Value) -> Value {
return self.sign_hash(self.hash_message(message), privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
Value::Null
}
pub fn construct_phantom_agent(&self, mut hash: Value, optional_args: &[Value]) -> Value {
let mut isTestnet = get_arg(optional_args, 0, Value::Bool(true));
let mut source: Value = (if is_true(&(isTestnet)) { Value::Str("b".into()) } else { Value::Str("a".into()) });
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("source".to_string(), source);
m.insert("connectionId".to_string(), hash);
m
});
Value::Null
}
pub fn action_hash(&self, mut action: Value, mut vaultAddress: Value, mut nonce: Value, optional_args: &[Value]) -> Value {
let mut expiresAfter = get_arg(optional_args, 0, Value::Null);
let mut dataBinary: Value = self.packb(action, &[]);
let mut dataHex: Value = self.binary_to_base16(dataBinary, &[]);
let mut data: Value = dataHex;
data = Value::Str(format!("{}{}", data, Value::Str(format!("{}{}", Value::Str("00000".into()), self.int_to_base16(nonce, &[])).into())).into());
if (vaultAddress == Value::Null) {
data = Value::Str(format!("{}{}", data, Value::Str("00".into())).into());
} else {
data = Value::Str(format!("{}{}", data, Value::Str("01".into())).into());
data = add(&data, &vaultAddress);
}
if (expiresAfter != Value::Null) {
data = Value::Str(format!("{}{}", data, Value::Str("00".into())).into());
data = Value::Str(format!("{}{}", data, Value::Str(format!("{}{}", Value::Str("00000".into()), self.int_to_base16(expiresAfter, &[])).into())).into());
}
return self.hash(self.base16_to_binary(data, &[]), Value::Str("keccak".into()), &[Value::Str("binary".into())]);
Value::Null
}
pub fn sign_l1_action(&self, mut action: Value, mut nonce: Value, optional_args: &[Value]) -> Value {
let mut vaultAdress = get_arg(optional_args, 0, Value::Null);
let mut expiresAfter = get_arg(optional_args, 1, Value::Null);
let mut hash: Value = self.action_hash(action, vaultAdress, nonce, &[expiresAfter]);
let mut isTestnet: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut phantomAgent: Value = self.construct_phantom_agent(hash, &[isTestnet]);
// const data: Dict = {
// 'domain': {
// 'chainId': 1337,
// 'name': 'Exchange',
// 'verifyingContract': '0x0000000000000000000000000000000000000000',
// 'version': '1',
// },
// 'types': {
// 'Agent': [
// { 'name': 'source', 'type': 'string' },
// { 'name': 'connectionId', 'type': 'bytes32' },
// ],
// 'EIP712Domain': [
// { 'name': 'name', 'type': 'string' },
// { 'name': 'version', 'type': 'string' },
// { 'name': 'chainId', 'type': 'uint256' },
// { 'name': 'verifyingContract', 'type': 'address' },
// ],
// },
// 'primaryType': 'Agent',
// 'message': phantomAgent,
// }
let mut zeroAddress: Value = self.safe_string_k(self.options.clone(), "zeroAddress", &[]);
let mut chainId: Value = Value::Int(1337); // check this out
let mut domain: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("chainId".to_string(), chainId);
m.insert("name".to_string(), Value::Str("Exchange".into()));
m.insert("verifyingContract".to_string(), zeroAddress);
m.insert("version".to_string(), Value::Str("1".into()));
m
});
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Agent".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("source".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("connectionId".into()));
m.insert("type".to_string(), Value::Str("bytes32".into()));
m
})]));
m
});
let mut msg: Value = self.eth_encode_structured_data(domain, messageTypes, phantomAgent);
let mut signature: Value = self.sign_message(msg, self.privateKey.clone());
return signature;
Value::Null
}
pub fn sign_user_signed_action(&self, mut messageTypes: Value, mut message: Value) -> Value {
let mut zeroAddress: Value = self.safe_string_k(self.options.clone(), "zeroAddress", &[]);
let mut chainId: Value = Value::Int(421614); // check this out
let mut domain: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("chainId".to_string(), chainId);
m.insert("name".to_string(), Value::Str("HyperliquidSignTransaction".into()));
m.insert("verifyingContract".to_string(), zeroAddress);
m.insert("version".to_string(), Value::Str("1".into()));
m
});
let mut msg: Value = self.eth_encode_structured_data(domain, messageTypes, message);
let mut signature: Value = self.sign_message(msg, self.privateKey.clone());
return signature;
Value::Null
}
pub fn build_usd_send_sig(&self, mut message: Value) -> Value {
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:UsdSend".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("destination".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("amount".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("time".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(messageTypes, message);
Value::Null
}
pub fn build_usd_class_send_sig(&self, mut message: Value) -> Value {
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:UsdClassTransfer".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("amount".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("toPerp".into()));
m.insert("type".to_string(), Value::Str("bool".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(messageTypes, message);
Value::Null
}
pub fn build_withdraw_sig(&self, mut message: Value) -> Value {
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:Withdraw".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("destination".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("amount".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("time".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(messageTypes, message);
Value::Null
}
pub fn build_user_dex_abstraction_sig(&self, mut message: Value) -> Value {
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:UserDexAbstraction".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("user".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("enabled".into()));
m.insert("type".to_string(), Value::Str("bool".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(messageTypes, message);
Value::Null
}
pub fn build_user_abstraction_sig(&self, mut message: Value) -> Value {
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:UserSetAbstraction".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("user".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("abstraction".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(messageTypes, message);
Value::Null
}
pub fn build_approve_builder_fee_sig(&self, mut message: Value) -> Value {
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:ApproveBuilderFee".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("maxFeeRate".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("builder".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(messageTypes, message);
Value::Null
}
pub async fn set_ref(&mut self) -> Value {
if matches!(self.safe_bool_k(self.options.clone(), "refSet", &[Value::Bool(false)]), Value::Bool(true)) {
return Value::Bool(true);
}
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("refSet".into(), Value::Bool(true)); }
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("setReferrer".into()));
m.insert("code".to_string(), self.safe_string_k(self.options.clone(), "ref", &[Value::Str("CCXT1".into())]));
m
});
let mut nonce: Value = self.incrementing_nonce();
let mut signature: Value = self.sign_l1_action(action.clone(), nonce.clone(), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), action);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
let mut response: Value = Value::Null;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
response = self.private_post_exchange(&[request]).await;
return response.clone();
#[allow(unreachable_code)] { Value::Null }})).await;
match _try_result { Ok(__try_ok) => { if !matches!(__try_ok, Value::Null) { return __try_ok; } return Value::Null; } Err(_try_err) => { let e: Value = panic_to_value(_try_err);
response = Value::Null; // ignore this
} }
return response;
Value::Null
}
pub async fn approve_builder_fee(&mut self, mut builder: Value, mut maxFeeRate: Value) -> Value {
let mut nonce: Value = self.incrementing_nonce();
let mut isSandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), (if (isSandboxMode.as_bool() == Some(true)) { Value::Str("Testnet".into()) } else { Value::Str("Mainnet".into()) }));
m.insert("maxFeeRate".to_string(), maxFeeRate);
m.insert("builder".to_string(), builder);
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut sig: Value = self.build_approve_builder_fee_sig(payload.clone());
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), match &payload { Value::Dict(__m15) => __m15.get("hyperliquidChain").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".into()));
m.insert("maxFeeRate".to_string(), match &payload { Value::Dict(__m15) => __m15.get("maxFeeRate").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("builder".to_string(), match &payload { Value::Dict(__m15) => __m15.get("builder").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("nonce".to_string(), nonce.clone());
m.insert("type".to_string(), Value::Str("approveBuilderFee".into()));
m
});
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), action);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), sig);
m.insert("vaultAddress".to_string(), Value::Null);
m
});
return self.private_post_exchange(&[request]).await;
Value::Null
}
pub async fn initialize_client(&mut self) -> Value {
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
promise_all(&Value::from(vec![self.handle_builder_fee_approval().await, self.set_ref().await, self.is_unified_enabled(Value::Str("fetchBalance".into()), &[Value::Null, Value::Bool(false), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).await])).await; // for now only fetchBalance requires the unified knowledge, but we can extend this to other methods as needed
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
return Value::Bool(false);
}
return Value::Bool(true);
Value::Null
}
pub async fn handle_builder_fee_approval(&mut self) -> Value {
let mut buildFee: Value = self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(true)]);
let mut approvedBuilderFee: Value = self.safe_bool_k(self.options.clone(), "approvedBuilderFee", &[Value::Bool(false)]);
if (approvedBuilderFee.as_bool() == Some(true)) {
return Value::Bool(true);
}
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut builder: Value = self.safe_string_k(self.options.clone(), "builder", &[Value::Str("0x6530512A6c89C7cfCEbC3BA7fcD9aDa5f30827a6".into())]);
// when the user disables the builder fee (builderFee = false) we still approve and attach the builder,
// but with a 0% fee rate, so orders remain attributed to the builder for statistics purposes only and the user is not charged
let mut maxFeeRate: Value = self.safe_string_k(self.options.clone(), "feeRate", &[Value::Str("0.01%".into())]);
if (buildFee.as_bool() != Some(true)) {
maxFeeRate = Value::Str("0%".into());
}
self.approve_builder_fee(builder, maxFeeRate).await;
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("approvedBuilderFee".into(), Value::Bool(true)); }
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("builderFee".into(), Value::Bool(false)); }; // disable builder fee if an error occurs
}
return Value::Bool(true);
Value::Null
}
/*
* @method
* @name hyperliquid#isUnifiedEnabled
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#query-a-users-abstraction-state
* @description returns enableUnifiedMargin so the user can check if unified account is enabled
* @param {string} method the method for which we want to check if unified margin is enabled, this is used to check options for specific methods (e.g. fetchBalance can have a specific option to enable unified margin)
* @param {string} [address] the wallet address to query; defaults to the configured walletAddress
* @param {boolean} [shouldRefresh] force a fresh request instead of returning the cached value
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {bool} enableUnifiedMargin
*/
pub async fn is_unified_enabled(&mut self, mut method: Value, optional_args: &[Value]) -> Value {
let mut address = get_arg(optional_args, 0, Value::Null);
let mut shouldRefresh = get_arg(optional_args, 1, Value::Bool(false));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut publicAddress: Value = Value::Null;
let mut paramsPublicAddress: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (address == Value::Null) {
{ let __destr_tmp = self.handle_public_address(Value::Str("isUnifiedEnabled".into()), params.clone()); publicAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsPublicAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
}
let mut userAddress: Value = (if (address != Value::Null) { address.clone() } else { publicAddress });
let mut paramsAddress: Value = (if (address != Value::Null) { params } else { paramsPublicAddress });
let mut enableUnifiedMarginOptionparamsEnableUnifiedMarginVariable = self.handle_option_bool_and_params(paramsAddress, method, Value::Str("enableUnifiedMargin".into()), &[]);
let mut enableUnifiedMarginOption: Value = enableUnifiedMarginOptionparamsEnableUnifiedMarginVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsEnableUnifiedMargin: Value = enableUnifiedMarginOptionparamsEnableUnifiedMarginVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut enableUnifiedMargin: Value = enableUnifiedMarginOption;
if (enableUnifiedMargin == Value::Null) || is_true(&shouldRefresh) {
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userAbstraction".into()));
m.insert("user".to_string(), userAddress);
m
});
let mut response: Value = Value::Null;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let __ws_arg_17 = self.extend(request, &[paramsEnableUnifiedMargin.clone()]);
let mut rawResponse: Value = self.public_post_info(&[__ws_arg_17]).await;
if matches!(&rawResponse, Value::Str(_)) {
response = rawResponse.clone();
}
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
if matches!(&e, Value::Str(__s) if __s.contains("[InvalidProxySettings]")) {
panic!("{}", e);
}
response = Value::Null; // ignore this error and assume unified margin is not enabled
}
//
// "unifiedAccount" | "portfolioMargin" | "disabled" | "default" | "dexAbstraction"
//
if (response != Value::Null) {
response = replace_str(&response, &Value::Str("\"".into()), &Value::Str("".into()));
response = replace_str(&response, &Value::Str("\"".into()), &Value::Str("".into()));
enableUnifiedMargin = Value::Bool(response.as_str() == Some("unifiedAccount"));
}
// don't cache this result if this is a different addresss
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("enableUnifiedMargin".into(), enableUnifiedMargin.clone()); }; // cache this for future calls
}
return Value::from(vec![enableUnifiedMargin, paramsEnableUnifiedMargin]);
Value::Null
}
/*
* @method
* @name hyperliquid#setUserAbstraction
* @description set user abstraction mode
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#set-user-abstraction
* @param {string} abstraction one of the strings ["disabled", "unifiedAccount", "portfolioMargin"],
* @param {object} [params]
* @param {string} [params.type] 'userSetAbstraction' or 'agentSetAbstraction' default is 'userSetAbstraction'
* @returns dictionary response from the exchange
*/
pub async fn set_user_abstraction(&mut self, mut abstraction: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddressparamsPublicAddressVariable = self.handle_public_address(Value::Str("setUserAbstraction".into()), params);
let mut userAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPublicAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut nonce: Value = self.incrementing_nonce();
let mut isSandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut type_var: Value = self.safe_string_k(paramsPublicAddress, "type", &[Value::Str("userSetAbstraction".into())]);
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), (if (isSandboxMode.as_bool() == Some(true)) { Value::Str("Testnet".into()) } else { Value::Str("Mainnet".into()) }));
m.insert("user".to_string(), userAddress);
m.insert("abstraction".to_string(), abstraction);
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut sig: Value = self.build_user_abstraction_sig(payload.clone());
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), match &payload { Value::Dict(__m15) => __m15.get("hyperliquidChain").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".into()));
m.insert("abstraction".to_string(), match &payload { Value::Dict(__m15) => __m15.get("abstraction").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("user".to_string(), match &payload { Value::Dict(__m15) => __m15.get("user").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("nonce".to_string(), nonce.clone());
m.insert("type".to_string(), type_var);
m
});
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), action);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), sig);
m.insert("vaultAddress".to_string(), Value::Null);
m
});
return self.private_post_exchange(&[request]).await;
Value::Null
}
/*
* @method
* @name hyperliquid#enableUserDexAbstraction
* @description If set, actions on HIP-3 perps will automatically transfer collateral from validator-operated USDC perps balance for HIP-3 DEXs where USDC is the collateral token, and spot otherwise
* @param {boolean} enabled whether to enable user dex abstraction
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] 'userDexAbstraction' or 'agentEnableDexAbstraction' default is 'userDexAbstraction'
* @returns dictionary response from the exchange
*/
pub async fn enable_user_dex_abstraction(&mut self, mut enabled: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddressparamsPublicAddressVariable = self.handle_public_address(Value::Str("enableUserDexAbstraction".into()), params);
let mut userAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPublicAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut nonce: Value = self.incrementing_nonce();
let mut isSandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut type_var: Value = self.safe_string_k(paramsPublicAddress, "type", &[Value::Str("userDexAbstraction".into())]);
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), (if (isSandboxMode.as_bool() == Some(true)) { Value::Str("Testnet".into()) } else { Value::Str("Mainnet".into()) }));
m.insert("user".to_string(), userAddress);
m.insert("enabled".to_string(), enabled);
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut sig: Value = self.build_user_dex_abstraction_sig(payload.clone());
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), match &payload { Value::Dict(__m15) => __m15.get("hyperliquidChain").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".into()));
m.insert("enabled".to_string(), match &payload { Value::Dict(__m15) => __m15.get("enabled").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("user".to_string(), match &payload { Value::Dict(__m15) => __m15.get("user").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("nonce".to_string(), nonce.clone());
m.insert("type".to_string(), type_var);
m
});
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), action);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), sig);
m.insert("vaultAddress".to_string(), Value::Null);
m
});
return self.private_post_exchange(&[request]).await;
Value::Null
}
/*
* @method
* @name hyperliquid#setAgentAbstraction
* @description set agent abstraction mode
* @param {string} abstraction one of the strings ["i", "u", "p"] where "i" is "disabled", "u" is "unifiedAccount", and "p" is "portfolioMargin"
* @param {object} [params]
* @returns dictionary response from the exchange
*/
pub async fn set_agent_abstraction(&mut self, mut abstraction: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut nonce: Value = self.incrementing_nonce();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("agentSetAbstraction".into()));
m.insert("abstraction".to_string(), abstraction);
m
});
let mut signature: Value = self.sign_l1_action(action.clone(), nonce, &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("action".into(), action); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("signature".into(), signature); }
let __ws_arg_18 = self.extend(request, &[params]);
let mut response: Value = self.private_post_exchange(&[__ws_arg_18]).await;
return response;
Value::Null
}
/*
* @method
* @name hyperliquid#createOrder
* @description create a trade order
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.timeInForce] 'Gtc', 'Ioc', 'Alo'
* @param {bool} [params.postOnly] true or false whether the order is post-only
* @param {bool} [params.reduceOnly] true or false whether the order is reduce-only
* @param {float} [params.triggerPrice] The price at which a trigger order is triggered at
* @param {string} [params.clientOrderId] client order id, (optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
* @param {string} [params.slippage] the slippage for market order
* @param {string} [params.vaultAddress] the vault address for order
* @param {string} [params.subAccountAddress] sub account user address
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_order(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut orderglobalParamsVariable = self.parse_create_edit_order_args(Value::Null, symbol, type_var, side, amount, &[price, params]);
let mut order: Value = orderglobalParamsVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut globalParams: Value = orderglobalParamsVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut orders: Value = self.create_orders(Value::from(vec![order]), &[globalParams]).await;
let mut created: Value = self.safe_dict(orders, Value::Int(0), &[]);
return created;
Value::Null
}
/*
* @method
* @name hyperliquid#createTwapOrder
* @description create a trade order that is executed as a TWAP order over a specified duration.
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {int} duration the duration of the TWAP order in milliseconds
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {bool} [params.randomize] whether to randomize the time intervals of the TWAP order slices (default is false, meaning equal intervals)
* @param {bool} [params.reduceOnly] true or false whether the order is reduce-only
* @param {int} [params.expiresAfter] time in ms after which the twap order expires
* @param {string} [params.vaultAddress] the vault address for order
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_twap_order(&mut self, mut symbol: Value, mut side: Value, mut amount: Value, mut duration: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut market: Value = self.market(symbol.clone());
let mut nonce: Value = self.incrementing_nonce();
let mut isBuy: Value = (Value::Bool(to_upper(&side).as_str() == Some("BUY")));
let mut randomize: Value = self.safe_bool_k(params.clone(), "randomize", &[Value::Bool(false)]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("randomize".into()), &[]);
let mut vaultAddressOptionparamsVaultVariable = self.handle_option_string_and_params(paramsOmitted, Value::Str("createOrder".into()), Value::Str("vaultAddress".into()), &[]);
let mut vaultAddressOption: Value = vaultAddressOptionparamsVaultVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsVault: Value = vaultAddressOptionparamsVaultVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut vaultAddress: Value = self.format_vault_address(&[vaultAddressOption]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut durationMins: Value = math_floor(&(match (((match ((duration).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64(), (Value::Int(60)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })); // convert from ms to minutes
let mut orderObj: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("a".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null)));
m.insert("b".to_string(), isBuy);
m.insert("s".to_string(), self.amount_to_precision(symbol, amount));
m.insert("r".to_string(), self.safe_bool_k(paramsVault.clone(), "reduceOnly", &[Value::Bool(false)]));
m.insert("m".to_string(), durationMins);
m.insert("t".to_string(), randomize);
m
});
let mut orderAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("twapOrder".into()));
m.insert("twap".to_string(), orderObj);
m
});
let mut signature: Value = self.sign_l1_action(orderAction.clone(), nonce.clone(), &[vaultAddress.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), orderAction);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("vaultAddress".into(), vaultAddress); }
}
let mut expiresAfter: Value = self.safe_integer_k(paramsVault, "expiresAfter", &[]);
if (expiresAfter != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("expiresAfter".into(), expiresAfter); }
}
let mut response: Value = self.private_post_exchange(&[request]).await;
// {
// "status":"ok",
// "response":{
// "type":"twapOrder",
// "data":{
// "status": {
// "running":{
// "twapId":77738308
// }
// }
// }
// }
// }
let mut responseObj: Value = self.safe_dict_k(response, "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(responseObj, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut status: Value = self.safe_dict_k(data, "status", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut running: Value = self.safe_dict_k(status, "running", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderId: Value = self.safe_string_k(running, "twapId", &[]);
return self.parse_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("running".into()));
m.insert("oid".to_string(), orderId);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name hyperliquid#createOrders
* @description create a list of trade orders
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
* @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut request: Value = self.create_orders_request(orders, &[params]);
let mut response: Value = self.private_post_exchange(&[request]).await;
//
// {
// "status": "ok",
// "response": {
// "type": "order",
// "data": {
// "statuses": [
// {
// "resting": {
// "oid": 5063830287
// }
// }
// ]
// }
// }
// }
//
let mut responseObj: Value = self.safe_dict_k(response, "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(responseObj, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut statuses: Value = self.safe_list_k(data, "statuses", &[Value::from(vec![])]);
let mut ordersToBeParsed: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_806: bool = true;
while { if !__for_first_806 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_806 = false; i.as_f64().unwrap_or(f64::NAN) < ((statuses.len() as i64) as f64) } {
let mut order: Value = statuses.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if (order.as_str() == Some("waitingForTrigger")) {
append_to_array(&mut ordersToBeParsed, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), order.clone());
m
})); // tp/sl orders can return a string like "waitingForTrigger",
} else {
append_to_array(&mut ordersToBeParsed, order);
}
}
}
return self.parse_orders(ordersToBeParsed, &[]);
Value::Null
}
pub fn create_order_request(&self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a type argument".into()))));
}
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a side argument".into()))));
}
let mut market: Value = self.market(symbol.clone());
let mut typeValue: Value = to_upper(&type_var);
let mut sideValue: Value = to_upper(&side);
let mut isMarket: Value = (Value::Bool(typeValue.as_str() == Some("MARKET")));
let mut isBuy: Value = (Value::Bool(sideValue.as_str() == Some("BUY")));
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
let mut slippage: Value = self.safe_string_k(params.clone(), "slippage", &[]);
let mut defaultTimeInForce: Value = Value::Str("gtc".into());
if matches!(&isMarket, Value::Bool(true)) {
defaultTimeInForce = Value::Str("ioc".into());
}
let mut postOnly: Value = self.safe_bool_k(params.clone(), "postOnly", &[Value::Bool(false)]);
if (postOnly.as_bool() == Some(true)) {
defaultTimeInForce = Value::Str("alo".into());
}
let mut timeInForce: Value = self.safe_string_lower_k(params.clone(), "timeInForce", &[defaultTimeInForce]);
timeInForce = self.capitalize(timeInForce.clone());
let mut triggerPrice: Value = self.safe_string2(params.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut stopLossPrice: Value = self.safe_string_k(params.clone(), "stopLossPrice", &[triggerPrice.clone()]);
let mut takeProfitPrice: Value = self.safe_string_k(params.clone(), "takeProfitPrice", &[]);
let mut isTrigger: bool = (stopLossPrice != Value::Null) || (takeProfitPrice != Value::Null);
let mut px: Value = Value::Null;
if matches!(&isMarket, Value::Bool(true)) {
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" market orders require price to calculate the max slippage price. Default slippage can be set in options (default is 5%).".into()))));
}
px = (if matches!(&isBuy, Value::Bool(true)) { crate::precise::Precise::stringMul(&price, &crate::precise::Precise::stringAdd(&Value::Str("1".into()), &slippage)) } else { crate::precise::Precise::stringMul(&price, &crate::precise::Precise::stringSub(&Value::Str("1".into()), &slippage)) });
px = self.price_to_precision(symbol.clone(), px.clone()); // round after adding slippage
} else {
px = self.price_to_precision(symbol.clone(), price);
}
let mut sz: Value = self.amount_to_precision(symbol.clone(), amount);
let mut reduceOnly: Value = self.safe_bool_k(params, "reduceOnly", &[Value::Bool(false)]);
let mut orderType: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if isTrigger {
let mut isTp: bool = false;
if (takeProfitPrice != Value::Null) {
triggerPrice = self.price_to_precision(symbol.clone(), takeProfitPrice);
isTp = true;
} else {
triggerPrice = self.price_to_precision(symbol, stopLossPrice);
}
let mut tpSlType: Value = Value::Str("sl".into());
if isTp {
tpSlType = Value::Str("tp".into());
}
if let Value::Dict(__d) = &mut orderType { std::sync::Arc::make_mut(__d).insert("trigger".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("isMarket".to_string(), isMarket);
m.insert("triggerPx".to_string(), triggerPrice);
m.insert("tpsl".to_string(), tpSlType);
m
})); }
} else {
if let Value::Dict(__d) = &mut orderType { std::sync::Arc::make_mut(__d).insert("limit".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tif".to_string(), timeInForce);
m
})); }
}
let mut orderObj: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("a".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null)));
m.insert("b".to_string(), isBuy);
m.insert("p".to_string(), px);
m.insert("s".to_string(), sz);
m.insert("r".to_string(), reduceOnly);
m.insert("t".to_string(), orderType);
m
});
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut orderObj { std::sync::Arc::make_mut(__d).insert("c".into(), clientOrderId); }
}
return orderObj;
Value::Null
}
pub fn create_orders_request(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
/*
* @method
* @name hyperliquid#createOrdersRequest
* @description create a list of trade orders
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
* @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
self.check_required_credentials(&[]);
let mut defaultSlippage: Value = self.safe_string_k(self.options.clone(), "defaultSlippage", &[]);
defaultSlippage = self.safe_string_k(params.clone(), "slippage", &[defaultSlippage.clone()]);
let mut hasClientOrderId: bool = false;
{
let mut i: Value = Value::Int(0);
let mut __for_first_807: bool = true;
while { if !__for_first_807 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_807 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder.clone(), "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut clientOrderId: Value = self.safe_string2(orderParams.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
if (clientOrderId != Value::Null) {
hasClientOrderId = true;
}
}
}
if hasClientOrderId {
{
let mut i: Value = Value::Int(0);
let mut __for_first_808: bool = true;
while { if !__for_first_808 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_808 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder.clone(), "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut clientOrderId: Value = self.safe_string2(orderParams.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
if (clientOrderId == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrders() all orders must have clientOrderId if at least one has a clientOrderId".into()))));
}
}
}
}
let mut params2: Value = self.omit(params, Value::from(vec![Value::Str("slippage".into()), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), Value::Str("slippage".into()), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("timeInForce".into())]), &[]);
let mut nonce: Value = self.incrementing_nonce();
let mut orderReq: Value = Value::from(vec![]);
let mut grouping: Value = Value::Str("na".into());
{
let mut i: Value = Value::Int(0);
let mut __for_first_809: bool = true;
while { if !__for_first_809 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_809 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut marketId: Value = self.safe_string_k(rawOrder.clone(), "symbol", &[]);
let mut market: Value = self.market(marketId);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut type_var: Value = self.safe_string_upper_k(rawOrder.clone(), "type", &[]);
let mut side: Value = self.safe_string_upper_k(rawOrder.clone(), "side", &[]);
let mut amount: Value = self.safe_string_k(rawOrder.clone(), "amount", &[]);
let mut price: Value = self.safe_string_k(rawOrder.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder, "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut slippage: Value = self.safe_string_k(orderParams.clone(), "slippage", &[defaultSlippage.clone()]);
add_element_to_object(&mut orderParams, &Value::Str("slippage".into()), slippage);
let mut stopLoss: Value = self.safe_dict_k(orderParams.clone(), "stopLoss", &[]);
let mut takeProfit: Value = self.safe_dict_k(orderParams.clone(), "takeProfit", &[]);
let mut hasStopLoss: bool = stopLoss != Value::Null;
let mut hasTakeProfit: bool = takeProfit != Value::Null;
orderParams = self.omit(orderParams.clone(), Value::from(vec![Value::Str("stopLoss".into()), Value::Str("takeProfit".into())]), &[]);
let mut mainOrderObj: Value = self.create_order_request(symbol.clone(), type_var, side.clone(), amount.clone(), &[price, orderParams.clone()]);
if hasStopLoss || hasTakeProfit {
// grouping opposed orders for sl/tp
let mut stopLossOrderTriggerPrice: Value = self.safe_string2(stopLoss.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut stopLossOrderType: Value = self.safe_string_k(stopLoss.clone(), "type", &[Value::Str("limit".into())]);
let mut stopLossOrderLimitPrice: Value = self.safe_string2(stopLoss, Value::Str("price".into()), Value::Str("stopLossPrice".into()), &[stopLossOrderTriggerPrice.clone()]);
let mut takeProfitOrderTriggerPrice: Value = self.safe_string2(takeProfit.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut takeProfitOrderType: Value = self.safe_string_k(takeProfit.clone(), "type", &[Value::Str("limit".into())]);
let mut takeProfitOrderLimitPrice: Value = self.safe_string2(takeProfit, Value::Str("price".into()), Value::Str("takeProfitPrice".into()), &[takeProfitOrderTriggerPrice.clone()]);
grouping = self.safe_string_k(orderParams.clone(), "grouping", &[Value::Str("normalTpsl".into())]);
if (grouping.as_str() == Some("positionTpsl")) {
amount = Value::Str("0".into());
stopLossOrderType = Value::Str("market".into());
takeProfitOrderType = Value::Str("market".into());
} else if (grouping.as_str() == Some("normalTpsl")) {
append_to_array(&mut orderReq, mainOrderObj.clone());
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" only support grouping normalTpsl and positionTpsl.".into()))));
}
orderParams = self.omit(orderParams.clone(), Value::from(vec![Value::Str("stopLoss".into()), Value::Str("takeProfit".into()), Value::Str("grouping".into())]), &[]);
let mut triggerOrderSide: Value = Value::Str("".into());
if (side.as_str() == Some("BUY")) {
triggerOrderSide = Value::Str("sell".into());
} else {
triggerOrderSide = Value::Str("buy".into());
}
if hasTakeProfit {
let __ws_arg_19 = self.extend(orderParams.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("takeProfitPrice".to_string(), takeProfitOrderTriggerPrice);
m.insert("reduceOnly".to_string(), Value::Bool(true));
m
})]);
let mut orderObj: Value = self.create_order_request(symbol.clone(), takeProfitOrderType, triggerOrderSide.clone(), amount.clone(), &[takeProfitOrderLimitPrice, __ws_arg_19]);
append_to_array(&mut orderReq, orderObj.clone());
}
if hasStopLoss {
let __ws_arg_20 = self.extend(orderParams, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stopLossPrice".to_string(), stopLossOrderTriggerPrice);
m.insert("reduceOnly".to_string(), Value::Bool(true));
m
})]);
let mut orderObj: Value = self.create_order_request(symbol, stopLossOrderType, triggerOrderSide, amount, &[stopLossOrderLimitPrice, __ws_arg_20]);
append_to_array(&mut orderReq, orderObj);
}
} else {
append_to_array(&mut orderReq, mainOrderObj);
}
}
}
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_string_and_params(params2.clone(), Value::Str("createOrder".into()), Value::Str("vaultAddress".into()), &[]); vaultAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut orderAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("order".into()));
m.insert("orders".to_string(), orderReq);
m.insert("grouping".to_string(), grouping);
m
});
if matches!(self.safe_bool_k(self.options.clone(), "approvedBuilderFee", &[Value::Bool(false)]), Value::Bool(true)) {
let mut builder: Value = Value::Str("0x6530512A6c89C7cfCEbC3BA7fcD9aDa5f30827a6".into());
let mut wallet: Value = self.safe_string_lower_k(self.options.clone(), "builder", &[to_lower(&builder)]);
// when builderFee is disabled the builder is still attached but with a 0% fee (f = 0), for statistics purposes only
let mut feeInt: Value = self.safe_integer_k(self.options.clone(), "feeInt", &[Value::Int(10)]);
if !matches!(self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(true)]), Value::Bool(true)) {
feeInt = Value::Int(0);
}
if let Value::Dict(__d) = &mut orderAction { std::sync::Arc::make_mut(__d).insert("builder".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("b".to_string(), wallet);
m.insert("f".to_string(), feeInt);
m
})); }
}
let mut signature: Value = self.sign_l1_action(orderAction.clone(), nonce.clone(), &[vaultAddress.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), orderAction);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
params2 = self.omit(params2.clone(), Value::Str("vaultAddress".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("vaultAddress".into(), vaultAddress); }
}
return request;
Value::Null
}
/*
* @method
* @name hyperliquid#cancelOrder
* @description cancels an open order
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] client order id, (optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
* @param {string} [params.vaultAddress] the vault address for order
* @param {string} [params.subAccountAddress] sub account user address
* @param {boolean} [params.twap] whether the order to cancel is a twap order, (default is false)
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if matches!(self.safe_bool_k(params.clone(), "twap", &[Value::Bool(false)]), Value::Bool(true)) {
return self.cancel_twap_order(id.clone(), &[symbol.clone(), self.omit(params.clone(), Value::Str("twap".into()), &[])]).await;
}
let mut orders: Value = self.cancel_orders(Value::from(vec![id]), &[symbol, params]).await;
let mut canceled: Value = self.safe_dict(orders, Value::Int(0), &[]);
return canceled;
Value::Null
}
/*
* @method
* @name hyperliquid#cancelOrders
* @description cancel multiple orders
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid
* @param {string[]} ids order ids
* @param {string} [symbol] unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string|string[]} [params.clientOrderId] client order ids, (optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
* @param {string} [params.vaultAddress] the vault address
* @param {string} [params.subAccountAddress] sub account user address
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut request: Value = self.cancel_orders_request(ids, &[symbol, params]);
let mut response: Value = self.private_post_exchange(&[request]).await;
//
// {
// "status":"ok",
// "response":{
// "type":"cancel",
// "data":{
// "statuses":[
// "success"
// ]
// }
// }
// }
//
let mut innerResponse: Value = self.safe_dict_k(response, "response", &[]);
let mut data: Value = self.safe_dict_k(innerResponse, "data", &[]);
let mut statuses: Value = self.safe_list_k(data, "statuses", &[Value::from(vec![])]);
let mut orders: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_810: bool = true;
while { if !__for_first_810 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_810 = false; i.as_f64().unwrap_or(f64::NAN) < ((statuses.len() as i64) as f64) } {
let mut status: Value = statuses.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
append_to_array(&mut orders, self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), status.clone());
m.insert("status".to_string(), status);
m
}), &[]));
}
}
return orders;
Value::Null
}
/*
* @method
* @name hyperliquid#cancelTwapOrder
* @description cancels a running twap order
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-a-twap-order
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.expiresAfter] time in ms after which the twap order expires
* @param {string} [params.vaultAddress] the vault address for order
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_twap_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelTwapOrder() requires a symbol argument".into()))));
}
let mut market: Value = self.market(symbol);
let mut vaultAddress: Value = Value::Null;
let mut params2: Value = Value::Null;
{ let __destr_tmp = self.handle_option_string_and_params(params, Value::Str("cancelTwapOrder".into()), Value::Str("vaultAddress".into()), &[]); vaultAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("twapCancel".into()));
m.insert("a".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null)));
m.insert("t".to_string(), self.parse_to_numeric(id.clone()));
m
});
let mut nonce: Value = self.incrementing_nonce();
let mut signature: Value = self.sign_l1_action(action.clone(), nonce.clone(), &[vaultAddress.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), action);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
params2 = self.omit(params2.clone(), Value::Str("vaultAddress".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("vaultAddress".into(), vaultAddress); }
}
let mut expiresAfter: Value = self.safe_integer_k(params2.clone(), "expiresAfter", &[]);
if (expiresAfter != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("expiresAfter".into(), expiresAfter); }
params2 = self.omit(params2, Value::Str("expiresAfter".into()), &[]);
}
let mut response: Value = self.private_post_exchange(&[request]).await;
//
// {
// "status":"ok",
// "response":{
// "type":"twapCancel",
// "data":{
// "status": "success"
// }
// }
// }
//
let mut responseObj: Value = self.safe_dict_k(response, "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(responseObj, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut status: Value = self.safe_string_k(data, "status", &[]);
return self.parse_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), status);
m.insert("oid".to_string(), id);
m
}), &[market]);
Value::Null
}
pub fn cancel_orders_request(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
/*
* @method
* @name hyperliquid#cancelOrdersRequest
* @description build the request payload for cancelling multiple orders
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid
* @param {string[]} ids order ids
* @param {string} symbol unified market symbol
* @param {object} [params]
* @returns {object} the raw request object to be sent to the exchange
*/
let mut market: Value = self.market(symbol.clone());
let mut clientOrderId: Value = self.safe_value2(params.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
let mut params2: Value = self.omit(params, Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("client_id".into())]), &[]);
let mut nonce: Value = self.incrementing_nonce();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut cancelReq: Value = Value::from(vec![]);
let mut cancelAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("".into()));
m.insert("cancels".to_string(), Value::from(vec![]));
m
});
let mut baseId: Value = self.parse_to_numeric(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null));
if (clientOrderId != Value::Null) {
if !(matches!(&clientOrderId, Value::Arr(_))) {
clientOrderId = Value::from(vec![clientOrderId.clone()]);
}
if let Value::Dict(__d) = &mut cancelAction { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("cancelByCloid".into())); }
{
let mut i: Value = Value::Int(0);
let mut __for_first_811: bool = true;
while { if !__for_first_811 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_811 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&clientOrderId).as_f64().unwrap_or(f64::NAN) } {
append_to_array(&mut cancelReq, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), baseId.clone());
m.insert("cloid".to_string(), get_value(&clientOrderId, &i));
m
}));
}
}
} else {
if let Value::Dict(__d) = &mut cancelAction { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("cancel".into())); }
{
let mut i: Value = Value::Int(0);
let mut __for_first_812: bool = true;
while { if !__for_first_812 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_812 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
let mut o: Value = self.parse_to_numeric(ids.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
append_to_array(&mut cancelReq, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("a".to_string(), baseId.clone());
m.insert("o".to_string(), o);
m
}));
}
}
}
if let Value::Dict(__d) = &mut cancelAction { std::sync::Arc::make_mut(__d).insert("cancels".into(), cancelReq); }
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_string_and_params2(params2.clone(), Value::Str("cancelOrders".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]); vaultAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut signature: Value = self.sign_l1_action(cancelAction.clone(), nonce, &[vaultAddress.clone()]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("action".into(), cancelAction); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("signature".into(), signature); }
if (vaultAddress != Value::Null) {
params2 = self.omit(params2.clone(), Value::Str("vaultAddress".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("vaultAddress".into(), vaultAddress); }
}
return request;
Value::Null
}
/*
* @method
* @name hyperliquid#cancelOrdersForSymbols
* @description cancel multiple orders for multiple symbols
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s-by-cloid
* @param {CancellationRequest[]} orders each order should contain the parameters required by cancelOrder namely id and symbol, example [{"id": "a", "symbol": "BTC/USDT"}, {"id": "b", "symbol": "ETH/USDT"}]
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.vaultAddress] the vault address
* @param {string} [params.subAccountAddress] sub account user address
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_orders_for_symbols(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut nonce: Value = self.incrementing_nonce();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut cancelReq: Value = Value::from(vec![]);
let mut cancelAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("".into()));
m.insert("cancels".to_string(), Value::from(vec![]));
m
});
let mut cancelByCloid: bool = false;
{
let mut i: Value = Value::Int(0);
let mut __for_first_813: bool = true;
while { if !__for_first_813 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_813 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut order: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut clientOrderId: Value = self.safe_string_k(order.clone(), "clientOrderId", &[]);
if (clientOrderId != Value::Null) {
cancelByCloid = true;
}
let mut id: Value = self.safe_string_k(order.clone(), "id", &[]);
let mut symbol: Value = self.safe_string_k(order, "symbol", &[]);
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrdersForSymbols() requires a symbol argument in each order".into()))));
}
if (id != Value::Null) && cancelByCloid {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" cancelOrdersForSymbols() all orders must have either id or clientOrderId".into()))));
}
let mut assetKey: Value = (if cancelByCloid { Value::Str("asset".into()) } else { Value::Str("a".into()) });
let mut idKey: Value = (if cancelByCloid { Value::Str("cloid".into()) } else { Value::Str("o".into()) });
let mut market: Value = self.market(symbol);
let mut cancelObj: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if let Value::Dict(__d) = &mut cancelObj { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&assetKey), self.parse_to_numeric(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null))); }
if let Value::Dict(__d) = &mut cancelObj { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&idKey), (if cancelByCloid { clientOrderId } else { self.parse_to_numeric(id) })); }
append_to_array(&mut cancelReq, cancelObj);
}
}
if let Value::Dict(__d) = &mut cancelAction { std::sync::Arc::make_mut(__d).insert("type".into(), (if cancelByCloid { Value::Str("cancelByCloid".into()) } else { Value::Str("cancel".into()) })); }
if let Value::Dict(__d) = &mut cancelAction { std::sync::Arc::make_mut(__d).insert("cancels".into(), cancelReq); }
let mut vaultAddressOption: Value = self.handle_option_string_and_params2(params, Value::Str("cancelOrdersForSymbols".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut vaultAddress: Value = self.format_vault_address(&[vaultAddressOption]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut signature: Value = self.sign_l1_action(cancelAction.clone(), nonce, &[vaultAddress.clone()]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("action".into(), cancelAction); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("signature".into(), signature); }
if (vaultAddress != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("vaultAddress".into(), vaultAddress); }
}
let mut response: Value = self.private_post_exchange(&[request]).await;
return Value::from(vec![self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
}), &[])]);
Value::Null
}
/*
* @method
* @name hyperliquid#cancelAllOrdersAfter
* @description dead man's switch, cancel all orders after the given timeout
* @param {number} timeout time in milliseconds, 0 represents cancel the timer
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.vaultAddress] the vault address
* @param {string} [params.subAccountAddress] sub account user address
* @returns {object} the api result
*/
pub async fn cancel_all_orders_after(&mut self, mut timeout: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut params2: Value = self.omit(params, Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("client_id".into())]), &[]);
let mut nonce: Value = self.incrementing_nonce();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut cancelAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("scheduleCancel".into()));
m.insert("time".to_string(), (match (&(nonce), &(timeout)) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }));
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_string_and_params2(params2.clone(), Value::Str("cancelAllOrdersAfter".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]); vaultAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut signature: Value = self.sign_l1_action(cancelAction.clone(), nonce, &[vaultAddress.clone()]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("action".into(), cancelAction); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("signature".into(), signature); }
if (vaultAddress != Value::Null) {
params2 = self.omit(params2, Value::Str("vaultAddress".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("vaultAddress".into(), vaultAddress); }
}
let mut response: Value = self.private_post_exchange(&[request]).await;
return response;
Value::Null
}
pub fn edit_orders_request(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
let mut hasClientOrderId: bool = false;
{
let mut i: Value = Value::Int(0);
let mut __for_first_814: bool = true;
while { if !__for_first_814 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_814 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder.clone(), "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut clientOrderId: Value = self.safe_string2(orderParams.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
if (clientOrderId != Value::Null) {
hasClientOrderId = true;
}
}
}
if hasClientOrderId {
{
let mut i: Value = Value::Int(0);
let mut __for_first_815: bool = true;
while { if !__for_first_815 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_815 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder.clone(), "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut clientOrderId: Value = self.safe_string2(orderParams.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
if (clientOrderId == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" editOrders() all orders must have clientOrderId if at least one has a clientOrderId".into()))));
}
}
}
}
let mut params2: Value = self.omit(params, Value::from(vec![Value::Str("slippage".into()), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), Value::Str("slippage".into()), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("timeInForce".into())]), &[]);
let mut modifies: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_816: bool = true;
while { if !__for_first_816 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_816 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut id: Value = self.safe_string_k(rawOrder.clone(), "id", &[]);
let mut marketId: Value = self.safe_string_k(rawOrder.clone(), "symbol", &[]);
let mut market: Value = self.market(marketId);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut type_var: Option<String> = self.safe_string_upper_k(rawOrder.clone(), "type", &[]).as_str().map(str::to_owned);
let mut isMarket: Value = (Value::Bool(type_var.as_deref() == Some("MARKET")));
let mut side: Option<String> = self.safe_string_upper_k(rawOrder.clone(), "side", &[]).as_str().map(str::to_owned);
let mut isBuy: Value = (Value::Bool(side.as_deref() == Some("BUY")));
let mut amount: Value = self.safe_string_k(rawOrder.clone(), "amount", &[]);
let mut price: Value = self.safe_string_k(rawOrder.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder, "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut defaultSlippage: Value = self.safe_string_k(self.options.clone(), "defaultSlippage", &[]);
let mut slippage: Value = self.safe_string_k(orderParams.clone(), "slippage", &[defaultSlippage]);
let mut defaultTimeInForce: Value = Value::Str("gtc".into());
if matches!(&isMarket, Value::Bool(true)) {
defaultTimeInForce = Value::Str("ioc".into());
}
let mut postOnly: Value = self.safe_bool_k(orderParams.clone(), "postOnly", &[Value::Bool(false)]);
if (postOnly.as_bool() == Some(true)) {
defaultTimeInForce = Value::Str("alo".into());
}
let mut timeInForce: Value = self.safe_string_lower_k(orderParams.clone(), "timeInForce", &[defaultTimeInForce]);
timeInForce = self.capitalize(timeInForce.clone());
let mut clientOrderId: Value = self.safe_string2(orderParams.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
let mut triggerPrice: Value = self.safe_string2(orderParams.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut stopLossPrice: Value = self.safe_string_k(orderParams.clone(), "stopLossPrice", &[triggerPrice.clone()]);
let mut takeProfitPrice: Value = self.safe_string_k(orderParams.clone(), "takeProfitPrice", &[]);
let mut isTrigger: bool = (stopLossPrice != Value::Null) || (takeProfitPrice != Value::Null);
let mut reduceOnly: Value = self.safe_bool_k(orderParams.clone(), "reduceOnly", &[Value::Bool(false)]);
orderParams = self.omit(orderParams, Value::from(vec![Value::Str("slippage".into()), Value::Str("timeInForce".into()), Value::Str("triggerPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), Value::Str("postOnly".into()), Value::Str("reduceOnly".into())]), &[]);
let mut px: Value = self.number_to_string(price);
if matches!(&isMarket, Value::Bool(true)) {
px = (if matches!(&isBuy, Value::Bool(true)) { crate::precise::Precise::stringMul(&px, &crate::precise::Precise::stringAdd(&Value::Str("1".into()), &slippage)) } else { crate::precise::Precise::stringMul(&px, &crate::precise::Precise::stringSub(&Value::Str("1".into()), &slippage)) });
px = self.price_to_precision(symbol.clone(), px.clone());
} else {
px = self.price_to_precision(symbol.clone(), px.clone());
}
let mut sz: Value = self.amount_to_precision(symbol.clone(), amount);
let mut orderType: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if isTrigger {
let mut isTp: bool = false;
if (takeProfitPrice != Value::Null) {
triggerPrice = self.price_to_precision(symbol.clone(), takeProfitPrice);
isTp = true;
} else {
triggerPrice = self.price_to_precision(symbol, stopLossPrice);
}
let mut tpSlType: Value = Value::Str("sl".into());
if isTp {
tpSlType = Value::Str("tp".into());
}
if let Value::Dict(__d) = &mut orderType { std::sync::Arc::make_mut(__d).insert("trigger".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("isMarket".to_string(), isMarket);
m.insert("triggerPx".to_string(), triggerPrice.clone());
m.insert("tpsl".to_string(), tpSlType);
m
})); }
} else {
if let Value::Dict(__d) = &mut orderType { std::sync::Arc::make_mut(__d).insert("limit".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tif".to_string(), timeInForce);
m
})); }
}
if (triggerPrice == Value::Null) {
triggerPrice = Value::Str("0".into());
}
let mut orderReq: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("a".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null)));
m.insert("b".to_string(), isBuy);
m.insert("p".to_string(), px);
m.insert("s".to_string(), sz);
m.insert("r".to_string(), reduceOnly);
m.insert("t".to_string(), orderType);
m
});
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut orderReq { std::sync::Arc::make_mut(__d).insert("c".into(), clientOrderId); }
}
let mut modifyReq: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("oid".to_string(), self.parse_to_int(id));
m.insert("order".to_string(), orderReq);
m
});
append_to_array(&mut modifies, modifyReq);
}
}
let mut nonce: Value = self.incrementing_nonce();
let mut modifyAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("batchModify".into()));
m.insert("modifies".to_string(), modifies);
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_string_and_params(params2.clone(), Value::Str("editOrder".into()), Value::Str("vaultAddress".into()), &[]); vaultAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut signature: Value = self.sign_l1_action(modifyAction.clone(), nonce.clone(), &[vaultAddress.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), modifyAction);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("vaultAddress".into(), vaultAddress); }
}
return request;
Value::Null
}
/*
* @method
* @name hyperliquid#editOrder
* @description edit a trade order
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#modify-multiple-orders
* @param {string} id cancel order id
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.timeInForce] 'Gtc', 'Ioc', 'Alo'
* @param {bool} [params.postOnly] true or false whether the order is post-only
* @param {bool} [params.reduceOnly] true or false whether the order is reduce-only
* @param {float} [params.triggerPrice] The price at which a trigger order is triggered at
* @param {string} [params.clientOrderId] client order id, (optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
* @param {string} [params.vaultAddress] the vault address for order
* @param {string} [params.subAccountAddress] sub account user address
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (id == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires an id argument".into()))));
}
let mut orderglobalParamsVariable = self.parse_create_edit_order_args(id, symbol, type_var, side, amount, &[price, params]);
let mut order: Value = orderglobalParamsVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut globalParams: Value = orderglobalParamsVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut orders: Value = self.edit_orders(Value::from(vec![order]), &[globalParams]).await;
let mut edited: Value = self.safe_dict(orders, Value::Int(0), &[]);
return edited;
Value::Null
}
/*
* @method
* @name hyperliquid#editOrders
* @description edit a list of trade orders
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#modify-multiple-orders
* @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn edit_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut request: Value = self.edit_orders_request(orders, &[params]);
let mut response: Value = self.private_post_exchange(&[request]).await;
//
// {
// "status": "ok",
// "response": {
// "type": "order",
// "data": {
// "statuses": [
// {
// "resting": {
// "oid": 5063830287
// }
// }
// ]
// }
// }
// }
// when the order is filled immediately
// {
// "status":"ok",
// "response":{
// "type":"order",
// "data":{
// "statuses":[
// {
// "filled":{
// "totalSz":"0.1",
// "avgPx":"100.84",
// "oid":6195281425
// }
// }
// ]
// }
// }
// }
//
let mut responseObject: Value = self.safe_dict_k(response, "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut dataObject: Value = self.safe_dict_k(responseObject, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut statuses: Value = self.safe_list_k(dataObject, "statuses", &[Value::from(vec![])]);
return self.parse_orders(statuses, &[]);
Value::Null
}
/*
* @method
* @name hyperliquid#createVault
* @description creates a value
* @param {string} name The name of the vault
* @param {string} description The description of the vault
* @param {number} initialUsd The initialUsd of the vault
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the api result
*/
pub async fn create_vault(&mut self, mut name: Value, mut description: Value, mut initialUsd: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut nonce: Value = self.incrementing_nonce();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut usd: Value = self.parse_to_int(crate::precise::Precise::stringMul(&self.number_to_string(initialUsd), &Value::Str("1000000".into())));
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("createVault".into()));
m.insert("name".to_string(), name);
m.insert("description".to_string(), description);
m.insert("initialUsd".to_string(), usd);
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut signature: Value = self.sign_l1_action(action.clone(), nonce, &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("action".into(), action); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("signature".into(), signature); }
let __ws_arg_21 = self.extend(request, &[params]);
let mut response: Value = self.private_post_exchange(&[__ws_arg_21]).await;
return response;
Value::Null
}
/*
* @method
* @name hyperliquid#fetchFundingRateHistory
* @description fetches historical funding rate prices
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-historical-funding-rates
* @param {string} symbol unified symbol of the market to fetch the funding rate history for
* @param {int} [since] timestamp in ms of the earliest funding rate to fetch
* @param {int} [limit] the maximum amount of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure} to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest funding rate
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure}
*/
pub async fn fetch_funding_rate_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRateHistory() requires a symbol argument".into()))));
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("fundingHistory".into()));
m.insert("coin".to_string(), self.safe_string_k(market.clone(), "baseName", &[]));
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
} else {
let mut maxLimit: Value = (if (limit == Value::Null) { Value::Int(500) } else { limit.clone() });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), (match (&(self.milliseconds()), &((match (&((match (&((match (&(maxLimit), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })); }
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("until".into()), &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
}
let __ws_arg_22 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.public_post_info(&[__ws_arg_22]).await;
//
// [
// {
// "coin": "ETH",
// "fundingRate": "0.0000125",
// "premium": "0.00057962",
// "time": 1704290400031
// }
// ]
//
let mut result: Value = Value::from(vec![]);
let mut fundings: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
fundings = response.clone();
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_817: bool = true;
while { if !__for_first_817 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_817 = false; i.as_f64().unwrap_or(f64::NAN) < ((fundings.len() as i64) as f64) } {
let mut entry: Value = self.safe_dict(fundings.clone(), i.clone(), &[]);
let mut timestamp: Value = self.safe_integer_k(entry.clone(), "time", &[]);
append_to_array(&mut result, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), entry.clone());
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market.clone()]));
m.insert("fundingRate".to_string(), self.safe_number_k(entry, "fundingRate", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
}));
}
}
let mut sorted: Value = self.sort_by(result, Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[symbol, since, limit]);
Value::Null
}
pub fn get_dex_from_hip3_symbol(&self, mut market: Value) -> Value {
let __market_empty = indexmap::IndexMap::new();
let market = market.as_map().unwrap_or(&__market_empty);
let mut baseName: Value = (match market.get("baseName") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
let mut part: Value = split(&baseName, &Value::Str(":".into()));
let mut partsLength: f64 = ((part.len() as i64) as f64);
if partsLength > ((1i64) as f64) {
return self.safe_string(part, Value::Int(0), &[]);
}
return Value::Null;
Value::Null
}
/*
* @method
* @name hyperliquid#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-open-orders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] user address, will default to this.walletAddress if not provided
* @param {string} [params.method] 'openOrders' or 'frontendOpenOrders' default is 'frontendOpenOrders'
* @param {string} [params.subAccountAddress] sub account user address
* @param {string} [params.dex] perp dex name. default is null
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddressparamsPublicAddressVariable = self.handle_public_address(Value::Str("fetchOpenOrders".into()), params);
let mut userAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPublicAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut methodparamsMethodVariable = self.handle_option_string_and_params(paramsPublicAddress, Value::Str("fetchOpenOrders".into()), Value::Str("method".into()), &[Value::Str("frontendOpenOrders".into())]);
let mut method: Value = methodparamsMethodVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMethod: Value = methodparamsMethodVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), method);
m.insert("user".to_string(), userAddress);
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
// check if is hip3 symbol
let mut dexName: Value = self.get_dex_from_hip3_symbol(market.clone());
if (dexName != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("dex".into(), dexName); }
}
}
let __ws_arg_23 = self.extend(request, &[paramsMethod]);
let mut response: Value = self.public_post_info(&[__ws_arg_23]).await;
//
// [
// {
// "coin": "ETH",
// "limitPx": "2000.0",
// "oid": 3991946565,
// "origSz": "0.1",
// "side": "B",
// "sz": "0.1",
// "timestamp": 1704346468838
// }
// ]
//
let mut orderWithStatus: Value = Value::from(vec![]);
let mut rawOrders: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
rawOrders = response.clone();
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_818: bool = true;
while { if !__for_first_818 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_818 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawOrders.len() as i64) as f64) } {
let mut order: Value = self.safe_dict(rawOrders.clone(), i.clone(), &[]);
let mut extendOrder: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (self.safe_string_k(order.clone(), "status", &[]) == Value::Null) {
if let Value::Dict(__d) = &mut extendOrder { std::sync::Arc::make_mut(__d).insert("ccxtStatus".into(), Value::Str("open".into())); }
}
append_to_array(&mut orderWithStatus, self.extend(order, &[extendOrder]));
}
}
return self.parse_orders(orderWithStatus, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchClosedOrders
* @description fetch all unfilled currently closed orders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] user address, will default to this.walletAddress if not provided
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.fetch_orders(&[symbol.clone(), Value::Null, Value::Null, params]).await; // don't filter here because we don't want to catch open orders
let mut closedOrders: Value = self.filter_by_array(orders, Value::Str("status".into()), &[Value::from(vec![Value::Str("closed".into())]), Value::Bool(false)]);
return self.filter_by_symbol_since_limit(closedOrders, &[symbol, since, limit]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchCanceledOrders
* @description fetch all canceled orders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] user address, will default to this.walletAddress if not provided
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_canceled_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.fetch_orders(&[symbol.clone(), Value::Null, Value::Null, params]).await; // don't filter here because we don't want to catch open orders
let mut closedOrders: Value = self.filter_by_array(orders, Value::Str("status".into()), &[Value::from(vec![Value::Str("canceled".into())]), Value::Bool(false)]);
return self.filter_by_symbol_since_limit(closedOrders, &[symbol, since, limit]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchCanceledAndClosedOrders
* @description fetch all closed and canceled orders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] user address, will default to this.walletAddress if not provided
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_canceled_and_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.fetch_orders(&[symbol.clone(), Value::Null, Value::Null, params]).await; // don't filter here because we don't want to catch open orders
let mut closedOrders: Value = self.filter_by_array(orders, Value::Str("status".into()), &[Value::from(vec![Value::Str("canceled".into()), Value::Str("closed".into()), Value::Str("rejected".into())]), Value::Bool(false)]);
return self.filter_by_symbol_since_limit(closedOrders, &[symbol, since, limit]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchOrders
* @description fetch all orders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] user address, will default to this.walletAddress if not provided
* @param {string} [params.subAccountAddress] sub account user address
* @param {string} [params.dex] perp dex name. default is null
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddressparamsPublicAddressVariable = self.handle_public_address(Value::Str("fetchOrders".into()), params);
let mut userAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPublicAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("historicalOrders".into()));
m.insert("user".to_string(), userAddress);
m
});
if (symbol != Value::Null) {
market = self.market(symbol);
// check if is hip3 symbol
let mut dexName: Value = self.get_dex_from_hip3_symbol(market.clone());
if (dexName != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("dex".into(), dexName); }
}
}
let __ws_arg_24 = self.extend(request, &[paramsPublicAddress]);
let mut response: Value = self.public_post_info(&[__ws_arg_24]).await;
//
// [
// {
// "order": {
// "coin": "ETH",
// "limitPx": "2000.0",
// "oid": 3991946565,
// "origSz": "0.1",
// "side": "B",
// "sz": "0.1",
// "timestamp": 1704346468838
// },
// "status": "open",
// "statusTimestamp": 1704346468838
// }
// ]
//
// Hyperliquid returns the full status history for each order,
// so a canceled order appears twice: once as 'open' and once as 'canceled'.
// Deduplicate by oid, keeping the entry with the most recent statusTimestamp.
let mut deduplicatedByOid: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut historicalOrders: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
historicalOrders = response.clone();
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_819: bool = true;
while { if !__for_first_819 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_819 = false; i.as_f64().unwrap_or(f64::NAN) < ((historicalOrders.len() as i64) as f64) } {
let mut rawOrder: Value = historicalOrders.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut entry: Value = self.safe_dict_k(rawOrder.clone(), "order", &[]);
if (entry == Value::Null) {
entry = rawOrder.clone();
}
let mut oid: Value = self.safe_string_k(entry, "oid", &[]);
if (oid != Value::Null) {
if !(in_op(&deduplicatedByOid, &oid)) {
if let Value::Dict(__d) = &mut deduplicatedByOid { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&oid), rawOrder.clone()); }
} else {
let mut existingTimestamp: Value = self.safe_integer(deduplicatedByOid.as_map().and_then(|__m| oid.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null), Value::Str("statusTimestamp".into()), &[]);
let mut currentTimestamp: Value = self.safe_integer_k(rawOrder.clone(), "statusTimestamp", &[]);
if (currentTimestamp != Value::Null) && ((existingTimestamp == Value::Null) || currentTimestamp.as_f64().unwrap_or(f64::NAN) > existingTimestamp.as_f64().unwrap_or(f64::NAN)) {
if let Value::Dict(__d) = &mut deduplicatedByOid { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&oid), rawOrder); }
}
}
}
}
}
let mut deduplicated: Value = object_values(&deduplicatedByOid);
return self.parse_orders(deduplicated, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchOrder
* @description fetches information on an order made by the user
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#query-order-status-by-oid-or-cloid
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] client order id, (optional 128 bit hex string e.g. 0x1234567890abcdef1234567890abcdef)
* @param {string} [params.user] user address, will default to this.walletAddress if not provided
* @param {string} [params.subAccountAddress] sub account user address
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddress: Value = Value::Null;
let mut params2: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchOrder".into()), params); userAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut clientOrderId: Value = self.safe_string_k(params2.clone(), "clientOrderId", &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("orderStatus".into()));
m.insert("user".to_string(), userAddress);
m
});
if (clientOrderId != Value::Null) {
params2 = self.omit(params2.clone(), Value::Str("clientOrderId".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("oid".into(), clientOrderId); }
} else {
let mut isClientOrderId: bool = ((id.len() as i64) as f64) >= ((34i64) as f64);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("oid".into(), (if isClientOrderId { id.clone() } else { self.parse_to_numeric(id) })); }
}
let __ws_arg_25 = self.extend(request, &[params2]);
let mut response: Value = self.public_post_info(&[__ws_arg_25]).await;
//
// {
// "order": {
// "order": {
// "children": [],
// "cloid": null,
// "coin": "ETH",
// "isPositionTpsl": false,
// "isTrigger": false,
// "limitPx": "2000.0",
// "oid": "3991946565",
// "orderType": "Limit",
// "origSz": "0.1",
// "reduceOnly": false,
// "side": "B",
// "sz": "0.1",
// "tif": "Gtc",
// "timestamp": "1704346468838",
// "triggerCondition": "N/A",
// "triggerPx": "0.0"
// },
// "status": "open",
// "statusTimestamp": "1704346468838"
// },
// "status": "order"
// }
//
let mut data: Value = self.safe_dict_k(response, "order", &[]);
return self.parse_order(data, &[market]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// createOrdersWs error
//
// {error: 'Insufficient margin to place order. asset=159'}
//
// fetchOpenOrders
//
// {
// "coin": "ETH",
// "limitPx": "2000.0",
// "oid": 3991946565,
// "origSz": "0.1",
// "side": "B",
// "sz": "0.1",
// "timestamp": 1704346468838
// }
// fetchClosedorders
// {
// "cloid": null,
// "closedPnl": "0.0",
// "coin": "SOL",
// "crossed": true,
// "dir": "Open Long",
// "fee": "0.003879",
// "hash": "0x4a2647998682b7f07bc5040ab531e1011400f9a51bfa0346a0b41ebe510e8875",
// "liquidationMarkPx": null,
// "oid": "6463280784",
// "px": "110.83",
// "side": "B",
// "startPosition": "1.64",
// "sz": "0.1",
// "tid": "232174667018988",
// "time": "1709142268394"
// }
//
// fetchOrder
//
// {
// "order": {
// "children": [],
// "cloid": null,
// "coin": "ETH",
// "isPositionTpsl": false,
// "isTrigger": false,
// "limitPx": "2000.0",
// "oid": "3991946565",
// "orderType": "Limit",
// "origSz": "0.1",
// "reduceOnly": false,
// "side": "B",
// "sz": "0.1",
// "tif": "Gtc",
// "timestamp": "1704346468838",
// "triggerCondition": "N/A",
// "triggerPx": "0.0"
// },
// "status": "open",
// "statusTimestamp": "1704346468838"
// }
//
// createOrder
//
// {
// "resting": {
// "oid": 5063830287
// }
// }
//
// {
// "filled":{
// "totalSz":"0.1",
// "avgPx":"100.84",
// "oid":6195281425
// }
// }
// frontendOrder
// {
// "children": [],
// "cloid": null,
// "coin": "BLUR",
// "isPositionTpsl": false,
// "isTrigger": true,
// "limitPx": "0.5",
// "oid": 8670487141,
// "orderType": "Stop Limit",
// "origSz": "20.0",
// "reduceOnly": false,
// "side": "B",
// "sz": "20.0",
// "tif": null,
// "timestamp": 1715523663687,
// "triggerCondition": "Price above 0.6",
// "triggerPx": "0.6"
// }
//
let mut error: Option<String> = self.safe_string_k(order.clone(), "error", &[]).as_str().map(str::to_owned);
if (error.is_some()) {
let mut finalOrder: Value = order.clone(); // java req
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), finalOrder);
m.insert("status".to_string(), Value::Str("rejected".into()));
m
}), &[]);
}
let mut entry: Value = self.safe_dict_n(order.clone(), Value::from(vec![Value::Str("order".into()), Value::Str("resting".into()), Value::Str("filled".into())]), &[]);
if (entry == Value::Null) {
entry = order.clone();
}
let mut filled: Value = self.safe_dict_k(order.clone(), "filled", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut coin: Value = self.safe_string_k(entry.clone(), "coin", &[]);
let mut marketId: Value = Value::Null;
if (coin != Value::Null) {
marketId = self.coin_to_market_id(coin).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
}
let mut marketResolved: Value = Value::Null;
if (self.safe_string_k(entry.clone(), "id", &[]) == Value::Null) {
marketResolved = self.safe_market(&[marketId.clone()]);
} else {
marketResolved = self.safe_market(&[marketId, market]);
}
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = self.safe_integer_k(entry.clone(), "timestamp", &[]);
let mut status: Value = self.safe_string2(order.clone(), Value::Str("status".into()), Value::Str("ccxtStatus".into()), &[]);
let mut orderOmitted: Value = self.omit(order, Value::from(vec![Value::Str("ccxtStatus".into())]), &[]);
let mut side: Value = self.safe_string_k(entry.clone(), "side", &[]);
if (side != Value::Null) {
side = (if (side.as_str() == Some("A")) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
}
let mut totalAmount: Value = self.safe_string2(entry.clone(), Value::Str("origSz".into()), Value::Str("totalSz".into()), &[]);
let mut remaining: Value = self.safe_string_k(entry.clone(), "sz", &[]);
let mut tif: Value = self.safe_string_upper_k(entry.clone(), "tif", &[]);
let mut postOnly: Value = Value::Null;
if (tif != Value::Null) {
postOnly = (Value::Bool(tif.as_str() == Some("ALO")));
}
let mut isTrigger: Value = self.safe_bool_k(entry.clone(), "isTrigger", &[Value::Bool(false)]);
let mut triggerPx: Value = (if isTrigger.as_bool() == Some(true) { self.safe_number_k(entry.clone(), "triggerPx", &[]) } else { Value::Null });
// standalone stop / take-profit orders carry their trigger in triggerPx - surface it
// through the unified stopLossPrice / takeProfitPrice fields as well, see #24318
let mut orderTypeRaw: Value = self.safe_string_lower_k(entry.clone(), "orderType", &[Value::Str("".into())]);
let mut stopLossPrice: Value = Value::Null;
let mut takeProfitPrice: Value = Value::Null;
if (triggerPx != Value::Null) {
if Value::Int(orderTypeRaw.as_str().and_then(|__s| __s.find("stop")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
stopLossPrice = triggerPx.clone();
} else if Value::Int(orderTypeRaw.as_str().and_then(|__s| __s.find("take profit")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
takeProfitPrice = triggerPx.clone();
}
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), orderOmitted.clone());
m.insert("id".to_string(), self.safe_string_k(entry.clone(), "oid", &[]));
m.insert("clientOrderId".to_string(), self.safe_string_k(entry.clone(), "cloid", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), self.safe_integer_k(orderOmitted, "statusTimestamp", &[]));
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), self.parse_order_type(self.safe_string_lower_k(entry.clone(), "orderType", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("timeInForce".to_string(), tif);
m.insert("postOnly".to_string(), postOnly);
m.insert("reduceOnly".to_string(), self.safe_bool_k(entry.clone(), "reduceOnly", &[]));
m.insert("side".to_string(), side);
m.insert("price".to_string(), self.safe_string_k(entry.clone(), "limitPx", &[]));
m.insert("triggerPrice".to_string(), triggerPx);
m.insert("stopLossPrice".to_string(), stopLossPrice);
m.insert("takeProfitPrice".to_string(), takeProfitPrice);
m.insert("amount".to_string(), totalAmount.clone());
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), self.safe_string_k(entry, "avgPx", &[]));
m.insert("filled".to_string(), self.safe_string_k(filled, "totalSz", &[crate::precise::Precise::stringSub(&totalAmount, &remaining)]));
m.insert("remaining".to_string(), remaining);
m.insert("status".to_string(), self.parse_order_status(status));
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[marketResolved]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
if (status == Value::Null) {
return Value::Null;
}
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("triggered".to_string(), Value::Str("open".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("open".to_string(), Value::Str("open".into()));
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m.insert("rejected".to_string(), Value::Str("rejected".into()));
m.insert("marginCanceled".to_string(), Value::Str("canceled".into()));
m
});
if (ends_with(&status, &Value::Str("Rejected".into()))) {
return Value::Str("rejected".into());
}
if (ends_with(&status, &Value::Str("Canceled".into()))) {
return Value::Str("canceled".into());
}
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_order_type(&self, mut status: Value) -> Option<String> {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stop limit".to_string(), Value::Str("limit".into()));
m.insert("stop market".to_string(), Value::Str("market".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name hyperliquid#fetchMyTrades
* @description fetch all trades made by the user
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills-by-time
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest trade
* @param {string} [params.subAccountAddress] sub account user address
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddressparamsPublicAddressVariable = self.handle_public_address(Value::Str("fetchMyTrades".into()), params);
let mut userAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPublicAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("user".to_string(), userAddress);
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("userFillsByTime".into())); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("userFills".into())); }
}
let mut until: Value = self.safe_integer_k(paramsPublicAddress.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(paramsPublicAddress, Value::Str("until".into()), &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
}
let __ws_arg_26 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.public_post_info(&[__ws_arg_26]).await;
//
// [
// {
// "closedPnl": "0.19343",
// "coin": "ETH",
// "crossed": true,
// "dir": "Close Long",
// "fee": "0.050062",
// "feeToken": "USDC",
// "hash": "0x09d77c96791e98b5775a04092584ab010d009445119c71e4005c0d634ea322bc",
// "liquidationMarkPx": null,
// "oid": 3929354691,
// "px": "2381.1",
// "side": "A",
// "startPosition": "0.0841",
// "sz": "0.0841",
// "tid": 128423918764978,
// "time": 1704262888911
// }
// ]
//
let mut myFills: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
myFills = response.clone();
}
return self.parse_trades(myFills, &[market, since, limit]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "closedPnl": "0.19343",
// "coin": "ETH",
// "crossed": true,
// "dir": "Close Long",
// "fee": "0.050062",
// "hash": "0x09d77c96791e98b5775a04092584ab010d009445119c71e4005c0d634ea322bc",
// "liquidationMarkPx": null,
// "oid": 3929354691,
// "px": "2381.1",
// "side": "A",
// "startPosition": "0.0841",
// "sz": "0.0841",
// "tid": 128423918764978,
// "time": 1704262888911
// }
//
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "time", &[]);
let mut price: Value = self.safe_string_k(trade.clone(), "px", &[]);
let mut amount: Value = self.safe_string_k(trade.clone(), "sz", &[]);
let mut coin: Value = self.safe_string_k(trade.clone(), "coin", &[]);
let mut marketId: Value = self.coin_to_market_id(coin).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut marketResolved: Value = self.safe_market(&[marketId]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut id: Value = self.safe_string_k(trade.clone(), "tid", &[]);
let mut side: Value = self.safe_string_k(trade.clone(), "side", &[]);
if (side != Value::Null) {
side = (if (side.as_str() == Some("A")) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
}
let mut fee: Value = self.safe_string_k(trade.clone(), "fee", &[]);
let mut takerOrMaker: Value = Value::Null;
let mut crossed: Value = self.safe_bool_k(trade.clone(), "crossed", &[]);
if (crossed != Value::Null) {
takerOrMaker = (if crossed.as_bool() == Some(true) { Value::Str("taker".into()) } else { Value::Str("maker".into()) });
}
let mut builderFee: Value = self.safe_string_k(trade.clone(), "builderFee", &[]);
if (builderFee != Value::Null) {
fee = crate::precise::Precise::stringAdd(&fee, &builderFee);
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), symbol);
m.insert("id".to_string(), id);
m.insert("order".to_string(), self.safe_string_k(trade.clone(), "oid", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), fee);
m.insert("currency".to_string(), self.safe_string_k(trade, "feeToken", &[]));
m.insert("rate".to_string(), Value::Null);
m
}));
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchPosition
* @description fetch data on an open position
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-users-perpetuals-account-summary
* @param {string} symbol unified market symbol of the market the position is held in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] user address, will default to this.walletAddress if not provided
* @returns {object} a [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut positions: Value = self.fetch_positions(&[Value::from(vec![symbol]), params]).await;
return self.safe_dict(positions, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
Value::Null
}
pub fn get_dex_from_symbols(&self, mut methodName: Value, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
if (symbols == Value::Null) {
return Value::Null;
}
let mut symbolsLength: f64 = ((symbols.len() as i64) as f64);
if (symbolsLength == 0.0) {
return Value::Null;
}
let mut dexName: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_820: bool = true;
while { if !__for_first_820 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_820 = false; i.as_f64().unwrap_or(f64::NAN) < symbolsLength } {
if (dexName == Value::Null) {
let mut market: Value = self.market(symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
dexName = self.get_dex_from_hip3_symbol(market.clone());
} else {
let mut market: Value = self.market(symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
let mut currentDexName: Value = self.get_dex_from_hip3_symbol(market);
if (currentDexName.as_str() != dexName.as_str()) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), methodName).into()), Value::Str(" only supports fetching positions for one DEX at a time for HIP3 markets".into()))));
}
}
}
}
return dexName;
Value::Null
}
/*
* @method
* @name hyperliquid#fetchPositions
* @description fetch all open positions
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-users-perpetuals-account-summary
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] user address, will default to this.walletAddress if not provided
* @param {string} [params.subAccountAddress] sub account user address
* @param {string} [params.dex] perp dex name, eg: XYZ
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddressparamsPublicAddressVariable = self.handle_public_address(Value::Str("fetchPositions".into()), params);
let mut userAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPublicAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("clearinghouseState".into()));
m.insert("user".to_string(), userAddress);
m
});
let mut dexName: Value = self.get_dex_from_symbols(Value::Str("fetchPositions".into()), &[symbolsNormalized.clone()]);
if (dexName != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("dex".into(), dexName); }
}
let __ws_arg_27 = self.extend(request, &[paramsPublicAddress]);
let mut response: Value = self.public_post_info(&[__ws_arg_27]).await;
//
// {
// "assetPositions": [
// {
// "position": {
// "coin": "ETH",
// "cumFunding": {
// "allTime": "0.0",
// "sinceChange": "0.0",
// "sinceOpen": "0.0"
// },
// "entryPx": "2213.9",
// "leverage": {
// "rawUsd": "-475.23904",
// "type": "isolated",
// "value": "20"
// },
// "liquidationPx": "2125.00856238",
// "marginUsed": "24.88097",
// "maxLeverage": "50",
// "positionValue": "500.12001",
// "returnOnEquity": "0.0",
// "szi": "0.2259",
// "unrealizedPnl": "0.0"
// },
// "type": "oneWay"
// }
// ],
// "crossMaintenanceMarginUsed": "0.0",
// "crossMarginSummary": {
// "accountValue": "100.0",
// "totalMarginUsed": "0.0",
// "totalNtlPos": "0.0",
// "totalRawUsd": "100.0"
// },
// "marginSummary": {
// "accountValue": "100.0",
// "totalMarginUsed": "0.0",
// "totalNtlPos": "0.0",
// "totalRawUsd": "100.0"
// },
// "time": "1704261007014",
// "withdrawable": "100.0"
// }
//
let mut data: Value = self.safe_list_k(response, "assetPositions", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_821: bool = true;
while { if !__for_first_821 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_821 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
append_to_array(&mut result, self.parse_position(data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[]));
}
}
return self.filter_by_array_positions(result, Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "position": {
// "coin": "ETH",
// "cumFunding": {
// "allTime": "0.0",
// "sinceChange": "0.0",
// "sinceOpen": "0.0"
// },
// "entryPx": "2213.9",
// "leverage": {
// "rawUsd": "-475.23904",
// "type": "isolated",
// "value": "20"
// },
// "liquidationPx": "2125.00856238",
// "marginUsed": "24.88097",
// "maxLeverage": "50",
// "positionValue": "500.12001",
// "returnOnEquity": "0.0",
// "szi": "0.2259",
// "unrealizedPnl": "0.0"
// },
// "type": "oneWay"
// }
//
let mut entry: Value = self.safe_dict_k(position.clone(), "position", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut coin: Value = self.safe_string_k(entry.clone(), "coin", &[]);
let mut marketId: Value = self.coin_to_market_id(coin).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut marketResolved: Value = self.safe_market(&[marketId]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut leverage: Value = self.safe_dict_k(entry.clone(), "leverage", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marginMode: Value = self.safe_string_k(leverage.clone(), "type", &[]);
let mut isIsolated: Value = (Value::Bool(marginMode.as_str() == Some("isolated")));
let mut rawSize: Value = self.safe_string_k(entry.clone(), "szi", &[]);
let mut size: Value = rawSize.clone();
let mut side: Value = Value::Null;
if (size != Value::Null) {
side = (if is_true(&crate::precise::Precise::stringGt(&rawSize, &Value::Str("0".into()))) { Value::Str("long".into()) } else { Value::Str("short".into()) });
size = crate::precise::Precise::stringAbs(&size);
}
let mut rawUnrealizedPnl: Value = self.safe_string_k(entry.clone(), "unrealizedPnl", &[]);
let mut absRawUnrealizedPnl: Value = crate::precise::Precise::stringAbs(&rawUnrealizedPnl);
let mut marginUsed: Value = self.safe_string_k(entry.clone(), "marginUsed", &[]);
let mut initialMargin: Value = Value::Null;
if matches!(&isIsolated, Value::Bool(true)) {
initialMargin = crate::precise::Precise::stringSub(&marginUsed, &rawUnrealizedPnl);
} else {
initialMargin = marginUsed.clone();
}
let mut percentage: Value = crate::precise::Precise::stringMul(&crate::precise::Precise::stringDiv(&absRawUnrealizedPnl, &marginUsed), &Value::Str("100".into()));
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position);
m.insert("id".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("isolated".to_string(), isIsolated);
m.insert("hedged".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("contracts".to_string(), self.parse_number(size, &[]));
m.insert("contractSize".to_string(), Value::Null);
m.insert("entryPrice".to_string(), self.safe_number_k(entry.clone(), "entryPx", &[]));
m.insert("markPrice".to_string(), Value::Null);
m.insert("notional".to_string(), self.safe_number_k(entry.clone(), "positionValue", &[]));
m.insert("leverage".to_string(), self.safe_number_k(leverage, "value", &[]));
m.insert("collateral".to_string(), self.parse_number(marginUsed, &[]));
m.insert("initialMargin".to_string(), self.parse_number(initialMargin, &[]));
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("unrealizedPnl".to_string(), self.parse_number(rawUnrealizedPnl, &[]));
m.insert("liquidationPrice".to_string(), self.safe_number_k(entry, "liquidationPx", &[]));
m.insert("marginMode".to_string(), marginMode);
m.insert("percentage".to_string(), self.parse_number(percentage, &[]));
m
}));
Value::Null
}
/*
* @method
* @name hyperliquid#setMarginMode
* @description set margin mode (symbol)
* @param {string} marginMode margin mode must be either [isolated, cross]
* @param {string} symbol unified market symbol of the market the position is held in, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.leverage] the rate of leverage, is required if setting trade mode (symbol)
* @param {string} [params.vaultAddress] the vault address
* @param {string} [params.subAccountAddress] sub account user address
* @returns {object} response from the exchange
*/
pub async fn set_margin_mode(&mut self, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut leverage: Value = self.safe_integer_k(params.clone(), "leverage", &[]);
if (leverage == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires a leverage parameter".into()))));
}
let mut asset: Value = self.parse_to_int(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null));
let mut isCross: Value = (Value::Bool(marginMode.as_str() == Some("cross")));
let mut nonce: Value = self.incrementing_nonce();
let mut params2: Value = self.omit(params, Value::from(vec![Value::Str("leverage".into())]), &[]);
let mut updateAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("updateLeverage".into()));
m.insert("asset".to_string(), asset);
m.insert("isCross".to_string(), isCross);
m.insert("leverage".to_string(), leverage);
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_string_and_params2(params2.clone(), Value::Str("setMarginMode".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]); vaultAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (vaultAddress != Value::Null) {
if (starts_with(&vaultAddress, &Value::Str("0x".into()))) {
vaultAddress = replace_str(&vaultAddress, &Value::Str("0x".into()), &Value::Str("".into()));
}
}
let mut signature: Value = self.sign_l1_action(updateAction.clone(), nonce.clone(), &[vaultAddress.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), updateAction);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("vaultAddress".into(), vaultAddress); }
}
let mut response: Value = self.private_post_exchange(&[request]).await;
return response;
Value::Null
}
/*
* @method
* @name hyperliquid#setLeverage
* @description set the level of leverage for a market
* @param {float} leverage the rate of leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.marginMode] margin mode must be either [isolated, cross], default is cross
* @returns {object} response from the exchange
*/
pub async fn set_leverage(&mut self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut marginMode: Option<String> = self.safe_string_k(params.clone(), "marginMode", &[Value::Str("cross".into())]).as_str().map(str::to_owned);
let mut isCross: Value = (Value::Bool(marginMode.as_deref() == Some("cross")));
let mut asset: Value = self.parse_to_int(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null));
let mut nonce: Value = self.incrementing_nonce();
let mut params2: Value = self.omit(params, Value::Str("marginMode".into()), &[]);
let mut updateAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("updateLeverage".into()));
m.insert("asset".to_string(), asset);
m.insert("isCross".to_string(), isCross);
m.insert("leverage".to_string(), leverage);
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_string_and_params2(params2.clone(), Value::Str("setLeverage".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]); vaultAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut signature: Value = self.sign_l1_action(updateAction.clone(), nonce.clone(), &[vaultAddress.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), updateAction);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
params2 = self.omit(params2, Value::Str("vaultAddress".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("vaultAddress".into(), vaultAddress); }
}
let mut response: Value = self.private_post_exchange(&[request]).await;
return response;
Value::Null
}
/*
* @method
* @name hyperliquid#addMargin
* @description add margin
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#update-isolated-margin
* @param {string} symbol unified market symbol
* @param {float} amount amount of margin to add
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.vaultAddress] the vault address
* @param {string} [params.subAccountAddress] sub account user address
* @returns {object} a [margin structure]{@link https://docs.ccxt.com/?id=margin-structure}
*/
pub async fn add_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.modify_margin_helper(symbol, amount, Value::Str("add".into()), &[params]).await;
Value::Null
}
/*
* @method
* @name hyperliquid#reduceMargin
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#update-isolated-margin
* @description remove margin from a position
* @param {string} symbol unified market symbol
* @param {float} amount the amount of margin to remove
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.vaultAddress] the vault address
* @param {string} [params.subAccountAddress] sub account user address
* @returns {object} a [margin structure]{@link https://docs.ccxt.com/?id=margin-structure}
*/
pub async fn reduce_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.modify_margin_helper(symbol, amount, Value::Str("reduce".into()), &[params]).await;
Value::Null
}
pub async fn modify_margin_helper(&mut self, mut symbol: Value, mut amount: Value, mut type_var: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut asset: Value = self.parse_to_int(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null));
let mut sz: Value = self.parse_to_int(crate::precise::Precise::stringMul(&self.amount_to_precision(symbol, amount), &Value::Str("1000000".into())));
if (type_var.as_str() == Some("reduce")) {
sz = negate(&sz);
}
let mut nonce: Value = self.incrementing_nonce();
let mut updateAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("updateIsolatedMargin".into()));
m.insert("asset".to_string(), asset);
m.insert("isBuy".to_string(), Value::Bool(true));
m.insert("ntli".to_string(), sz);
m
});
let mut vaultAddressOption: Value = self.handle_option_string_and_params2(params, Value::Str("modifyMargin".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut vaultAddress: Value = self.format_vault_address(&[vaultAddressOption]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut signature: Value = self.sign_l1_action(updateAction.clone(), nonce.clone(), &[vaultAddress.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), updateAction);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("vaultAddress".into(), vaultAddress); }
}
let mut response: Value = self.private_post_exchange(&[request]).await;
let __ws_arg_28 = self.parse_margin_modification(response.clone(), &[market]);
let __ws_arg_29 = self.safe_string_k(response, "status", &[]);
return self.extend(__ws_arg_28, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("code".to_string(), __ws_arg_29);
m
})]);
Value::Null
}
pub fn parse_margin_modification(&self, mut data: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data);
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market.clone()]));
m.insert("type".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Str("isolated".into()));
m.insert("amount".to_string(), Value::Null);
m.insert("total".to_string(), Value::Null);
m.insert("code".to_string(), self.safe_string_k(market, "settle", &[]));
m.insert("status".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name hyperliquid#transfer
* @description transfer currency internally between wallets on the same account
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#l1-usdc-transfer
* @param {string} code unified currency code
* @param {float} amount amount to transfer
* @param {string} fromAccount account to transfer from *spot, swap*
* @param {string} toAccount account to transfer to *swap, spot or address*
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.vaultAddress] the vault address for order
* @returns {object} a [transfer structure]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn transfer(&mut self, mut code: Value, mut amount: Value, mut fromAccount: Value, mut toAccount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut isSandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[]);
let mut nonce: Value = self.incrementing_nonce();
if self.in_array(fromAccount.clone(), Value::from(vec![Value::Str("spot".into()), Value::Str("swap".into()), Value::Str("perp".into())])).as_bool() == Some(true) {
// handle swap <> spot account transfer
if !(self.in_array(toAccount.clone(), Value::from(vec![Value::Str("spot".into()), Value::Str("swap".into()), Value::Str("perp".into())])).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" transfer() only support spot <> swap transfer".into()))));
}
let mut strAmount: Value = self.number_to_string(amount.clone());
let mut vaultAddress: Value = self.safe_string2(params.clone(), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]);
if (vaultAddress != Value::Null) {
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
strAmount = Value::Str(format!("{}{}", Value::Str(format!("{}{}", strAmount, Value::Str(" subaccount:".into())).into()), vaultAddress).into());
}
let mut strAmountFinal: Value = strAmount; // java req
let mut toPerp: Value = Value::Bool((toAccount.as_str() == Some("perp")) || (toAccount.as_str() == Some("swap")));
let mut transferPayload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), (if (isSandboxMode.as_bool() == Some(true)) { Value::Str("Testnet".into()) } else { Value::Str("Mainnet".into()) }));
m.insert("amount".to_string(), strAmountFinal.clone());
m.insert("toPerp".to_string(), toPerp.clone());
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut transferSig: Value = self.build_usd_class_send_sig(transferPayload.clone());
let mut transferRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), match &transferPayload { Value::Dict(__m15) => __m15.get("hyperliquidChain").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".into()));
m.insert("type".to_string(), Value::Str("usdClassTransfer".into()));
m.insert("amount".to_string(), strAmountFinal);
m.insert("toPerp".to_string(), toPerp);
m.insert("nonce".to_string(), nonce.clone());
m
}));
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), transferSig);
m
});
let mut transferResponse: Value = self.private_post_exchange(&[transferRequest]).await;
//
// {'response': {'type': 'default'}, 'status': 'ok'}
//
// the sub-account branches below already hand back the unified structure; the
// spot <> swap branch returned the raw acknowledgement, breaking the shape
let mut currency: Value = self.safe_currency(code.clone(), &[]);
return self.parse_transfer(transferResponse, &[currency.clone()]);
}
// transfer between main account and subaccount
let mut isDeposit: Value = Value::Bool(false);
let mut subAccountAddress: Value = Value::Null;
if (fromAccount.as_str() == Some("main")) {
subAccountAddress = toAccount.clone();
isDeposit = Value::Bool(true);
} else if (toAccount.as_str() == Some("main")) {
subAccountAddress = fromAccount;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" transfer() only support main <> subaccount transfer".into()))));
}
self.check_address(&[subAccountAddress.clone()]);
// hyperliquid keeps separate perp and spot ledgers for sub-account transfers: subAccountTransfer
// moves perp USD, while subAccountSpotTransfer moves spot tokens (USDC included) - pass
// params['type'] = 'spot' to move spot USDC, see https://github.com/ccxt/ccxt/issues/27029
let mut transferType: Option<String> = self.safe_string_k(params, "type", &[]).as_str().map(str::to_owned);
let mut isUsdc: bool = to_upper(&code).as_str() == Some("USDC");
if isUsdc && (transferType.as_deref() != Some("spot")) {
// Transfer USDC with subAccountTransfer
let mut usd: Value = self.parse_to_int(crate::precise::Precise::stringMul(&self.number_to_string(amount.clone()), &Value::Str("1000000".into())));
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("subAccountTransfer".into()));
m.insert("subAccountUser".to_string(), subAccountAddress.clone());
m.insert("isDeposit".to_string(), isDeposit.clone());
m.insert("usd".to_string(), usd);
m
});
let mut sig: Value = self.sign_l1_action(action.clone(), nonce.clone(), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), action.clone());
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), sig.clone());
m
});
let mut response: Value = self.private_post_exchange(&[request.clone()]).await;
return self.parse_transfer(response.clone(), &[]);
} else {
// Transfer spot tokens (including spot USDC) with subAccountSpotTransfer - the api
// expects the token as "NAME:tokenId", e.g. "USDC:0x6d1e7cde53ba9467b783cb7c530ce054"
if (code == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" transfer() requires a currency code for spot sub-account transfers".into()))));
}
let mut currency: Value = self.currency(code);
let mut currencyInfo: Value = self.safe_dict_k(currency, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut tokenName: Value = self.safe_string_k(currencyInfo.clone(), "name", &[]);
let mut tokenId: Value = self.safe_string_k(currencyInfo, "tokenId", &[]);
let mut token: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", tokenName, Value::Str(":".into())).into()), tokenId).into());
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("subAccountSpotTransfer".into()));
m.insert("subAccountUser".to_string(), subAccountAddress);
m.insert("isDeposit".to_string(), isDeposit);
m.insert("token".to_string(), token);
m.insert("amount".to_string(), self.number_to_string(amount));
m
});
let mut sig: Value = self.sign_l1_action(action.clone(), nonce.clone(), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), action);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), sig);
m
});
let mut response: Value = self.private_post_exchange(&[request]).await;
return self.parse_transfer(response, &[]);
}
Value::Null
}
pub fn parse_transfer(&self, mut transfer: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transfer.clone());
m.insert("id".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("currency".to_string(), self.safe_currency_code(Value::Null, &[currency]));
m.insert("amount".to_string(), Value::Null);
m.insert("fromAccount".to_string(), Value::Null);
m.insert("toAccount".to_string(), Value::Null);
m.insert("status".to_string(), self.safe_string_k(transfer, "status", &[Value::Str("ok".into())]));
m
});
Value::Null
}
/*
* @method
* @name hyperliquid#withdraw
* @description make a withdrawal (only support USDC)
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#initiate-a-withdrawal-request
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#deposit-or-withdraw-from-a-vault
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {string} tag
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.vaultAddress] vault address withdraw from
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut tag = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.check_address(&[address.clone()]);
if (to_upper(&code).as_str() != Some("USDC")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" withdraw() only support USDC".into()))));
}
let mut vaultAddressOption: Value = self.handle_option_string_and_params(params, Value::Str("withdraw".into()), Value::Str("vaultAddress".into()), &[]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut vaultAddress: Value = self.format_vault_address(&[vaultAddressOption]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut nonce: Value = self.incrementing_nonce();
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut sig: Value = Value::Null;
if (vaultAddress != Value::Null) {
action = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("vaultTransfer".into()));
m.insert("vaultAddress".to_string(), Value::Str(format!("{}{}", Value::Str("0x".into()), vaultAddress).into()));
m.insert("isDeposit".to_string(), Value::Bool(false));
m.insert("usd".to_string(), amount.clone());
m
});
sig = self.sign_l1_action(action.clone(), nonce.clone(), &[]);
} else {
let mut isSandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), (if (isSandboxMode.as_bool() == Some(true)) { Value::Str("Testnet".into()) } else { Value::Str("Mainnet".into()) }));
m.insert("destination".to_string(), address.clone());
m.insert("amount".to_string(), to_string_val(&amount));
m.insert("time".to_string(), nonce.clone());
m
});
sig = self.build_withdraw_sig(payload.clone());
action = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), match &payload { Value::Dict(__m15) => __m15.get("hyperliquidChain").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".into()));
m.insert("destination".to_string(), address);
m.insert("amount".to_string(), to_string_val(&amount));
m.insert("time".to_string(), nonce.clone());
m.insert("type".to_string(), Value::Str("withdraw3".into()));
m
});
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), action);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), sig);
m
});
let mut response: Value = self.private_post_exchange(&[request]).await;
return self.parse_transaction(response, &[]);
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// { status: 'ok', response: { type: 'default' } }
//
// fetchDeposits / fetchWithdrawals
// {
// "time":1724762307531,
// "hash":"0x620a234a7e0eb7930575040f59482a01050058b0802163b4767bfd9033e77781",
// "delta":{
// "type":"accountClassTransfer",
// "usdc":"50.0",
// "toPerp":false
// }
// }
//
let mut timestamp: Value = self.safe_integer_k(transaction.clone(), "time", &[]);
let mut delta: Value = self.safe_dict_k(transaction.clone(), "delta", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fee: Value = Value::Null;
let mut feeCost: Value = self.safe_integer_k(delta.clone(), "fee", &[]);
if (feeCost != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Str("USDC".into()));
m.insert("cost".to_string(), feeCost);
m
});
}
let mut internal: Value = Value::Null;
let mut type_var: Option<String> = self.safe_string_k(delta.clone(), "type", &[]).as_str().map(str::to_owned);
if (type_var.is_some()) {
internal = (Value::Bool(type_var.as_deref() == Some("internalTransfer")));
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), Value::Null);
m.insert("txid".to_string(), self.safe_string_k(transaction.clone(), "hash", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("network".to_string(), Value::Null);
m.insert("address".to_string(), Value::Null);
m.insert("addressTo".to_string(), self.safe_string_k(delta.clone(), "destination", &[]));
m.insert("addressFrom".to_string(), self.safe_string_k(delta.clone(), "user", &[]));
m.insert("tag".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("amount".to_string(), self.safe_number_k(delta, "usdc", &[]));
m.insert("currency".to_string(), Value::Null);
m.insert("status".to_string(), self.safe_string_k(transaction, "status", &[]));
m.insert("updated".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("internal".to_string(), internal);
m.insert("fee".to_string(), fee);
m
});
Value::Null
}
/*
* @method
* @name hyperliquid#fetchTradingFee
* @description fetch the trading fees for a market
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] user address, will default to this.walletAddress if not provided
* @param {string} [params.subAccountAddress] sub account user address
* @returns {object} a [fee structure]{@link https://docs.ccxt.com/?id=fee-structure}
*/
pub async fn fetch_trading_fee(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddressparamsPublicAddressVariable = self.handle_public_address(Value::Str("fetchTradingFee".into()), params);
let mut userAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPublicAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userFees".into()));
m.insert("user".to_string(), userAddress);
m
});
let __ws_arg_30 = self.extend(request, &[paramsPublicAddress]);
let mut response: Value = self.public_post_info(&[__ws_arg_30]).await;
//
// {
// "dailyUserVlm": [
// {
// "date": "2024-07-08",
// "userCross": "0.0",
// "userAdd": "0.0",
// "exchange": "90597185.23639999"
// }
// ],
// "feeSchedule": {
// "cross": "0.00035",
// "add": "0.0001",
// "tiers": {
// "vip": [
// {
// "ntlCutoff": "5000000.0",
// "cross": "0.0003",
// "add": "0.00005"
// }
// ],
// "mm": [
// {
// "makerFractionCutoff": "0.005",
// "add": "-0.00001"
// }
// ]
// },
// "referralDiscount": "0.04"
// },
// "userCrossRate": "0.00035",
// "userAddRate": "0.0001",
// "activeReferralDiscount": "0.0"
// }
//
let mut data: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("userCrossRate".to_string(), self.safe_string_k(response.clone(), "userCrossRate", &[]));
m.insert("userAddRate".to_string(), self.safe_string_k(response, "userAddRate", &[]));
m
});
return self.parse_trading_fee(data, &[market]);
Value::Null
}
pub fn parse_trading_fee(&self, mut fee: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "dailyUserVlm": [
// {
// "date": "2024-07-08",
// "userCross": "0.0",
// "userAdd": "0.0",
// "exchange": "90597185.23639999"
// }
// ],
// "feeSchedule": {
// "cross": "0.00035",
// "add": "0.0001",
// "tiers": {
// "vip": [
// {
// "ntlCutoff": "5000000.0",
// "cross": "0.0003",
// "add": "0.00005"
// }
// ],
// "mm": [
// {
// "makerFractionCutoff": "0.005",
// "add": "-0.00001"
// }
// ]
// },
// "referralDiscount": "0.04"
// },
// "userCrossRate": "0.00035",
// "userAddRate": "0.0001",
// "activeReferralDiscount": "0.0"
// }
//
let mut symbol: Value = self.safe_symbol(Value::Null, &[market]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), fee.clone());
m.insert("symbol".to_string(), symbol);
m.insert("maker".to_string(), self.safe_number_k(fee.clone(), "userAddRate", &[]));
m.insert("taker".to_string(), self.safe_number_k(fee, "userCrossRate", &[]));
m.insert("percentage".to_string(), Value::Null);
m.insert("tierBased".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name hyperliquid#fetchLedger
* @description fetch the history of changes, actions done by the user or operations that altered the balance of the user
* @param {string} [code] unified currency code
* @param {int} [since] timestamp in ms of the earliest ledger entry
* @param {int} [limit] max number of ledger entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest ledger entry
* @param {string} [params.subAccountAddress] sub account user address
* @returns {object} a [ledger structure]{@link https://docs.ccxt.com/?id=ledger-entry-structure}
*/
pub async fn fetch_ledger(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Value = Value::Null;
let mut params2: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchLedger".into()), params); userAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userNonFundingLedgerUpdates".into()));
m.insert("user".to_string(), userAddress);
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
}
let mut until: Value = self.safe_integer_k(params2.clone(), "until", &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
params2 = self.omit(params2.clone(), Value::from(vec![Value::Str("until".into())]), &[]);
}
let __ws_arg_31 = self.extend(request, &[params2]);
let mut response: Value = self.public_post_info(&[__ws_arg_31]).await;
return self.parse_ledger(response, &[Value::Null, since, limit]);
Value::Null
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "time":1724762307531,
// "hash":"0x620a234a7e0eb7930575040f59482a01050058b0802163b4767bfd9033e77781",
// "delta":{
// "type":"accountClassTransfer",
// "usdc":"50.0",
// "toPerp":false
// }
// }
//
let mut timestamp: Value = self.safe_integer_k(item.clone(), "time", &[]);
let mut delta: Value = self.safe_dict_k(item.clone(), "delta", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fee: Value = Value::Null;
let mut feeCost: Value = self.safe_integer_k(delta.clone(), "fee", &[]);
if (feeCost != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Str("USDC".into()));
m.insert("cost".to_string(), feeCost);
m
});
}
let mut type_var: Value = self.safe_string_k(delta.clone(), "type", &[]);
let mut amount: Value = self.safe_string_k(delta.clone(), "usdc", &[]);
return self.safe_ledger_entry(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), item.clone());
m.insert("id".to_string(), self.safe_string_k(item.clone(), "hash", &[]));
m.insert("direction".to_string(), Value::Null);
m.insert("account".to_string(), Value::Null);
m.insert("referenceAccount".to_string(), self.safe_string_k(delta, "user", &[]));
m.insert("referenceId".to_string(), self.safe_string_k(item, "hash", &[]));
m.insert("type".to_string(), self.parse_ledger_entry_type(type_var).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("currency".to_string(), Value::Null);
m.insert("amount".to_string(), self.parse_number(amount, &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("before".to_string(), Value::Null);
m.insert("after".to_string(), Value::Null);
m.insert("status".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
}), &[currency]);
Value::Null
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Option<String> {
let mut ledgerType: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("internalTransfer".to_string(), Value::Str("transfer".into()));
m.insert("accountClassTransfer".to_string(), Value::Str("transfer".into()));
m
});
return self.safe_string(ledgerType, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name hyperliquid#fetchDeposits
* @description fetch all deposits made to an account
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch deposits for
* @param {int} [limit] the maximum number of deposits structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch withdrawals for
* @param {string} [params.subAccountAddress] sub account user address
* @param {string} [params.vaultAddress] vault address
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Value = Value::Null;
let mut params2: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchDepositsWithdrawals".into()), params); userAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userNonFundingLedgerUpdates".into()));
m.insert("user".to_string(), userAddress);
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
}
let mut until: Value = self.safe_integer_k(params2.clone(), "until", &[]);
if (until != Value::Null) {
if (since == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchDeposits requires since while until is set".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
params2 = self.omit(params2.clone(), Value::from(vec![Value::Str("until".into())]), &[]);
}
let __ws_arg_32 = self.extend(request, &[params2.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_32]).await;
//
// [
// {
// "time":1724762307531,
// "hash":"0x620a234a7e0eb7930575040f59482a01050058b0802163b4767bfd9033e77781",
// "delta":{
// "type":"accountClassTransfer",
// "usdc":"50.0",
// "toPerp":false
// }
// }
// ]
//
let mut depositLedger: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
depositLedger = response.clone();
}
let mut records: Value = self.extract_type_from_delta(&[depositLedger]);
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_string_and_params(params2.clone(), Value::Str("fetchDepositsWithdrawals".into()), Value::Str("vaultAddress".into()), &[]); vaultAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut deposits: Value = Value::from(vec![]);
if (vaultAddress != Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_822: bool = true;
while { if !__for_first_822 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_822 = false; i.as_f64().unwrap_or(f64::NAN) < ((records.len() as i64) as f64) } {
let mut record: Value = records.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if (self.safe_string_k(record.clone(), "type", &[]).as_str() == Some("vaultDeposit")) {
let mut delta: Value = self.safe_dict_k(record.clone(), "delta", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if is_equal(&delta.as_map().and_then(|__m| __m.get("vault")).cloned().unwrap_or(Value::Null), &Value::Str(format!("{}{}", Value::Str("0x".into()), vaultAddress).into())) {
append_to_array(&mut deposits, record);
}
}
}
}
} else {
deposits = self.filter_by_array(records, Value::Str("type".into()), &[Value::from(vec![Value::Str("deposit".into())]), Value::Bool(false)]);
}
return self.parse_transactions(deposits, &[Value::Null, since, limit]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch withdrawals for
* @param {int} [limit] the maximum number of withdrawals structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch withdrawals for
* @param {string} [params.subAccountAddress] sub account user address
* @param {string} [params.vaultAddress] vault address
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Value = Value::Null;
let mut params2: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchDepositsWithdrawals".into()), params); userAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userNonFundingLedgerUpdates".into()));
m.insert("user".to_string(), userAddress);
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
}
let mut until: Value = self.safe_integer_k(params2.clone(), "until", &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
params2 = self.omit(params2.clone(), Value::from(vec![Value::Str("until".into())]), &[]);
}
let __ws_arg_33 = self.extend(request, &[params2.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_33]).await;
//
// [
// {
// "time":1724762307531,
// "hash":"0x620a234a7e0eb7930575040f59482a01050058b0802163b4767bfd9033e77781",
// "delta":{
// "type":"accountClassTransfer",
// "usdc":"50.0",
// "toPerp":false
// }
// }
// ]
//
let mut withdrawalLedger: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
withdrawalLedger = response.clone();
}
let mut records: Value = self.extract_type_from_delta(&[withdrawalLedger]);
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_string_and_params(params2.clone(), Value::Str("fetchDepositsWithdrawals".into()), Value::Str("vaultAddress".into()), &[]); vaultAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut withdrawals: Value = Value::from(vec![]);
if (vaultAddress != Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_823: bool = true;
while { if !__for_first_823 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_823 = false; i.as_f64().unwrap_or(f64::NAN) < ((records.len() as i64) as f64) } {
let mut record: Value = records.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if (self.safe_string_k(record.clone(), "type", &[]).as_str() == Some("vaultWithdraw")) {
let mut delta: Value = self.safe_dict_k(record.clone(), "delta", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if is_equal(&delta.as_map().and_then(|__m| __m.get("vault")).cloned().unwrap_or(Value::Null), &Value::Str(format!("{}{}", Value::Str("0x".into()), vaultAddress).into())) {
append_to_array(&mut withdrawals, record);
}
}
}
}
} else {
withdrawals = self.filter_by_array(records, Value::Str("type".into()), &[Value::from(vec![Value::Str("withdraw".into())]), Value::Bool(false)]);
}
return self.parse_transactions(withdrawals, &[Value::Null, since, limit]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchOpenInterests
* @description Retrieves the open interest for a list of symbols
* @param {string[]} [symbols] Unified CCXT market symbol
* @param {object} [params] exchange specific parameters
* @returns {object} an open interest structure{@link https://docs.ccxt.com/?id=open-interest-structure}
*/
pub async fn fetch_open_interests(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut swapMarkets: Value = self.fetch_swap_markets(&[]).await;
return self.parse_open_interests(swapMarkets, &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchOpenInterest
* @description retrieves the open interest of a contract trading pair
* @param {string} symbol unified CCXT market symbol
* @param {object} [params] exchange specific parameters
* @returns {object} an [open interest structure]{@link https://docs.ccxt.com/?id=open-interest-structure}
*/
pub async fn fetch_open_interest(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut symbolValue: Value = self.symbol(symbol.clone());
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut ois: Value = self.fetch_open_interests(&[Value::from(vec![symbolValue.clone()]), params]).await;
let mut openInterest: Value = self.safe_dict(ois, symbolValue, &[]);
return openInterest;
Value::Null
}
pub fn parse_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// szDecimals: '2',
// name: 'HYPE',
// maxLeverage: '3',
// funding: '0.00014735',
// openInterest: '14677900.74',
// prevDayPx: '26.145',
// dayNtlVlm: '299643445.12560016',
// premium: '0.00081613',
// oraclePx: '27.569',
// markPx: '27.63',
// midPx: '27.599',
// impactPxs: [ '27.5915', '27.6319' ],
// dayBaseVlm: '10790652.83',
// baseId: 159
// }
//
let mut interestValue: Value = self.safe_dict_k(interest, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut coin: Value = self.safe_string_k(interestValue.clone(), "name", &[]);
let mut marketId: Value = Value::Null;
if (coin != Value::Null) {
marketId = self.coin_to_market_id(coin).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
}
return self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[]));
m.insert("openInterestAmount".to_string(), self.safe_number_k(interestValue.clone(), "openInterest", &[]));
m.insert("openInterestValue".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("info".to_string(), interestValue);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchFundingHistory
* @description fetch the history of funding payments paid and received on this account
* @param {string} [symbol] unified market symbol
* @param {int} [since] the earliest time in ms to fetch funding history for
* @param {int} [limit] the maximum number of funding history structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subAccountAddress] sub account user address
* @returns {object} a [funding history structure]{@link https://docs.ccxt.com/?id=funding-history-structure}
*/
pub async fn fetch_funding_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut userAddressparamsPublicAddressVariable = self.handle_public_address(Value::Str("fetchFundingHistory".into()), params);
let mut userAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPublicAddress: Value = userAddressparamsPublicAddressVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("user".to_string(), userAddress);
m.insert("type".to_string(), Value::Str("userFunding".into()));
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
}
let mut until: Value = self.safe_integer_k(paramsPublicAddress.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(paramsPublicAddress, Value::Str("until".into()), &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
}
let __ws_arg_34 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.public_post_info(&[__ws_arg_34]).await;
return self.parse_incomes(response, &[market, since, limit]);
Value::Null
}
pub fn parse_income(&self, mut income: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "time": 1734026400057,
// "hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
// "delta": {
// "type": "funding",
// "coin": "SOL",
// "usdc": "75.635093",
// "szi": "-7375.9",
// "fundingRate": "0.00004381",
// "nSamples": null
// }
// }
//
let mut id: Value = self.safe_string_k(income.clone(), "hash", &[]);
let mut timestamp: Value = self.safe_integer_k(income.clone(), "time", &[]);
let mut delta: Value = self.safe_dict_k(income.clone(), "delta", &[]);
let mut coin: Value = self.safe_string_k(delta.clone(), "coin", &[]);
let mut marketId: Value = Value::Null;
if (coin != Value::Null) {
marketId = self.coin_to_market_id(coin).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
}
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut amount: Value = self.safe_string_k(delta.clone(), "usdc", &[]);
let mut code: Value = self.safe_string_k(marketResolved.clone(), "settle", &[Value::Str("USDC".into())]);
let mut rate: Value = self.safe_number_k(delta, "fundingRate", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), income);
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("code".to_string(), code);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("id".to_string(), id);
m.insert("amount".to_string(), self.parse_number(amount, &[]));
m.insert("rate".to_string(), rate);
m
});
Value::Null
}
/*
* @method
* @name hyperliquid#reserveRequestWeight
* @description Instead of trading to increase the address based rate limits, this action allows reserving additional actions for 0.0005 USDC per request. The cost is paid from the Perps balance.
* @param {number} weight the weight to reserve, 1 weight = 1 action, 0.0005 USDC per action
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a response object
*/
pub async fn reserve_request_weight(&mut self, mut weight: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut nonce: Value = self.incrementing_nonce();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("reserveRequestWeight".into()));
m.insert("weight".to_string(), weight);
m
});
let mut signature: Value = self.sign_l1_action(action.clone(), nonce, &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("action".into(), action); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("signature".into(), signature); }
let __ws_arg_35 = self.extend(request, &[params]);
let mut response: Value = self.private_post_exchange(&[__ws_arg_35]).await;
return response;
Value::Null
}
/*
* @method
* @name hyperliquid#createAccount
* @description creates a sub-account under the main account
* @param {string} name the name of the sub-account
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.expiresAfter] time in ms after which the sub-account will expire
* @returns {object} a response object
*/
pub async fn create_sub_account(&mut self, mut name: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut nonce: Value = self.incrementing_nonce();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("createSubAccount".into()));
m.insert("name".to_string(), name);
m
});
let mut expiresAfter: Value = self.safe_integer_k(params.clone(), "expiresAfter", &[]);
if (expiresAfter != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("expiresAfter".into(), expiresAfter.clone()); }
}
let mut signature: Value = self.sign_l1_action(action.clone(), nonce, &[Value::Null, expiresAfter]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("action".into(), action); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("signature".into(), signature); }
let __ws_arg_36 = self.extend(request, &[self.omit(params, Value::Str("expiresAfter".into()), &[])]);
let mut response: Value = self.private_post_exchange(&[__ws_arg_36]).await;
return response;
Value::Null
}
pub fn extract_type_from_delta(&self, optional_args: &[Value]) -> Value {
let mut data = get_arg(optional_args, 0, Value::from(vec![]));
let mut records: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_824: bool = true;
while { if !__for_first_824 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_824 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut record: Value = get_value(&data, &i);
let mut record: Value = get_value(&data, &i);
{ let __be_tmp = crate::value::get_value_k(&crate::value::get_value_k(&record, "delta"), "type"); add_element_to_object(&mut record, &Value::Str("type".into()), __be_tmp); };
append_to_array(&mut records, record);
}
}
return records;
Value::Null
}
pub fn format_vault_address(&self, optional_args: &[Value]) -> Option<String> {
let mut address = get_arg(optional_args, 0, Value::Null);
if (address == Value::Null) {
return None;
}
if (starts_with(&address, &Value::Str("0x".into()))) {
return replace_str(&address, &Value::Str("0x".into()), &Value::Str("".into())).as_str().map(str::to_owned);
}
return address.as_str().map(str::to_owned);
}
pub fn handle_public_address(&self, mut methodName: Value, mut params: Value) -> Value {
let mut userAuxparamsUserVariable = self.handle_option_string_and_params2(params, methodName.clone(), Value::Str("user".into()), Value::Str("subAccountAddress".into()), &[]);
let mut userAux: Value = userAuxparamsUserVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUser: Value = userAuxparamsUserVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut userparamsAddressVariable = self.handle_option_string_and_params(paramsUser, methodName.clone(), Value::Str("address".into()), &[userAux]);
let mut user: Value = userparamsAddressVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAddress: Value = userparamsAddressVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (user != Value::Null) && (user.as_str() != Some("")) {
return Value::from(vec![user, paramsAddress.clone()]);
}
if (self.walletAddress.clone() != Value::Null) && (self.walletAddress.as_str() != Some("")) {
return Value::from(vec![self.walletAddress.clone(), paramsAddress]);
}
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), methodName).into()), Value::Str("() requires a user parameter inside 'params' or the wallet address set".into()))));
Value::Null
}
pub fn coin_to_market_id(&self, mut coin: Value) -> Option<String> {
// handle also hip3 tokens like flx:CRCL
if (coin == Value::Null) {
return None;
}
let mut hi3TokensByname: Value = self.safe_dict_k(self.options.clone(), "hip3TokensByName", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (self.safe_dict(hi3TokensByname.clone(), coin.clone(), &[]) != Value::Null) {
let mut hip3Dict: Value = self.safe_dict(hi3TokensByname, coin.clone(), &[]);
let mut quote: Value = self.safe_string_k(hip3Dict.clone(), "quote", &[Value::Str("USDC".into())]);
let mut code: Value = self.safe_string_k(hip3Dict, "code", &[coin.clone()]);
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", code, Value::Str("/".into())).into()), quote).into()), Value::Str(":".into())).into()), quote).into()).as_str().map(str::to_owned);
}
if Value::Int(coin.as_str().and_then(|__s| __s.find("/")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64) || Value::Int(coin.as_str().and_then(|__s| __s.find("@")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64) {
return coin.as_str().map(str::to_owned);
}
// hip3
let mut coinId: Value = coin.clone();
if Value::Int(coin.as_str().and_then(|__s| __s.find(":")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64) {
coinId = replace_str(&coin, &Value::Str(":".into()), &Value::Str("-".into()));
}
return Value::Str(format!("{}{}", self.safe_currency_code(coinId, &[]), Value::Str("/USDC:USDC".into())).into()).as_str().map(str::to_owned);
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) || (response == Value::Null) {
return Value::Null;
}
// {"status":"err","response":"User or API Wallet 0xb8a6f8b26223de27c31938d56e470a5b832703a5 does not exist."}
//
// {
// status: 'ok',
// response: { type: 'order', data: { statuses: [ { error: 'Insufficient margin to place order. asset=4' } ] } }
// }
// {"status":"ok","response":{"type":"order","data":{"statuses":[{"error":"Insufficient margin to place order. asset=84"}]}}}
//
// {"status":"unknownOid"}
//
let mut status: Option<String> = self.safe_string_k(response.clone(), "status", &[Value::Str("".into())]).as_str().map(str::to_owned);
let mut error: Value = self.safe_string_k(response.clone(), "error", &[]);
let mut message: Value = Value::Null;
if (status.as_deref() == Some("err")) {
message = self.safe_string_k(response.clone(), "response", &[]);
} else if (status.as_deref() == Some("unknownOid")) {
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body)));
} else if (error != Value::Null) {
message = error;
} else {
let mut responsePayload: Value = self.safe_dict_k(response, "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(responsePayload, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut statuses: Value = self.safe_list_k(data.clone(), "statuses", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_825: bool = true;
while { if !__for_first_825 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_825 = false; i.as_f64().unwrap_or(f64::NAN) < ((statuses.len() as i64) as f64) } {
message = self.safe_string(statuses.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), Value::Str("error".into()), &[]);
if (message != Value::Null) {
break;
}
}
}
if (matches!(&data, Value::Dict(__d) if __d.contains_key("status"))) {
let mut errorStatus: Value = self.safe_dict_k(data, "status", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut errorMsg: Value = self.safe_string_k(errorStatus.clone(), "error", &[]);
if (errorStatus != Value::Null) {
message = errorMsg;
}
}
}
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
let mut nonEmptyMessage: bool = (message != Value::Null) && (message.as_str() != Some(""));
if nonEmptyMessage {
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), message.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), message, feedback.clone());
}
if nonEmptyMessage {
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::Str("public".into()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut apiUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), api, &[]);
if (apiUrl == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.implode_hostname(apiUrl), Value::Str("/".into())).into()), path).into());
let mut isPost: bool = method.as_str() == Some("POST");
let mut postHeaders: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Content-Type".to_string(), Value::Str("application/json".into()));
m
});
let mut requestHeaders: Value = headers;
if isPost {
requestHeaders = postHeaders;
}
let mut requestBody: Value = body;
if isPost {
requestBody = json_stringify(¶ms);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), requestBody);
m.insert("headers".to_string(), requestHeaders);
m
});
Value::Null
}
pub fn calculate_rate_limiter_cost(&self, mut api: Value, mut method: Value, mut path: Value, mut params: Value, optional_args: &[Value]) -> Value {
let mut config = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __config_empty = indexmap::IndexMap::new();
let config = config.as_map().unwrap_or(&__config_empty);
if (config.contains_key("byType")) && (in_op(¶ms, &Value::Str("type".into()))) {
let mut type_var: Value = crate::value::get_value_k(¶ms, "type");
let mut byType: Value = config.get("byType").cloned().unwrap_or(Value::Null);
if (in_op(&byType, &type_var)) {
return get_value(&byType, &type_var);
}
}
return (match config.get("cost") { Some(__v) if !matches!(__v, Value::Null) && !matches!(__v, Value::Str(__s) if __s.is_empty()) => __v.clone(), _ => Value::Int(1) });
Value::Null
}
pub fn parse_create_edit_order_args(&self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut market: Value = self.market(symbol);
let mut vaultAddress: Value = Value::Null;
let mut params2: Value = Value::Null;
{ let __destr_tmp = self.handle_option_string_and_params2(params, Value::Str("createOrder".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]); vaultAddress = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut symbolValue: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut order: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbolValue);
m.insert("type".to_string(), type_var);
m.insert("side".to_string(), side);
m.insert("amount".to_string(), amount);
m.insert("price".to_string(), price);
m.insert("params".to_string(), params2);
m
});
let mut globalParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (vaultAddress != Value::Null) {
if let Value::Dict(__d) = &mut globalParams { std::sync::Arc::make_mut(__d).insert("vaultAddress".into(), vaultAddress); }
}
if (id != Value::Null) {
if let Value::Dict(__d) = &mut order { std::sync::Arc::make_mut(__d).insert("id".into(), id); }
}
return Value::from(vec![order, globalParams]);
Value::Null
}
}