// 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;
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 parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_ticker(self, ticker, &[market.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone(), method.clone(), params.clone(), headers.clone(), body.clone()])
}
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.get(3..).unwrap_or(&[]).to_vec()[..]),
"add_margin" => self.add_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]).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.get(4..).unwrap_or(&[]).to_vec()[..]),
"cancel_all_orders_after" => self.cancel_all_orders_after(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_orders_for_symbols" => self.cancel_orders_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_orders_request" => self.cancel_orders_request(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"cancel_twap_order" => self.cancel_twap_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"coin_to_market_id" => self.coin_to_market_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"construct_phantom_agent" => self.construct_phantom_agent(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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.get(4..).unwrap_or(&[]).to_vec()[..]).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.get(4..).unwrap_or(&[]).to_vec()[..]),
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"create_orders_request" => self.create_orders_request(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"create_sub_account" => self.create_sub_account(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).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.get(4..).unwrap_or(&[]).to_vec()[..]).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.get(3..).unwrap_or(&[]).to_vec()[..]).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.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"edit_orders" => self.edit_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"edit_orders_request" => self.edit_orders_request(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"enable_user_dex_abstraction" => self.enable_user_dex_abstraction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"extract_type_from_delta" => self.extract_type_from_delta(&args.get(0..).unwrap_or(&[]).to_vec()[..]),
"fetch_balance" => self.fetch_balance(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_canceled_and_closed_orders" => self.fetch_canceled_and_closed_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_canceled_orders" => self.fetch_canceled_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_currencies" => self.fetch_currencies(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposits" => self.fetch_deposits(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_funding_history" => self.fetch_funding_history(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_funding_rate" => self.fetch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_funding_rates" => self.fetch_funding_rates(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_hip3_markets" => self.fetch_hip3_markets(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ledger" => self.fetch_ledger(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_markets" => self.fetch_markets(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_open_interests" => self.fetch_open_interests(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_orders" => self.fetch_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_positions" => self.fetch_positions(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_spot_markets" => self.fetch_spot_markets(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_status" => self.fetch_status(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_swap_markets" => self.fetch_swap_markets(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_tickers" => self.fetch_tickers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_time" => self.fetch_time(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_trading_fee" => self.fetch_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"format_vault_address" => self.format_vault_address(&args.get(0..).unwrap_or(&[]).to_vec()[..]),
"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.get(1..).unwrap_or(&[]).to_vec()[..]),
"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.get(1..).unwrap_or(&[]).to_vec()[..]).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.get(3..).unwrap_or(&[]).to_vec()[..]).await,
"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.get(5..).unwrap_or(&[]).to_vec()[..]),
"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.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_income" => self.parse_income(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ledger_entry" => self.parse_ledger_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ledger_entry_type" => self.parse_ledger_entry_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_margin_modification" => self.parse_margin_modification(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_open_interest" => self.parse_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_order_type" => self.parse_order_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_trading_fee" => self.parse_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"reserve_request_weight" => self.reserve_request_weight(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"set_agent_abstraction" => self.set_agent_abstraction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"set_margin_mode" => self.set_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"set_ref" => self.set_ref().await,
"set_user_abstraction" => self.set_user_abstraction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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.get(2..).unwrap_or(&[]).to_vec()[..]),
"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.get(4..).unwrap_or(&[]).to_vec()[..]).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.get(3..).unwrap_or(&[]).to_vec()[..]).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".to_string()));
m.insert("name".to_string(), Value::Str("Hyperliquid".to_string()));
m.insert("countries".to_string(), Value::List(vec![]));
m.insert("version".to_string(), Value::Str("v1".to_string()));
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".to_string()));
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".to_string()));
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".to_string()));
m.insert("3m".to_string(), Value::Str("3m".to_string()));
m.insert("5m".to_string(), Value::Str("5m".to_string()));
m.insert("15m".to_string(), Value::Str("15m".to_string()));
m.insert("30m".to_string(), Value::Str("30m".to_string()));
m.insert("1h".to_string(), Value::Str("1h".to_string()));
m.insert("2h".to_string(), Value::Str("2h".to_string()));
m.insert("4h".to_string(), Value::Str("4h".to_string()));
m.insert("8h".to_string(), Value::Str("8h".to_string()));
m.insert("12h".to_string(), Value::Str("12h".to_string()));
m.insert("1d".to_string(), Value::Str("1d".to_string()));
m.insert("3d".to_string(), Value::Str("3d".to_string()));
m.insert("1w".to_string(), Value::Str("1w".to_string()));
m.insert("1M".to_string(), Value::Str("1M".to_string()));
m
}));
m.insert("hostname".to_string(), Value::Str("hyperliquid.xyz".to_string()));
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".to_string()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://api.{hostname}".to_string()));
m.insert("private".to_string(), Value::Str("https://api.{hostname}".to_string()));
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".to_string()));
m.insert("private".to_string(), Value::Str("https://api.hyperliquid-testnet.xyz".to_string()));
m
}));
m.insert("www".to_string(), Value::Str("https://hyperliquid.xyz".to_string()));
m.insert("doc".to_string(), Value::Str("https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api".to_string()));
m.insert("fees".to_string(), Value::Str("https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees".to_string()));
m.insert("referral".to_string(), Value::Str("https://app.hyperliquid.xyz/".to_string()));
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(20));
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".to_string()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.00015".to_string()), &[]));
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".to_string()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.0004".to_string()), &[]));
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".to_string()).clone());
m.insert("Order must have minimum value of $10".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("Insufficient margin to place order.".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("Reduce only order would increase position.".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("Post only order would have immediately matched,".to_string(), Value::Str("InvalidOrder".to_string()));
m.insert("Order could not immediately match against any resting orders.".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("Invalid TP/SL price.".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("No liquidity available for market order.".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("Order was never placed, already canceled, or filled.".to_string(), Value::Str("OrderNotFound".to_string()));
m.insert("User or API Wallet ".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("Order has invalid size".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("Order price cannot be more than 80% away from the reference price".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("Order has zero size.".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("Insufficient spot balance asset".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("Insufficient balance for withdrawal".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("Insufficient balance for token transfer".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("TWAP order value too small. Min is $1200, which is $10 per minute.".to_string(), Value::Str("InvalidOrder".to_string()));
m.insert("TWAP was never placed, already canceled, or filled.".to_string(), Value::Str("OrderNotFound".to_string()));
m.insert("Too many cumulative requests sent".to_string(), Value::Str("RateLimitExceeded".to_string()).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".to_string()));
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::List(vec![Value::Str("hip3TokensByName".to_string()), Value::Str("cachedCurrenciesById".to_string())]));
m.insert("zeroAddress".to_string(), Value::Str("0x0000000000000000000000000000000000000000".to_string()));
m.insert("spotCurrencyMapping".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("UDZ".to_string(), Value::Str("2Z".to_string()));
m.insert("UBONK".to_string(), Value::Str("BONK".to_string()));
m.insert("UBTC".to_string(), Value::Str("BTC".to_string()));
m.insert("UETH".to_string(), Value::Str("ETH".to_string()));
m.insert("UFART".to_string(), Value::Str("FARTCOIN".to_string()));
m.insert("HPENGU".to_string(), Value::Str("PENGU".to_string()));
m.insert("UPUMP".to_string(), Value::Str("PUMP".to_string()));
m.insert("USOL".to_string(), Value::Str("SOL".to_string()));
m.insert("UUUSPX".to_string(), Value::Str("SPX".to_string()));
m.insert("USDT0".to_string(), Value::Str("USDT".to_string()));
m.insert("XAUT0".to_string(), Value::Str("XAUT".to_string()));
m.insert("UXPL".to_string(), Value::Str("XPL".to_string()));
m
}));
m.insert("fetchMarkets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("types".to_string(), Value::List(vec![Value::Str("spot".to_string()), Value::Str("swap".to_string()), Value::Str("hip3".to_string())]));
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::List(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".to_string()));
m
}));
m.insert("forPerps".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".to_string()));
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".to_string()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forPerps".to_string()));
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".to_string()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forPerps".to_string()));
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());
add_element_to_object(&mut self.options, &Value::Str("sandboxMode".to_string()), enabled.clone());
}
pub fn market(&self, mut symbol: Value) -> Value {
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" market() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" markets not loaded".to_string()))));
}
if is_true(&(!is_equal(&symbol, &Value::Null))) && !is_true(&(Value::Bool(in_op(&self.markets, &symbol)))) {
let mut symbolParts: Value = split(&symbol, &Value::Str("/".to_string()));
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 is_true(&Value::Bool(in_op(&spotCurrencyMapping, &baseName))) {
let mut unifiedBaseName: Value = self.safe_string(spotCurrencyMapping.clone(), baseName.clone(), &[]);
let mut quote: Value = self.safe_string(symbolParts.clone(), Value::Int(1), &[]);
let mut newSymbol: Value = add(&add(&self.safe_currency_code(unifiedBaseName.clone(), &[]), &Value::Str("/".to_string())), "e);
if is_true(&Value::Bool(in_op(&self.markets, &newSymbol))) {
return get_value(&self.markets, &newSymbol);
}
}
}
return self.super_market(symbol.clone());
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".to_string()));
m
});
let __ws_arg_0 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_0]).await;
//
// {
// "status": "ok"
// }
//
let mut status: Value = self.safe_string_k(response.clone(), "specialStatuses", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), ternary(is_true(&(is_equal(&status, &Value::Null))), Value::Str("ok".to_string()), Value::Str("maintenance".to_string())));
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.clone());
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".to_string()));
m
});
let __ws_arg_1 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_1]).await;
return self.safe_integer_k(response.clone(), "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 is_true(&self.check_required_credentials(&[Value::Bool(false)])) {
self.initialize_client().await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("spotMeta".to_string()));
m
});
let __ws_arg_2 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "tokens", &[Value::List(vec![])]);
// const meta = this.safeList (response, 'universe', []);
add_element_to_object(&mut self.options, &Value::Str("cachedCurrenciesById".to_string()), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})); // used to map hip3 markets
return self.parse_currencies(tokens.clone());
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".to_string())), &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.clone());
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".to_string()));
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.clone(), "fullName", &[]);
if !is_equal(&fullName, &Value::Null) && !is_equal(&name, &Value::Null) {
let mut isWrapped: bool = is_true(&Value::Bool(starts_with(&fullName, &Value::Str("Unit ".to_string())))) && is_true(&Value::Bool(starts_with(&name, &Value::Str("U".to_string()))));
if is_true(&isWrapped) {
let mut parts: Value = split(&name, &Value::Str("U".to_string()));
let mut nameWithoutU: Value = Value::Str("".to_string());
{
let mut j: Value = Value::Int(0);
let mut __for_first_789: bool = true;
while { if !__for_first_789 { j = add(&j, &Value::Int(1)); } __for_first_789 = false; is_less_than(&j, &get_array_length(&parts)) } {
nameWithoutU = add(&nameWithoutU, &get_value(&parts, &j));
}
}
let mut baseCode: Value = self.safe_currency_code(nameWithoutU.clone(), &[]);
if !is_equal(&code, &Value::Null) {
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("spotCurrencyMapping".to_string())), &code, baseCode.clone());
}
}
}
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.clone(), "types", &[Value::List(vec![])]);
let mut rawPromises: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_790: bool = true;
while { if !__for_first_790 { i = add(&i, &Value::Int(1)); } __for_first_790 = false; is_less_than(&i, &get_array_length(&types)) } {
let mut marketType: Value = get_value(&types, &i);
let mut marketType: Value = get_value(&types, &i);
if is_equal(&marketType, &Value::Str("swap".to_string())) {
append_to_array(&mut rawPromises, self.fetch_swap_markets(&[params.clone()]).await);
} else if is_equal(&marketType, &Value::Str("spot".to_string())) {
append_to_array(&mut rawPromises, self.fetch_spot_markets(&[params.clone()]).await);
} else if is_equal(&marketType, &Value::Str("hip3".to_string())) {
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::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_791: bool = true;
while { if !__for_first_791 { i = add(&i, &Value::Int(1)); } __for_first_791 = false; is_less_than(&i, &get_array_length(&promises)) } {
result = self.array_concat(result.clone(), get_value(&promises, &i));
}
}
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".to_string()));
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_792: bool = true;
while { if !__for_first_792 { i = add(&i, &Value::Int(1)); } __for_first_792 = false; is_less_than(&i, &get_array_length(&fetchDexes)) } {
// 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 = multiply(&(subtract(&i, &Value::Int(1))), &Value::Int(10000));
let mut offset: Value = self.sum(&[Value::Int(110000), secondPart.clone()]);
add_element_to_object(&mut perpDexesOffset, &get_value(&dex, &Value::Str("name".to_string())), offset.clone());
}
}
let mut fetchDexesList: Value = Value::List(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::List(vec![])]); // let users provide their own list of dexes to load
let mut maxLimit: Value = self.safe_integer_k(hip3.clone(), "limit", &[Value::Int(10)]);
let mut userProvidedDexesLength: Value = get_array_length(&dexesProvided);
if is_greater_than(&userProvidedDexesLength, &Value::Int(0)) {
if is_greater_than(&userProvidedDexesLength, &Value::Int(0)) {
fetchDexesList = dexesProvided.clone();
}
} else {
let mut fetchDexesLength: Value = get_array_length(&fetchDexes);
{
let mut i: Value = Value::Int(1);
let mut __for_first_793: bool = true;
while { if !__for_first_793 { i = add(&i, &Value::Int(1)); } __for_first_793 = false; is_less_than(&i, &maxLimit) } {
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 is_equal(&dex, &Value::Null) {
continue;
}
let mut dexName: Value = self.safe_string_k(dex.clone(), "name", &[]);
append_to_array(&mut fetchDexesList, dexName.clone());
}
}
}
let mut rawPromises: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_794: bool = true;
while { if !__for_first_794 { i = add(&i, &Value::Int(1)); } __for_first_794 = false; is_less_than(&i, &get_array_length(&fetchDexesList)) } {
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("metaAndAssetCtxs".to_string()));
m.insert("dex".to_string(), self.safe_string(fetchDexesList.clone(), i.clone(), &[]));
m
});
let __ws_arg_3 = self.extend(request.clone(), &[params.clone()]);
append_to_array(&mut rawPromises, self.public_post_info(&[__ws_arg_3]).await);
}
}
let mut promises: Value = promise_all(&rawPromises).await;
add_element_to_object(&mut self.options, &Value::Str("hip3TokensByName".to_string()), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut markets: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_796: bool = true;
while { if !__for_first_796 { i = add(&i, &Value::Int(1)); } __for_first_796 = false; is_less_than(&i, &get_array_length(&promises)) } {
let mut dexName: Value = get_value(&fetchDexesList, &i);
let mut dexName: Value = get_value(&fetchDexesList, &i);
let mut offset: Value = get_value(&perpDexesOffset, &dexName);
let mut offset: Value = get_value(&perpDexesOffset, &dexName);
let mut response: Value = get_value(&promises, &i);
let mut response: Value = get_value(&promises, &i);
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.clone(), "universe", &[Value::List(vec![])]);
let mut assetCtxs: Value = self.safe_list(response.clone(), Value::Int(1), &[Value::List(vec![])]);
let mut result: Value = Value::List(vec![]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_795: bool = true;
while { if !__for_first_795 { j = add(&j, &Value::Int(1)); } __for_first_795 = false; is_less_than(&j, &get_array_length(&universe)) } {
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".to_string()), self.sum(&[j.clone(), offset.clone()]));
add_element_to_object(&mut data, &Value::Str("collateralToken".to_string()), collateralToken.clone());
add_element_to_object(&mut data, &Value::Str("hip3".to_string()), Value::Bool(true));
add_element_to_object(&mut data, &Value::Str("dex".to_string()), 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 is_true(&Value::Bool(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".to_string()), collateralTokenCode.clone());
// eg: 'flx:crcl' => {'quote': 'USDC', 'code': 'FLX-CRCL'}
let mut safeCode: Value = self.safe_currency_code(name.clone(), &[]);
let mut hip3Code: Value = ternary(is_true(&(is_equal(&safeCode, &Value::Null))), name.clone(), replace_str(&safeCode, &Value::Str(":".to_string()), &Value::Str("-".to_string())));
add_element_to_object(get_value_mut(&mut self.options, &Value::Str("hip3TokensByName".to_string())), &name, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("quote".to_string(), collateralTokenCode.clone());
m.insert("code".to_string(), hip3Code.clone());
m
}));
}
append_to_array(&mut result, data.clone());
}
}
markets = self.array_concat(markets.clone(), self.parse_markets(result.clone()));
}
}
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".to_string()));
m
});
let __ws_arg_6 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "universe", &[Value::List(vec![])]);
let mut assetCtxs: Value = self.safe_list(response.clone(), Value::Int(1), &[Value::List(vec![])]);
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_797: bool = true;
while { if !__for_first_797 { i = add(&i, &Value::Int(1)); } __for_first_797 = false; is_less_than(&i, &get_array_length(&universe)) } {
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".to_string()), i.clone());
append_to_array(&mut result, data.clone());
}
}
return self.parse_markets(result.clone());
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.clone());
if is_equal(&priceStr, &Value::Null) {
return Value::Int(0);
}
let mut priceSplitted: Value = split(&priceStr, &Value::Str(".".to_string()));
if is_true(&crate::precise::Precise::stringEq(&priceStr, &Value::Str("0".to_string()))) {
// 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(&subtract(&maxDecimals, &amountPrecision), &subtract(&significantDigits, &integerDigits));
} else if is_true(&crate::precise::Precise::stringGt(&priceStr, &Value::Str("0".to_string()))) && is_true(&crate::precise::Precise::stringLt(&priceStr, &Value::Str("1".to_string()))) {
// 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("".to_string())]);
// Count the number of leading zeros in the decimal part
let mut leadingZeros: Value = Value::Int(0);
while is_true(&(is_less_than_or_equal(&leadingZeros, &get_array_length(&decimalPart)))) && is_true(&(is_equal(&get_value(&decimalPart, &leadingZeros), &Value::Str("0".to_string())))) {
leadingZeros = add(&leadingZeros, &Value::Int(1));
}
// Calculate price precision based on leading zeros and significant digits
pricePrecision = add(&leadingZeros, &significantDigits);
// Calculate the price precision based on maxDecimals - szDecimals and the calculated price precision from the previous step
pricePrecision = crate::runtime::Math::min(&subtract(&maxDecimals, &amountPrecision), &pricePrecision);
} else {
// Count the numbers before the decimal separator
let mut integerPart: Value = self.safe_string(priceSplitted.clone(), Value::Int(0), &[Value::Str("".to_string())]);
// Get significant digits, take the max() of 5 and the integer digits count
let mut significantDigits: Value = crate::runtime::Math::max(&Value::Int(5), &get_array_length(&integerPart));
// Calculate price precision based on maxDecimals - szDecimals and significantDigits - integerPart.length
pricePrecision = crate::runtime::Math::min(&subtract(&maxDecimals, &amountPrecision), &subtract(&significantDigits, &get_array_length(&integerPart)));
}
return self.parse_to_int(pricePrecision.clone());
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".to_string()));
m
});
let __ws_arg_9 = self.extend(request.clone(), &[params.clone()]);
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.clone(), Value::Int(1), &[Value::List(vec![])]);
let mut meta: Value = self.safe_list_k(first.clone(), "universe", &[Value::List(vec![])]);
let mut tokens: Value = self.safe_list_k(first.clone(), "tokens", &[Value::List(vec![])]);
let mut markets: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_798: bool = true;
while { if !__for_first_798 { i = add(&i, &Value::Int(1)); } __for_first_798 = false; is_less_than(&i, &get_array_length(&meta)) } {
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.clone(), "maker", &[]);
let mut tokensPos: Value = self.safe_list_k(market.clone(), "tokens", &[Value::List(vec![])]);
let mut baseTokenPos: Value = self.safe_integer(tokensPos.clone(), Value::Int(0), &[]);
let mut quoteTokenPos: Value = self.safe_integer(tokensPos.clone(), Value::Int(1), &[]);
let mut baseTokenInfo: Value = self.safe_dict(tokens.clone(), baseTokenPos.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut quoteTokenInfo: Value = self.safe_dict(tokens.clone(), quoteTokenPos.clone(), &[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.clone(), "name", &[]);
if is_equal(&baseName, &Value::Null) || is_equal("eId, &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.clone(), quoteId.clone(), &[quoteId.clone()]);
let mut mappedBase: Value = self.safe_currency_code(mappedBaseName.clone(), &[]);
let mut mappedQuote: Value = self.safe_currency_code(mappedQuoteId.clone(), &[]);
let mut mappedSymbol: Value = add(&add(&mappedBase, &Value::Str("/".to_string())), &mappedQuote);
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.clone(), "szDecimals", &[]);
let mut amountPrecision: Value = crate::runtime::parse_int(&amountPrecisionStr);
let mut price: Value = self.safe_number_k(extraData.clone(), "midPx", &[]);
let mut pricePrecision: Value = Value::Int(0);
if !is_equal(&price, &Value::Null) {
pricePrecision = self.calculate_price_precision(price.clone(), amountPrecision.clone(), Value::Int(8));
}
let mut pricePrecisionStr: Value = self.number_to_string(pricePrecision.clone());
// const quotePrecision = this.parseNumber (this.parsePrecision (this.safeString (innerQuoteTokenInfo, 'szDecimals')));
let mut baseId: Value = self.number_to_string(add(&index, &Value::Int(10000)));
let mut entry: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketName.clone());
m.insert("symbol".to_string(), mappedSymbol.clone());
m.insert("base".to_string(), mappedBase.clone());
m.insert("quote".to_string(), mappedQuote.clone());
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId.clone());
m.insert("baseName".to_string(), baseName.clone());
m.insert("quoteId".to_string(), quoteId.clone());
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("spot".to_string()));
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.clone());
m.insert("maker".to_string(), maker.clone());
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.clone()]), &[]));
m.insert("price".to_string(), self.parse_number(self.parse_precision(&[pricePrecisionStr.clone()]), &[]));
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".to_string()), &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), self.extend(extraData.clone(), &[market.clone()]));
m
});
append_to_array(&mut markets, self.safe_market_structure(&[entry.clone()]));
}
}
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 = ternary(is_true(&(is_equal(&collateralTokenCode, &Value::Null))), Value::Str("USDC".to_string()), collateralTokenCode.clone());
let mut settleId: Value = ternary(is_true(&(is_equal(&collateralTokenCode, &Value::Null))), Value::Str("USDC".to_string()), collateralTokenCode.clone());
let mut baseName: Value = self.safe_string_k(market.clone(), "name", &[]);
let mut base: Value = self.safe_currency_code(baseName.clone(), &[]);
if is_equal(&base, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" parseMarket() missing base currency".to_string()))));
}
base = replace_str(&base, &Value::Str(":".to_string()), &Value::Str("-".to_string())); // handle hip3 tokens and converts from like flx:crcl to FLX-CRCL
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
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 = add(&add(&base, &Value::Str("/".to_string())), "e);
let mut contract: Value = Value::Bool(true);
let mut swap: Value = Value::Bool(true);
if is_true(&contract) {
if is_true(&swap) {
symbol = add(&add(&symbol, &Value::Str(":".to_string())), &settle);
}
}
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.clone(), "maker", &[]);
let mut amountPrecisionStr: Value = self.safe_string_k(market.clone(), "szDecimals", &[]);
let mut amountPrecision: Value = crate::runtime::parse_int(&amountPrecisionStr);
let mut price: Value = self.safe_number_k(market.clone(), "markPx", &[Value::Int(0)]);
let mut pricePrecision: Value = Value::Int(0);
if !is_equal(&price, &Value::Null) {
pricePrecision = self.calculate_price_precision(price.clone(), amountPrecision.clone(), Value::Int(6));
}
let mut pricePrecisionStr: Value = self.number_to_string(pricePrecision.clone());
let mut isDelisted: Value = self.safe_bool_k(market.clone(), "isDelisted", &[]);
let mut active: Value = Value::Bool(true);
if !is_equal(&isDelisted, &Value::Null) {
active = Value::Bool(!is_true(&isDelisted));
}
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.clone());
m.insert("base".to_string(), base.clone());
m.insert("quote".to_string(), quote.clone());
m.insert("settle".to_string(), settle.clone());
m.insert("baseId".to_string(), baseId.clone());
m.insert("baseName".to_string(), baseName.clone());
m.insert("quoteId".to_string(), quoteId.clone());
m.insert("settleId".to_string(), settleId.clone());
m.insert("type".to_string(), Value::Str("swap".to_string()));
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Null);
m.insert("swap".to_string(), swap.clone());
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), active.clone());
m.insert("contract".to_string(), contract.clone());
m.insert("linear".to_string(), Value::Bool(true));
m.insert("inverse".to_string(), Value::Bool(false));
m.insert("taker".to_string(), taker.clone());
m.insert("maker".to_string(), maker.clone());
m.insert("contractSize".to_string(), self.parse_number(Value::Str("1".to_string()), &[]));
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.clone()]), &[]));
m.insert("price".to_string(), self.parse_number(self.parse_precision(&[pricePrecisionStr.clone()]), &[]));
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".to_string()), &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), market.clone());
m
})]);
Value::Null
}
pub fn update_spot_currency_code(&self, mut code: Value) -> Value {
if is_equal(&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.clone(), 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(is_true(&(!is_equal(&self.safe_string2(params.clone(), Value::Str("user".to_string()), Value::Str("address".to_string()), &[]), &Value::Null))) && is_equal(&self.safe_bool_k(params.clone(), "enableUnifiedMargin", &[]), &Value::Null));
let mut userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchBalance".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchBalance".to_string()), &[Value::Null, params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("fetchBalance".to_string()), &[params.clone()]); marginMode = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut isUnifiedEnabled: Value = Value::Null;
{ let __destr_tmp = self.is_unified_enabled(Value::Str("fetchBalance".to_string()), &[userAddress.clone(), shouldRefresh.clone(), params.clone()]).await; isUnifiedEnabled = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut dex: Value = self.safe_string_k(params.clone(), "dex", &[]);
let mut isSpot: Value = Value::Bool(is_true(&(is_true(&(is_equal(&type_var, &Value::Str("spot".to_string())))) || is_true(&(is_equal(&isUnifiedEnabled, &Value::Bool(true)))))) && is_true(&(is_equal(&dex, &Value::Null))));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), ternary(is_true(&(is_equal(&isSpot, &Value::Bool(true)))), Value::Str("spotClearinghouseState".to_string()), Value::Str("clearinghouseState".to_string())));
m.insert("user".to_string(), userAddress.clone());
m
});
let __ws_arg_10 = self.extend(request.clone(), &[params.clone()]);
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 !is_equal(&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_799: bool = true;
while { if !__for_first_799 { i = add(&i, &Value::Int(1)); } __for_first_799 = false; is_less_than(&i, &get_array_length(&balances)) } {
let mut balance: Value = get_value(&balances, &i);
let mut balance: Value = get_value(&balances, &i);
let mut unifiedCode: Value = self.safe_currency_code(self.safe_string_k(balance.clone(), "coin", &[]), &[]);
let mut code: Value = ternary(is_true(&(is_equal(&isSpot, &Value::Bool(true)))), self.update_spot_currency_code(unifiedCode.clone()), unifiedCode.clone());
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.clone(), "hold", &[]);
add_element_to_object(&mut account, &Value::Str("total".to_string()), total.clone());
add_element_to_object(&mut account, &Value::Str("used".to_string()), used.clone());
if !is_equal(&code, &Value::Null) {
add_element_to_object(&mut spotBalances, &code, account.clone());
}
}
}
return self.safe_balance(spotBalances.clone());
}
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 is_true(&(!is_equal(&marginMode, &Value::Null))) && is_true(&(is_equal(&marginMode, &Value::Str("isolated".to_string())))) {
add_element_to_object(&mut usdcBalance, &Value::Str("free".to_string()), self.safe_number_k(response.clone(), "withdrawable", &[]));
} else {
add_element_to_object(&mut usdcBalance, &Value::Str("used".to_string()), self.safe_number_k(data.clone(), "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.clone());
m
});
let mut timestamp: Value = self.safe_integer_k(response.clone(), "time", &[]);
add_element_to_object(&mut result, &Value::Str("timestamp".to_string()), timestamp.clone());
add_element_to_object(&mut result, &Value::Str("datetime".to_string()), self.iso8601(timestamp.clone()));
return self.safe_balance(result.clone());
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
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("l2Book".to_string()));
m.insert("coin".to_string(), ternary(is_true(&(is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)))), self.safe_string_k(market.clone(), "baseName", &[]), get_value(&market, &Value::Str("id".to_string()))));
m
});
let __ws_arg_11 = self.extend(request.clone(), &[params.clone()]);
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::List(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::List(vec![])]));
m.insert("asks".to_string(), self.safe_list(data.clone(), Value::Int(1), &[Value::List(vec![])]));
m
});
let mut timestamp: Value = self.safe_integer_k(response.clone(), "time", &[]);
return self.parse_order_book(result.clone(), get_value(&market, &Value::Str("symbol".to_string())), &[timestamp.clone(), Value::Str("bids".to_string()), Value::Str("asks".to_string()), Value::Str("px".to_string()), Value::Str("sz".to_string())]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone()]);
// at this stage, to get tickers data, we use fetchMarkets endpoints
let mut response: Value = Value::List(vec![]);
let mut type_var: Value = self.safe_string_k(params.clone(), "type", &[]);
params = self.omit(params.clone(), Value::Str("type".to_string()), &[]);
let mut hip3: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchTickers".to_string()), Value::Str("hip3".to_string()), &[Value::Bool(false)]); hip3 = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if !is_equal(&symbols, &Value::Null) {
// infer from first symbol
let mut firstSymbol: Value = self.safe_string(symbols.clone(), Value::Int(0), &[]);
if !is_equal(&firstSymbol, &Value::Null) {
let mut market: Value = self.market(firstSymbol.clone());
if is_equal(&self.safe_bool(self.safe_dict_k(market.clone(), "info", &[]), Value::Str("hip3".to_string()), &[]), &Value::Bool(true)) {
hip3 = Value::Bool(true);
}
}
}
if is_true(&hip3) {
params = self.omit(params.clone(), Value::Str("hip3".to_string()), &[]);
response = self.fetch_hip3_markets(&[params.clone()]).await;
} else if is_equal(&type_var, &Value::Str("spot".to_string())) {
response = self.fetch_spot_markets(&[params.clone()]).await;
} else if is_equal(&type_var, &Value::Str("swap".to_string())) {
response = self.fetch_swap_markets(&[params.clone()]).await;
} else {
response = self.fetch_markets(&[params.clone()]).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_800: bool = true;
while { if !__for_first_800 { i = add(&i, &Value::Int(1)); } __for_first_800 = false; is_less_than(&i, &get_array_length(&response)) } {
let mut market: Value = get_value(&response, &i);
let mut market: Value = get_value(&response, &i);
let mut info: Value = get_value(&market, &Value::Str("info".to_string()));
let mut ticker: Value = self.parse_ticker(info.clone(), &[market.clone()]);
let mut symbol: Value = self.safe_string_k(ticker.clone(), "symbol", &[]);
add_element_to_object(&mut result, &symbol, ticker.clone());
}
}
return self.filter_by_array_tickers(result.clone(), Value::Str("symbol".to_string()), &[symbols.clone()]);
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::List(vec![get_value(&market, &Value::Str("symbol".to_string()))]), params.clone()]).await;
let mut rate: Value = self.safe_dict(rates.clone(), get_value(&market, &Value::Str("symbol".to_string())), &[]);
if is_equal(&rate, &Value::Null) {
panic!("{}", crate::exchange_errors::bad_symbol(add(&add(&self.id, &Value::Str(" fetchFundingRate() could not find a funding rate for ".to_string())), &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".to_string()));
m
});
let __ws_arg_12 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "universe", &[Value::List(vec![])]);
let mut assetCtxs: Value = self.safe_list(response.clone(), Value::Int(1), &[Value::List(vec![])]);
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_801: bool = true;
while { if !__for_first_801 { i = add(&i, &Value::Int(1)); } __for_first_801 = false; is_less_than(&i, &get_array_length(&universe)) } {
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.clone());
}
}
return self.parse_funding_rates(result.clone(), &[symbols.clone()]);
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.clone());
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[market.clone()]);
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 = multiply(&multiply(&multiply(&(add(&math_floor(÷(÷(÷(&self.milliseconds(), &Value::Int(60)), &Value::Int(60)), &Value::Int(1000))), &Value::Int(1))), &Value::Int(60)), &Value::Int(60)), &Value::Int(1000));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), info.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("markPrice".to_string(), markPx.clone());
m.insert("indexPrice".to_string(), oraclePx.clone());
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.clone());
m.insert("fundingTimestamp".to_string(), fundingTimestamp.clone());
m.insert("fundingDatetime".to_string(), self.iso8601(fundingTimestamp.clone()));
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".to_string()));
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.clone());
market = self.safe_market(&[marketId.clone(), market.clone()]);
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(), get_value(&market, &Value::Str("symbol".to_string())));
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.clone(), Value::Int(1), &[]));
m.insert("quoteVolume".to_string(), self.safe_number_k(ticker.clone(), "dayNtlVlm", &[]));
m.insert("info".to_string(), ticker.clone());
m
}), &[market.clone()]);
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".to_string()));
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[self.milliseconds()]);
let mut useTail: Value = Value::Bool(is_equal(&since, &Value::Null));
let mut originalSince: Value = since.clone();
if is_equal(&since, &Value::Null) {
if !is_equal(&limit, &Value::Null) {
// optimization if limit is provided
let mut timeframeInMilliseconds: Value = multiply(&self.parse_timeframe(timeframe.clone()), &Value::Int(1000));
since = self.sum(&[until.clone(), multiply(&multiply(&timeframeInMilliseconds, &limit), &negate(&Value::Int(1)))]);
if is_less_than(&since, &Value::Int(0)) {
since = Value::Int(0);
}
useTail = Value::Bool(false);
} else {
since = Value::Int(0);
}
}
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("candleSnapshot".to_string()));
m.insert("req".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("coin".to_string(), ternary(is_true(&(is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)))), self.safe_string_k(market.clone(), "baseName", &[]), get_value(&market, &Value::Str("id".to_string()))));
m.insert("interval".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m.insert("startTime".to_string(), since.clone());
m.insert("endTime".to_string(), until.clone());
m
}));
m
});
let __ws_arg_15 = self.extend(request.clone(), &[params.clone()]);
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::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
candles = response.clone();
}
return self.parse_ohlc_vs(candles.clone(), &[market.clone(), timeframe.clone(), originalSince.clone(), limit.clone(), useTail.clone()]);
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::List(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.clone(), "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 userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchTrades".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("user".to_string(), userAddress.clone());
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("type".to_string()), Value::Str("userFillsByTime".to_string()));
add_element_to_object(&mut request, &Value::Str("startTime".to_string()), since.clone());
} else {
add_element_to_object(&mut request, &Value::Str("type".to_string()), Value::Str("userFills".to_string()));
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
params = self.omit(params.clone(), Value::Str("until".to_string()), &[]);
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), until.clone());
}
let __ws_arg_16 = self.extend(request.clone(), &[params.clone()]);
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::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
fills = response.clone();
}
return self.parse_trades(fills.clone(), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn amount_to_precision(&self, mut symbol: Value, mut amount: Value) -> Value {
let mut market: Value = self.market(symbol.clone());
return self.decimal_to_precision(amount.clone(), Value::Int(crate::runtime::ROUND), get_value(&get_value(&market, &Value::Str("precision".to_string())), &Value::Str("amount".to_string())), &[self.precisionMode.clone(), self.paddingMode.clone()]);
Value::Null
}
pub fn price_to_precision(&self, mut symbol: Value, mut price: Value) -> Value {
let mut market: Value = self.market(symbol.clone());
let mut priceStr: Value = self.number_to_string(price.clone());
let mut integerPart: Value = get_value(&split(&priceStr, &Value::Str(".".to_string())), &Value::Int(0));
let mut significantDigits: Value = crate::runtime::Math::max(&Value::Int(5), &get_array_length(&integerPart));
let mut result: Value = self.decimal_to_precision(price.clone(), Value::Int(crate::runtime::ROUND), significantDigits.clone(), &[Value::Int(crate::runtime::SIGNIFICANT_DIGITS), self.paddingMode.clone()]);
let mut maxDecimals: Value = ternary(is_true(&(is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)))), Value::Int(8), Value::Int(6));
let mut subtractedValue: Value = subtract(&maxDecimals, &self.precision_from_string(self.safe_string(get_value(&market, &Value::Str("precision".to_string())), Value::Str("amount".to_string()), &[])));
return self.decimal_to_precision(result.clone(), Value::Int(crate::runtime::ROUND), subtractedValue.clone(), &[Value::Int(crate::runtime::DECIMAL_PLACES), self.paddingMode.clone()]);
Value::Null
}
pub fn hash_message(&self, mut message: Value) -> Value {
return add(&Value::Str("0x".to_string()), &self.hash(message.clone(), Value::Str("keccak".to_string()), &[Value::Str("hex".to_string())]));
Value::Null
}
pub fn sign_hash(&self, mut hash: Value, mut privateKey: Value) -> Value {
let mut signature: Value = ecdsa(slice(&hash, &negate(&Value::Int(64)), &Value::Null), slice(&privateKey, &negate(&Value::Int(64)), &Value::Null), Value::Str("secp256k1".to_string()), Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("r".to_string(), add(&Value::Str("0x".to_string()), &get_value(&signature, &Value::Str("r".to_string()))));
m.insert("s".to_string(), add(&Value::Str("0x".to_string()), &get_value(&signature, &Value::Str("s".to_string()))));
m.insert("v".to_string(), self.sum(&[Value::Int(27), get_value(&signature, &Value::Str("v".to_string()))]));
m
});
Value::Null
}
pub fn sign_message(&self, mut message: Value, mut privateKey: Value) -> Value {
return self.sign_hash(self.hash_message(message.clone()), slice(&privateKey, &negate(&Value::Int(64)), &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 = ternary(is_true(&(isTestnet)), Value::Str("b".to_string()), Value::Str("a".to_string()));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("source".to_string(), source.clone());
m.insert("connectionId".to_string(), hash.clone());
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.clone(), &[]);
let mut dataHex: Value = self.binary_to_base16(dataBinary.clone(), &[]);
let mut data: Value = dataHex.clone();
data = add(&data, &add(&Value::Str("00000".to_string()), &self.int_to_base16(nonce.clone(), &[])));
if is_equal(&vaultAddress, &Value::Null) {
data = add(&data, &Value::Str("00".to_string()));
} else {
data = add(&data, &Value::Str("01".to_string()));
data = add(&data, &vaultAddress);
}
if !is_equal(&expiresAfter, &Value::Null) {
data = add(&data, &Value::Str("00".to_string()));
data = add(&data, &add(&Value::Str("00000".to_string()), &self.int_to_base16(expiresAfter.clone(), &[])));
}
return self.hash(self.base16_to_binary(data.clone(), &[]), Value::Str("keccak".to_string()), &[Value::Str("binary".to_string())]);
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.clone(), vaultAdress.clone(), nonce.clone(), &[expiresAfter.clone()]);
let mut isTestnet: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut phantomAgent: Value = self.construct_phantom_agent(hash.clone(), &[isTestnet.clone()]);
// 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.clone());
m.insert("name".to_string(), Value::Str("Exchange".to_string()));
m.insert("verifyingContract".to_string(), zeroAddress.clone());
m.insert("version".to_string(), Value::Str("1".to_string()));
m
});
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Agent".to_string(), Value::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("source".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("connectionId".to_string()));
m.insert("type".to_string(), Value::Str("bytes32".to_string()));
m
})]));
m
});
let mut msg: Value = self.eth_encode_structured_data(domain.clone(), messageTypes.clone(), phantomAgent.clone());
let mut signature: Value = self.sign_message(msg.clone(), 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.clone());
m.insert("name".to_string(), Value::Str("HyperliquidSignTransaction".to_string()));
m.insert("verifyingContract".to_string(), zeroAddress.clone());
m.insert("version".to_string(), Value::Str("1".to_string()));
m
});
let mut msg: Value = self.eth_encode_structured_data(domain.clone(), messageTypes.clone(), message.clone());
let mut signature: Value = self.sign_message(msg.clone(), 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::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("destination".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("amount".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("time".to_string()));
m.insert("type".to_string(), Value::Str("uint64".to_string()));
m
})]));
m
});
return self.sign_user_signed_action(messageTypes.clone(), message.clone());
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::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("amount".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("toPerp".to_string()));
m.insert("type".to_string(), Value::Str("bool".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".to_string()));
m.insert("type".to_string(), Value::Str("uint64".to_string()));
m
})]));
m
});
return self.sign_user_signed_action(messageTypes.clone(), message.clone());
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::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("destination".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("amount".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("time".to_string()));
m.insert("type".to_string(), Value::Str("uint64".to_string()));
m
})]));
m
});
return self.sign_user_signed_action(messageTypes.clone(), message.clone());
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::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("user".to_string()));
m.insert("type".to_string(), Value::Str("address".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("enabled".to_string()));
m.insert("type".to_string(), Value::Str("bool".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".to_string()));
m.insert("type".to_string(), Value::Str("uint64".to_string()));
m
})]));
m
});
return self.sign_user_signed_action(messageTypes.clone(), message.clone());
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::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("user".to_string()));
m.insert("type".to_string(), Value::Str("address".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("abstraction".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".to_string()));
m.insert("type".to_string(), Value::Str("uint64".to_string()));
m
})]));
m
});
return self.sign_user_signed_action(messageTypes.clone(), message.clone());
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::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("maxFeeRate".to_string()));
m.insert("type".to_string(), Value::Str("string".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("builder".to_string()));
m.insert("type".to_string(), Value::Str("address".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".to_string()));
m.insert("type".to_string(), Value::Str("uint64".to_string()));
m
})]));
m
});
return self.sign_user_signed_action(messageTypes.clone(), message.clone());
Value::Null
}
pub async fn set_ref(&mut self) -> Value {
if is_true(&self.safe_bool_k(self.options.clone(), "refSet", &[Value::Bool(false)])) {
return Value::Bool(true);
}
add_element_to_object(&mut self.options, &Value::Str("refSet".to_string()), Value::Bool(true));
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("setReferrer".to_string()));
m.insert("code".to_string(), self.safe_string_k(self.options.clone(), "ref", &[Value::Str("CCXT1".to_string())]));
m
});
let mut nonce: Value = self.milliseconds();
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.clone());
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), signature.clone());
m
});
let mut response: Value = Value::Null;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
response = self.private_post_exchange(&[request.clone()]).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.milliseconds();
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(), ternary(is_true(&(is_equal(&isSandboxMode, &Value::Bool(true)))), Value::Str("Testnet".to_string()), Value::Str("Mainnet".to_string())));
m.insert("maxFeeRate".to_string(), maxFeeRate.clone());
m.insert("builder".to_string(), builder.clone());
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(), get_value(&payload, &Value::Str("hyperliquidChain".to_string())));
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".to_string()));
m.insert("maxFeeRate".to_string(), get_value(&payload, &Value::Str("maxFeeRate".to_string())));
m.insert("builder".to_string(), get_value(&payload, &Value::Str("builder".to_string())));
m.insert("nonce".to_string(), nonce.clone());
m.insert("type".to_string(), Value::Str("approveBuilderFee".to_string()));
m
});
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.insert("vaultAddress".to_string(), Value::Null);
m
});
return self.private_post_exchange(&[request.clone()]).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::List(vec![self.handle_builder_fee_approval().await, self.set_ref().await, self.is_unified_enabled(Value::Str("fetchBalance".to_string()), &[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 is_equal(&approvedBuilderFee, &Value::Bool(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".to_string())]);
// 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%".to_string())]);
if !is_equal(&buildFee, &Value::Bool(true)) {
maxFeeRate = Value::Str("0%".to_string());
}
self.approve_builder_fee(builder.clone(), maxFeeRate.clone()).await;
add_element_to_object(&mut self.options, &Value::Str("approvedBuilderFee".to_string()), Value::Bool(true));
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
add_element_to_object(&mut self.options, &Value::Str("builderFee".to_string()), 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 userAddress: Value = Value::Null;
if !is_equal(&address, &Value::Null) {
userAddress = address.clone();
} else {
{ let __destr_tmp = self.handle_public_address(Value::Str("isUnifiedEnabled".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
}
let mut enableUnifiedMargin: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), method.clone(), Value::Str("enableUnifiedMargin".to_string()), &[]); enableUnifiedMargin = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&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".to_string()));
m.insert("user".to_string(), userAddress.clone());
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.clone(), &[params.clone()]);
let mut rawResponse: Value = self.public_post_info(&[__ws_arg_17]).await;
if is_string(&rawResponse) {
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 is_true(&is_instance(&e, &Value::Str("InvalidProxySettings".to_string()))) {
panic!("{}", e);
}
response = Value::Null; // ignore this error and assume unified margin is not enabled
}
//
// "unifiedAccount" | "portfolioMargin" | "disabled" | "default" | "dexAbstraction"
//
if !is_equal(&response, &Value::Null) {
response = replace_str(&response, &Value::Str("\"".to_string()), &Value::Str("".to_string()));
response = replace_str(&response, &Value::Str("\"".to_string()), &Value::Str("".to_string()));
enableUnifiedMargin = Value::Bool(is_equal(&response, &Value::Str("unifiedAccount".to_string())));
}
// don't cache this result if this is a different addresss
add_element_to_object(&mut self.options, &Value::Str("enableUnifiedMargin".to_string()), enableUnifiedMargin.clone()); // cache this for future calls
}
return Value::List(vec![enableUnifiedMargin.clone(), params.clone()]);
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 userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("setUserAbstraction".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut nonce: Value = self.milliseconds();
let mut isSandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut type_var: Value = self.safe_string_k(params.clone(), "type", &[Value::Str("userSetAbstraction".to_string())]);
params = self.omit(params.clone(), Value::Str("type".to_string()), &[]);
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), ternary(is_true(&(is_equal(&isSandboxMode, &Value::Bool(true)))), Value::Str("Testnet".to_string()), Value::Str("Mainnet".to_string())));
m.insert("user".to_string(), userAddress.clone());
m.insert("abstraction".to_string(), abstraction.clone());
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(), get_value(&payload, &Value::Str("hyperliquidChain".to_string())));
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".to_string()));
m.insert("abstraction".to_string(), get_value(&payload, &Value::Str("abstraction".to_string())));
m.insert("user".to_string(), get_value(&payload, &Value::Str("user".to_string())));
m.insert("nonce".to_string(), nonce.clone());
m.insert("type".to_string(), type_var.clone());
m
});
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.insert("vaultAddress".to_string(), Value::Null);
m
});
return self.private_post_exchange(&[request.clone()]).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 userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("enableUserDexAbstraction".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut nonce: Value = self.milliseconds();
let mut isSandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut type_var: Value = self.safe_string_k(params.clone(), "type", &[Value::Str("userDexAbstraction".to_string())]);
params = self.omit(params.clone(), Value::Str("type".to_string()), &[]);
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), ternary(is_true(&(is_equal(&isSandboxMode, &Value::Bool(true)))), Value::Str("Testnet".to_string()), Value::Str("Mainnet".to_string())));
m.insert("user".to_string(), userAddress.clone());
m.insert("enabled".to_string(), enabled.clone());
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(), get_value(&payload, &Value::Str("hyperliquidChain".to_string())));
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".to_string()));
m.insert("enabled".to_string(), get_value(&payload, &Value::Str("enabled".to_string())));
m.insert("user".to_string(), get_value(&payload, &Value::Str("user".to_string())));
m.insert("nonce".to_string(), nonce.clone());
m.insert("type".to_string(), type_var.clone());
m
});
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.insert("vaultAddress".to_string(), Value::Null);
m
});
return self.private_post_exchange(&[request.clone()]).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.milliseconds();
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".to_string()));
m.insert("abstraction".to_string(), abstraction.clone());
m
});
let mut signature: Value = self.sign_l1_action(action.clone(), nonce.clone(), &[]);
add_element_to_object(&mut request, &Value::Str("action".to_string()), action.clone());
add_element_to_object(&mut request, &Value::Str("signature".to_string()), signature.clone());
let __ws_arg_18 = self.extend(request.clone(), &[params.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut orderglobalParamsVariable = self.parse_create_edit_order_args(Value::Null, symbol.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params.clone()]);
let mut order: Value = get_value(&orderglobalParamsVariable, &Value::Int(0));
let mut globalParams: Value = get_value(&orderglobalParamsVariable, &Value::Int(1));
let mut orders: Value = self.create_orders(Value::List(vec![order.clone()]), &[globalParams.clone()]).await;
return get_value(&orders, &Value::Int(0));
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut market: Value = self.market(symbol.clone());
let mut nonce: Value = self.milliseconds();
let mut isBuy: Value = Value::Bool(is_equal(&side, &Value::Str("BUY".to_string())));
let mut vaultAddress: Value = Value::Null;
let mut randomize: Value = self.safe_bool_k(params.clone(), "randomize", &[Value::Bool(false)]);
params = self.omit(params.clone(), Value::Str("randomize".to_string()), &[]);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".to_string()), Value::Str("vaultAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
let mut durationMins: Value = math_floor(÷(÷(&duration, &Value::Int(1000)), &Value::Int(60))); // 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(get_value(&market, &Value::Str("baseId".to_string()))));
m.insert("b".to_string(), isBuy.clone());
m.insert("s".to_string(), self.amount_to_precision(symbol.clone(), amount.clone()));
m.insert("r".to_string(), self.safe_bool_k(params.clone(), "reduceOnly", &[Value::Bool(false)]));
m.insert("m".to_string(), durationMins.clone());
m.insert("t".to_string(), randomize.clone());
m
});
let mut orderAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("twapOrder".to_string()));
m.insert("twap".to_string(), orderObj.clone());
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.clone());
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), signature.clone());
m
});
if !is_equal(&vaultAddress, &Value::Null) {
params = self.omit(params.clone(), Value::Str("vaultAddress".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("vaultAddress".to_string()), vaultAddress.clone());
}
let mut expiresAfter: Value = self.safe_integer_k(params.clone(), "expiresAfter", &[]);
if !is_equal(&expiresAfter, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("expiresAfter".to_string()), expiresAfter.clone());
params = self.omit(params.clone(), Value::Str("expiresAfter".to_string()), &[]);
}
let mut response: Value = self.private_post_exchange(&[request.clone()]).await;
// {
// "status":"ok",
// "response":{
// "type":"twapOrder",
// "data":{
// "status": {
// "running":{
// "twapId":77738308
// }
// }
// }
// }
// }
let mut responseObj: Value = self.safe_dict_k(response.clone(), "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(responseObj.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut status: Value = self.safe_dict_k(data.clone(), "status", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut running: Value = self.safe_dict_k(status.clone(), "running", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderId: Value = self.safe_string_k(running.clone(), "twapId", &[]);
return self.parse_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("running".to_string()));
m.insert("oid".to_string(), orderId.clone());
m
}), &[market.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut request: Value = self.create_orders_request(orders.clone(), &[params.clone()]);
let mut response: Value = self.private_post_exchange(&[request.clone()]).await;
//
// {
// "status": "ok",
// "response": {
// "type": "order",
// "data": {
// "statuses": [
// {
// "resting": {
// "oid": 5063830287
// }
// }
// ]
// }
// }
// }
//
let mut responseObj: Value = self.safe_dict_k(response.clone(), "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(responseObj.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut statuses: Value = self.safe_list_k(data.clone(), "statuses", &[Value::List(vec![])]);
let mut ordersToBeParsed: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_802: bool = true;
while { if !__for_first_802 { i = add(&i, &Value::Int(1)); } __for_first_802 = false; is_less_than(&i, &get_array_length(&statuses)) } {
let mut order: Value = get_value(&statuses, &i);
let mut order: Value = get_value(&statuses, &i);
if is_equal(&order, &Value::Str("waitingForTrigger".to_string())) {
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.clone());
}
}
}
return self.parse_orders(ordersToBeParsed.clone(), &[]);
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 is_equal(&type_var, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" requires a type argument".to_string()))));
}
if is_equal(&side, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" requires a side argument".to_string()))));
}
let mut market: Value = self.market(symbol.clone());
type_var = to_upper(&type_var);
side = to_upper(&side);
let mut isMarket: Value = Value::Bool(is_equal(&type_var, &Value::Str("MARKET".to_string())));
let mut isBuy: Value = Value::Bool(is_equal(&side, &Value::Str("BUY".to_string())));
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clientOrderId".to_string()), Value::Str("client_id".to_string()), &[]);
let mut slippage: Value = self.safe_string_k(params.clone(), "slippage", &[]);
let mut defaultTimeInForce: Value = ternary(is_true(&(isMarket)), Value::Str("ioc".to_string()), Value::Str("gtc".to_string()));
let mut postOnly: Value = self.safe_bool_k(params.clone(), "postOnly", &[Value::Bool(false)]);
if is_equal(&postOnly, &Value::Bool(true)) {
defaultTimeInForce = Value::Str("alo".to_string());
}
let mut timeInForce: Value = self.safe_string_lower(params.clone(), Value::Str("timeInForce".to_string()), &[defaultTimeInForce.clone()]);
timeInForce = self.capitalize(timeInForce.clone());
let mut triggerPrice: Value = self.safe_string2(params.clone(), Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), &[]);
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 = is_true(&(!is_equal(&stopLossPrice, &Value::Null))) || is_true(&(!is_equal(&takeProfitPrice, &Value::Null)));
let mut px: Value = Value::Null;
if is_true(&isMarket) {
if is_equal(&price, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" market orders require price to calculate the max slippage price. Default slippage can be set in options (default is 5%).".to_string()))));
}
px = ternary(is_true(&(isBuy)), crate::precise::Precise::stringMul(&price, &crate::precise::Precise::stringAdd(&Value::Str("1".to_string()), &slippage)), crate::precise::Precise::stringMul(&price, &crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &slippage)));
px = self.price_to_precision(symbol.clone(), px.clone()); // round after adding slippage
} else {
px = self.price_to_precision(symbol.clone(), price.clone());
}
let mut sz: Value = self.amount_to_precision(symbol.clone(), amount.clone());
let mut reduceOnly: Value = self.safe_bool_k(params.clone(), "reduceOnly", &[Value::Bool(false)]);
let mut orderType: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_true(&isTrigger) {
let mut isTp: Value = Value::Bool(false);
if !is_equal(&takeProfitPrice, &Value::Null) {
triggerPrice = self.price_to_precision(symbol.clone(), takeProfitPrice.clone());
isTp = Value::Bool(true);
} else {
triggerPrice = self.price_to_precision(symbol.clone(), stopLossPrice.clone());
}
let mut tpSlType: Value = ternary(is_true(&(isTp)), Value::Str("tp".to_string()), Value::Str("sl".to_string()));
add_element_to_object(&mut orderType, &Value::Str("trigger".to_string()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("isMarket".to_string(), isMarket.clone());
m.insert("triggerPx".to_string(), triggerPrice.clone());
m.insert("tpsl".to_string(), tpSlType.clone());
m
}));
} else {
add_element_to_object(&mut orderType, &Value::Str("limit".to_string()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tif".to_string(), timeInForce.clone());
m
}));
}
params = self.omit(params.clone(), Value::List(vec![Value::Str("clientOrderId".to_string()), Value::Str("slippage".to_string()), Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), Value::Str("stopLossPrice".to_string()), Value::Str("takeProfitPrice".to_string()), Value::Str("timeInForce".to_string()), Value::Str("client_id".to_string()), Value::Str("reduceOnly".to_string()), Value::Str("postOnly".to_string())]), &[]);
let mut orderObj: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("a".to_string(), self.parse_to_int(get_value(&market, &Value::Str("baseId".to_string()))));
m.insert("b".to_string(), isBuy.clone());
m.insert("p".to_string(), px.clone());
m.insert("s".to_string(), sz.clone());
m.insert("r".to_string(), reduceOnly.clone());
m.insert("t".to_string(), orderType.clone());
m
});
if !is_equal(&clientOrderId, &Value::Null) {
add_element_to_object(&mut orderObj, &Value::Str("c".to_string()), clientOrderId.clone());
}
return orderObj;
Value::Null
}
pub fn create_orders_request(&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_803: bool = true;
while { if !__for_first_803 { i = add(&i, &Value::Int(1)); } __for_first_803 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut rawOrder: Value = get_value(&orders, &i);
let mut rawOrder: Value = get_value(&orders, &i);
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".to_string()), Value::Str("client_id".to_string()), &[]);
if !is_equal(&clientOrderId, &Value::Null) {
hasClientOrderId = true;
}
}
}
if is_true(&hasClientOrderId) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_804: bool = true;
while { if !__for_first_804 { i = add(&i, &Value::Int(1)); } __for_first_804 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut rawOrder: Value = get_value(&orders, &i);
let mut rawOrder: Value = get_value(&orders, &i);
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".to_string()), Value::Str("client_id".to_string()), &[]);
if is_equal(&clientOrderId, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" createOrders() all orders must have clientOrderId if at least one has a clientOrderId".to_string()))));
}
}
}
}
params = self.omit(params.clone(), Value::List(vec![Value::Str("slippage".to_string()), Value::Str("clientOrderId".to_string()), Value::Str("client_id".to_string()), Value::Str("slippage".to_string()), Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), Value::Str("stopLossPrice".to_string()), Value::Str("takeProfitPrice".to_string()), Value::Str("timeInForce".to_string())]), &[]);
let mut nonce: Value = self.milliseconds();
let mut orderReq: Value = Value::List(vec![]);
let mut grouping: Value = Value::Str("na".to_string());
{
let mut i: Value = Value::Int(0);
let mut __for_first_805: bool = true;
while { if !__for_first_805 { i = add(&i, &Value::Int(1)); } __for_first_805 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut rawOrder: Value = get_value(&orders, &i);
let mut rawOrder: Value = get_value(&orders, &i);
let mut marketId: Value = self.safe_string_k(rawOrder.clone(), "symbol", &[]);
let mut market: Value = self.market(marketId.clone());
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut type_var: Value = self.safe_string_upper(rawOrder.clone(), Value::Str("type".to_string()), &[]);
let mut side: Value = self.safe_string_upper(rawOrder.clone(), Value::Str("side".to_string()), &[]);
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.clone(), "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".to_string()), slippage.clone());
let mut stopLoss: Value = self.safe_value_k(orderParams.clone(), "stopLoss", &[]);
let mut takeProfit: Value = self.safe_value_k(orderParams.clone(), "takeProfit", &[]);
let mut hasStopLoss: bool = !is_equal(&stopLoss, &Value::Null);
let mut hasTakeProfit: bool = !is_equal(&takeProfit, &Value::Null);
orderParams = self.omit(orderParams.clone(), Value::List(vec![Value::Str("stopLoss".to_string()), Value::Str("takeProfit".to_string())]), &[]);
let mut mainOrderObj: Value = self.create_order_request(symbol.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), orderParams.clone()]);
if is_true(&hasStopLoss) || is_true(&hasTakeProfit) {
// grouping opposed orders for sl/tp
let mut stopLossOrderTriggerPrice: Value = self.safe_string2(stopLoss.clone(), Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), &[]);
let mut stopLossOrderType: Value = self.safe_string_k(stopLoss.clone(), "type", &[Value::Str("limit".to_string())]);
let mut stopLossOrderLimitPrice: Value = self.safe_string2(stopLoss.clone(), Value::Str("price".to_string()), Value::Str("stopLossPrice".to_string()), &[stopLossOrderTriggerPrice.clone()]);
let mut takeProfitOrderTriggerPrice: Value = self.safe_string2(takeProfit.clone(), Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), &[]);
let mut takeProfitOrderType: Value = self.safe_string_k(takeProfit.clone(), "type", &[Value::Str("limit".to_string())]);
let mut takeProfitOrderLimitPrice: Value = self.safe_string2(takeProfit.clone(), Value::Str("price".to_string()), Value::Str("takeProfitPrice".to_string()), &[takeProfitOrderTriggerPrice.clone()]);
grouping = self.safe_string_k(orderParams.clone(), "grouping", &[Value::Str("normalTpsl".to_string())]);
if is_equal(&grouping, &Value::Str("positionTpsl".to_string())) {
amount = Value::Str("0".to_string());
stopLossOrderType = Value::Str("market".to_string());
takeProfitOrderType = Value::Str("market".to_string());
} else if is_equal(&grouping, &Value::Str("normalTpsl".to_string())) {
append_to_array(&mut orderReq, mainOrderObj.clone());
} else {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" only support grouping normalTpsl and positionTpsl.".to_string()))));
}
orderParams = self.omit(orderParams.clone(), Value::List(vec![Value::Str("stopLoss".to_string()), Value::Str("takeProfit".to_string()), Value::Str("grouping".to_string())]), &[]);
let mut triggerOrderSide: Value = Value::Str("".to_string());
if is_equal(&side, &Value::Str("BUY".to_string())) {
triggerOrderSide = Value::Str("sell".to_string());
} else {
triggerOrderSide = Value::Str("buy".to_string());
}
if is_true(&hasTakeProfit) {
let __ws_arg_19 = self.extend(orderParams.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("takeProfitPrice".to_string(), takeProfitOrderTriggerPrice.clone());
m.insert("reduceOnly".to_string(), Value::Bool(true));
m
})]);
let mut orderObj: Value = self.create_order_request(symbol.clone(), takeProfitOrderType.clone(), triggerOrderSide.clone(), amount.clone(), &[takeProfitOrderLimitPrice.clone(), __ws_arg_19]);
append_to_array(&mut orderReq, orderObj.clone());
}
if is_true(&hasStopLoss) {
let __ws_arg_20 = self.extend(orderParams.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stopLossPrice".to_string(), stopLossOrderTriggerPrice.clone());
m.insert("reduceOnly".to_string(), Value::Bool(true));
m
})]);
let mut orderObj: Value = self.create_order_request(symbol.clone(), stopLossOrderType.clone(), triggerOrderSide.clone(), amount.clone(), &[stopLossOrderLimitPrice.clone(), __ws_arg_20]);
append_to_array(&mut orderReq, orderObj.clone());
}
} else {
append_to_array(&mut orderReq, mainOrderObj.clone());
}
}
}
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".to_string()), Value::Str("vaultAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
let mut orderAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("order".to_string()));
m.insert("orders".to_string(), orderReq.clone());
m.insert("grouping".to_string(), grouping.clone());
m
});
if is_true(&self.safe_bool_k(self.options.clone(), "approvedBuilderFee", &[Value::Bool(false)])) {
let mut wallet: Value = self.safe_string_lower(self.options.clone(), Value::Str("builder".to_string()), &[Value::Str("0x6530512A6c89C7cfCEbC3BA7fcD9aDa5f30827a6".to_string())]);
// 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 !is_true(&self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(true)])) {
feeInt = Value::Int(0);
}
add_element_to_object(&mut orderAction, &Value::Str("builder".to_string()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("b".to_string(), wallet.clone());
m.insert("f".to_string(), feeInt.clone());
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.clone());
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), signature.clone());
m
});
if !is_equal(&vaultAddress, &Value::Null) {
params = self.omit(params.clone(), Value::Str("vaultAddress".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("vaultAddress".to_string()), vaultAddress.clone());
}
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 is_true(&self.safe_bool_k(params.clone(), "twap", &[Value::Bool(false)])) {
params = self.omit(params.clone(), Value::Str("twap".to_string()), &[]);
return self.cancel_twap_order(id.clone(), &[symbol.clone(), params.clone()]).await;
}
let mut orders: Value = self.cancel_orders(Value::List(vec![id.clone()]), &[symbol.clone(), params.clone()]).await;
return self.safe_dict(orders.clone(), Value::Int(0), &[]);
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 is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelOrders() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut request: Value = self.cancel_orders_request(ids.clone(), &[symbol.clone(), params.clone()]);
let mut response: Value = self.private_post_exchange(&[request.clone()]).await;
//
// {
// "status":"ok",
// "response":{
// "type":"cancel",
// "data":{
// "statuses":[
// "success"
// ]
// }
// }
// }
//
let mut innerResponse: Value = self.safe_dict_k(response.clone(), "response", &[]);
let mut data: Value = self.safe_dict_k(innerResponse.clone(), "data", &[]);
let mut statuses: Value = self.safe_list_k(data.clone(), "statuses", &[Value::List(vec![])]);
let mut orders: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_806: bool = true;
while { if !__for_first_806 { i = add(&i, &Value::Int(1)); } __for_first_806 = false; is_less_than(&i, &get_array_length(&statuses)) } {
let mut status: Value = get_value(&statuses, &i);
let mut status: Value = get_value(&statuses, &i);
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.clone());
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelTwapOrder() requires a symbol argument".to_string()))));
}
let mut market: Value = self.market(symbol.clone());
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("cancelTwapOrder".to_string()), Value::Str("vaultAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("twapCancel".to_string()));
m.insert("a".to_string(), self.parse_to_int(get_value(&market, &Value::Str("baseId".to_string()))));
m.insert("t".to_string(), self.parse_to_numeric(id.clone()));
m
});
let mut nonce: Value = self.milliseconds();
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.clone());
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), signature.clone());
m
});
if !is_equal(&vaultAddress, &Value::Null) {
params = self.omit(params.clone(), Value::Str("vaultAddress".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("vaultAddress".to_string()), vaultAddress.clone());
}
let mut expiresAfter: Value = self.safe_integer_k(params.clone(), "expiresAfter", &[]);
if !is_equal(&expiresAfter, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("expiresAfter".to_string()), expiresAfter.clone());
params = self.omit(params.clone(), Value::Str("expiresAfter".to_string()), &[]);
}
let mut response: Value = self.private_post_exchange(&[request.clone()]).await;
//
// {
// "status":"ok",
// "response":{
// "type":"twapCancel",
// "data":{
// "status": "success"
// }
// }
// }
//
let mut responseObj: Value = self.safe_dict_k(response.clone(), "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(responseObj.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut status: Value = self.safe_string_k(data.clone(), "status", &[]);
return self.parse_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), status.clone());
m.insert("oid".to_string(), id.clone());
m
}), &[market.clone()]);
Value::Null
}
pub fn cancel_orders_request(&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".to_string()), Value::Str("client_id".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("clientOrderId".to_string()), Value::Str("client_id".to_string())]), &[]);
let mut nonce: Value = self.milliseconds();
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::List(vec![]);
let mut cancelAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("".to_string()));
m.insert("cancels".to_string(), Value::List(vec![]));
m
});
let mut baseId: Value = self.parse_to_numeric(get_value(&market, &Value::Str("baseId".to_string())));
if !is_equal(&clientOrderId, &Value::Null) {
if !is_true(&Value::Bool(is_array(&clientOrderId))) {
clientOrderId = Value::List(vec![clientOrderId.clone()]);
}
add_element_to_object(&mut cancelAction, &Value::Str("type".to_string()), Value::Str("cancelByCloid".to_string()));
{
let mut i: Value = Value::Int(0);
let mut __for_first_807: bool = true;
while { if !__for_first_807 { i = add(&i, &Value::Int(1)); } __for_first_807 = false; is_less_than(&i, &get_array_length(&clientOrderId)) } {
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 {
add_element_to_object(&mut cancelAction, &Value::Str("type".to_string()), Value::Str("cancel".to_string()));
{
let mut i: Value = Value::Int(0);
let mut __for_first_808: bool = true;
while { if !__for_first_808 { i = add(&i, &Value::Int(1)); } __for_first_808 = false; is_less_than(&i, &get_array_length(&ids)) } {
let mut o: Value = self.parse_to_numeric(get_value(&ids, &i));
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.clone());
m
}));
}
}
}
add_element_to_object(&mut cancelAction, &Value::Str("cancels".to_string()), cancelReq.clone());
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("cancelOrders".to_string()), Value::Str("vaultAddress".to_string()), Value::Str("subAccountAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
let mut signature: Value = self.sign_l1_action(cancelAction.clone(), nonce.clone(), &[vaultAddress.clone()]);
add_element_to_object(&mut request, &Value::Str("action".to_string()), cancelAction.clone());
add_element_to_object(&mut request, &Value::Str("signature".to_string()), signature.clone());
if !is_equal(&vaultAddress, &Value::Null) {
params = self.omit(params.clone(), Value::Str("vaultAddress".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("vaultAddress".to_string()), vaultAddress.clone());
}
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut nonce: Value = self.milliseconds();
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::List(vec![]);
let mut cancelAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("".to_string()));
m.insert("cancels".to_string(), Value::List(vec![]));
m
});
let mut cancelByCloid: bool = false;
{
let mut i: Value = Value::Int(0);
let mut __for_first_809: bool = true;
while { if !__for_first_809 { i = add(&i, &Value::Int(1)); } __for_first_809 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut order: Value = get_value(&orders, &i);
let mut order: Value = get_value(&orders, &i);
let mut clientOrderId: Value = self.safe_string_k(order.clone(), "clientOrderId", &[]);
if !is_equal(&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.clone(), "symbol", &[]);
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelOrdersForSymbols() requires a symbol argument in each order".to_string()))));
}
if !is_equal(&id, &Value::Null) && is_true(&cancelByCloid) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" cancelOrdersForSymbols() all orders must have either id or clientOrderId".to_string()))));
}
let mut assetKey: Value = ternary(is_true(&cancelByCloid), Value::Str("asset".to_string()), Value::Str("a".to_string()));
let mut idKey: Value = ternary(is_true(&cancelByCloid), Value::Str("cloid".to_string()), Value::Str("o".to_string()));
let mut market: Value = self.market(symbol.clone());
let mut cancelObj: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut cancelObj, &assetKey, self.parse_to_numeric(get_value(&market, &Value::Str("baseId".to_string()))));
add_element_to_object(&mut cancelObj, &idKey, ternary(is_true(&cancelByCloid), clientOrderId.clone(), self.parse_to_numeric(id.clone())));
append_to_array(&mut cancelReq, cancelObj.clone());
}
}
add_element_to_object(&mut cancelAction, &Value::Str("type".to_string()), ternary(is_true(&cancelByCloid), Value::Str("cancelByCloid".to_string()), Value::Str("cancel".to_string())));
add_element_to_object(&mut cancelAction, &Value::Str("cancels".to_string()), cancelReq.clone());
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("cancelOrdersForSymbols".to_string()), Value::Str("vaultAddress".to_string()), Value::Str("subAccountAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
let mut signature: Value = self.sign_l1_action(cancelAction.clone(), nonce.clone(), &[vaultAddress.clone()]);
add_element_to_object(&mut request, &Value::Str("action".to_string()), cancelAction.clone());
add_element_to_object(&mut request, &Value::Str("signature".to_string()), signature.clone());
if !is_equal(&vaultAddress, &Value::Null) {
params = self.omit(params.clone(), Value::Str("vaultAddress".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("vaultAddress".to_string()), vaultAddress.clone());
}
let mut response: Value = self.private_post_exchange(&[request.clone()]).await;
return Value::List(vec![self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
params = self.omit(params.clone(), Value::List(vec![Value::Str("clientOrderId".to_string()), Value::Str("client_id".to_string())]), &[]);
let mut nonce: Value = self.milliseconds();
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".to_string()));
m.insert("time".to_string(), add(&nonce, &timeout));
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("cancelAllOrdersAfter".to_string()), Value::Str("vaultAddress".to_string()), Value::Str("subAccountAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
let mut signature: Value = self.sign_l1_action(cancelAction.clone(), nonce.clone(), &[vaultAddress.clone()]);
add_element_to_object(&mut request, &Value::Str("action".to_string()), cancelAction.clone());
add_element_to_object(&mut request, &Value::Str("signature".to_string()), signature.clone());
if !is_equal(&vaultAddress, &Value::Null) {
params = self.omit(params.clone(), Value::Str("vaultAddress".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("vaultAddress".to_string()), vaultAddress.clone());
}
let mut response: Value = self.private_post_exchange(&[request.clone()]).await;
return response;
Value::Null
}
pub fn edit_orders_request(&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_810: bool = true;
while { if !__for_first_810 { i = add(&i, &Value::Int(1)); } __for_first_810 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut rawOrder: Value = get_value(&orders, &i);
let mut rawOrder: Value = get_value(&orders, &i);
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".to_string()), Value::Str("client_id".to_string()), &[]);
if !is_equal(&clientOrderId, &Value::Null) {
hasClientOrderId = true;
}
}
}
if is_true(&hasClientOrderId) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_811: bool = true;
while { if !__for_first_811 { i = add(&i, &Value::Int(1)); } __for_first_811 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut rawOrder: Value = get_value(&orders, &i);
let mut rawOrder: Value = get_value(&orders, &i);
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".to_string()), Value::Str("client_id".to_string()), &[]);
if is_equal(&clientOrderId, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" editOrders() all orders must have clientOrderId if at least one has a clientOrderId".to_string()))));
}
}
}
}
params = self.omit(params.clone(), Value::List(vec![Value::Str("slippage".to_string()), Value::Str("clientOrderId".to_string()), Value::Str("client_id".to_string()), Value::Str("slippage".to_string()), Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), Value::Str("stopLossPrice".to_string()), Value::Str("takeProfitPrice".to_string()), Value::Str("timeInForce".to_string())]), &[]);
let mut modifies: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_812: bool = true;
while { if !__for_first_812 { i = add(&i, &Value::Int(1)); } __for_first_812 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut rawOrder: Value = get_value(&orders, &i);
let mut rawOrder: Value = get_value(&orders, &i);
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.clone());
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut type_var: Value = self.safe_string_upper(rawOrder.clone(), Value::Str("type".to_string()), &[]);
let mut isMarket: Value = Value::Bool(is_equal(&type_var, &Value::Str("MARKET".to_string())));
let mut side: Value = self.safe_string_upper(rawOrder.clone(), Value::Str("side".to_string()), &[]);
let mut isBuy: Value = Value::Bool(is_equal(&side, &Value::Str("BUY".to_string())));
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.clone(), "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.clone()]);
let mut defaultTimeInForce: Value = ternary(is_true(&(isMarket)), Value::Str("ioc".to_string()), Value::Str("gtc".to_string()));
let mut postOnly: Value = self.safe_bool_k(orderParams.clone(), "postOnly", &[Value::Bool(false)]);
if is_equal(&postOnly, &Value::Bool(true)) {
defaultTimeInForce = Value::Str("alo".to_string());
}
let mut timeInForce: Value = self.safe_string_lower(orderParams.clone(), Value::Str("timeInForce".to_string()), &[defaultTimeInForce.clone()]);
timeInForce = self.capitalize(timeInForce.clone());
let mut clientOrderId: Value = self.safe_string2(orderParams.clone(), Value::Str("clientOrderId".to_string()), Value::Str("client_id".to_string()), &[]);
let mut triggerPrice: Value = self.safe_string2(orderParams.clone(), Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), &[]);
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 = is_true(&(!is_equal(&stopLossPrice, &Value::Null))) || is_true(&(!is_equal(&takeProfitPrice, &Value::Null)));
let mut reduceOnly: Value = self.safe_bool_k(orderParams.clone(), "reduceOnly", &[Value::Bool(false)]);
orderParams = self.omit(orderParams.clone(), Value::List(vec![Value::Str("slippage".to_string()), Value::Str("timeInForce".to_string()), Value::Str("triggerPrice".to_string()), Value::Str("stopLossPrice".to_string()), Value::Str("takeProfitPrice".to_string()), Value::Str("clientOrderId".to_string()), Value::Str("client_id".to_string()), Value::Str("postOnly".to_string()), Value::Str("reduceOnly".to_string())]), &[]);
let mut px: Value = self.number_to_string(price.clone());
if is_true(&isMarket) {
px = ternary(is_true(&(isBuy)), crate::precise::Precise::stringMul(&px, &crate::precise::Precise::stringAdd(&Value::Str("1".to_string()), &slippage)), crate::precise::Precise::stringMul(&px, &crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &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.clone());
let mut orderType: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_true(&isTrigger) {
let mut isTp: Value = Value::Bool(false);
if !is_equal(&takeProfitPrice, &Value::Null) {
triggerPrice = self.price_to_precision(symbol.clone(), takeProfitPrice.clone());
isTp = Value::Bool(true);
} else {
triggerPrice = self.price_to_precision(symbol.clone(), stopLossPrice.clone());
}
let mut tpSlType: Value = ternary(is_true(&(isTp)), Value::Str("tp".to_string()), Value::Str("sl".to_string()));
add_element_to_object(&mut orderType, &Value::Str("trigger".to_string()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("isMarket".to_string(), isMarket.clone());
m.insert("triggerPx".to_string(), triggerPrice.clone());
m.insert("tpsl".to_string(), tpSlType.clone());
m
}));
} else {
add_element_to_object(&mut orderType, &Value::Str("limit".to_string()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tif".to_string(), timeInForce.clone());
m
}));
}
if is_equal(&triggerPrice, &Value::Null) {
triggerPrice = Value::Str("0".to_string());
}
let mut orderReq: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("a".to_string(), self.parse_to_int(get_value(&market, &Value::Str("baseId".to_string()))));
m.insert("b".to_string(), isBuy.clone());
m.insert("p".to_string(), px.clone());
m.insert("s".to_string(), sz.clone());
m.insert("r".to_string(), reduceOnly.clone());
m.insert("t".to_string(), orderType.clone());
m
});
if !is_equal(&clientOrderId, &Value::Null) {
add_element_to_object(&mut orderReq, &Value::Str("c".to_string()), clientOrderId.clone());
}
let mut modifyReq: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("oid".to_string(), self.parse_to_int(id.clone()));
m.insert("order".to_string(), orderReq.clone());
m
});
append_to_array(&mut modifies, modifyReq.clone());
}
}
let mut nonce: Value = self.milliseconds();
let mut modifyAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("batchModify".to_string()));
m.insert("modifies".to_string(), modifies.clone());
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("editOrder".to_string()), Value::Str("vaultAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
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.clone());
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), signature.clone());
m
});
if !is_equal(&vaultAddress, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("vaultAddress".to_string()), vaultAddress.clone());
}
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&id, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" editOrder() requires an id argument".to_string()))));
}
let mut orderglobalParamsVariable = self.parse_create_edit_order_args(id.clone(), symbol.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params.clone()]);
let mut order: Value = get_value(&orderglobalParamsVariable, &Value::Int(0));
let mut globalParams: Value = get_value(&orderglobalParamsVariable, &Value::Int(1));
let mut orders: Value = self.edit_orders(Value::List(vec![order.clone()]), &[globalParams.clone()]).await;
return get_value(&orders, &Value::Int(0));
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut request: Value = self.edit_orders_request(orders.clone(), &[params.clone()]);
let mut response: Value = self.private_post_exchange(&[request.clone()]).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.clone(), "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut dataObject: Value = self.safe_dict_k(responseObject.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut statuses: Value = self.safe_list_k(dataObject.clone(), "statuses", &[Value::List(vec![])]);
return self.parse_orders(statuses.clone(), &[]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut nonce: Value = self.milliseconds();
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.clone()), &Value::Str("1000000".to_string())));
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("createVault".to_string()));
m.insert("name".to_string(), name.clone());
m.insert("description".to_string(), description.clone());
m.insert("initialUsd".to_string(), usd.clone());
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut signature: Value = self.sign_l1_action(action.clone(), nonce.clone(), &[]);
add_element_to_object(&mut request, &Value::Str("action".to_string()), action.clone());
add_element_to_object(&mut request, &Value::Str("signature".to_string()), signature.clone());
let __ws_arg_21 = self.extend(request.clone(), &[params.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchFundingRateHistory() requires a symbol argument".to_string()))));
}
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".to_string()));
m.insert("coin".to_string(), self.safe_string_k(market.clone(), "baseName", &[]));
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("startTime".to_string()), since.clone());
} else {
let mut maxLimit: Value = ternary(is_true(&(is_equal(&limit, &Value::Null))), Value::Int(500), limit.clone());
add_element_to_object(&mut request, &Value::Str("startTime".to_string()), subtract(&self.milliseconds(), &multiply(&multiply(&multiply(&maxLimit, &Value::Int(60)), &Value::Int(60)), &Value::Int(1000))));
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
params = self.omit(params.clone(), Value::Str("until".to_string()), &[]);
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), until.clone());
}
let __ws_arg_22 = self.extend(request.clone(), &[params.clone()]);
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::List(vec![]);
let mut fundings: Value = Value::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
fundings = response.clone();
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_813: bool = true;
while { if !__for_first_813 { i = add(&i, &Value::Int(1)); } __for_first_813 = false; is_less_than(&i, &get_array_length(&fundings)) } {
let mut entry: Value = get_value(&fundings, &i);
let mut entry: Value = get_value(&fundings, &i);
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.clone(), "fundingRate", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m
}));
}
}
let mut sorted: Value = self.sort_by(result.clone(), Value::Str("timestamp".to_string()), &[]);
return self.filter_by_symbol_since_limit(sorted.clone(), &[symbol.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn get_dex_from_hip3_symbol(&self, mut market: Value) -> Value {
let mut baseName: Value = self.safe_string_k(market.clone(), "baseName", &[Value::Str("".to_string())]);
let mut part: Value = split(&baseName, &Value::Str(":".to_string()));
let mut partsLength: Value = get_array_length(&part);
if is_greater_than(&partsLength, &Value::Int(1)) {
return self.safe_string(part.clone(), 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 userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchOpenOrders".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut method: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOpenOrders".to_string()), Value::Str("method".to_string()), &[Value::Str("frontendOpenOrders".to_string())]); method = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), method.clone());
m.insert("user".to_string(), userAddress.clone());
m
});
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
// check if is hip3 symbol
let mut dexName: Value = self.get_dex_from_hip3_symbol(market.clone());
if !is_equal(&dexName, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("dex".to_string()), dexName.clone());
}
}
let __ws_arg_23 = self.extend(request.clone(), &[params.clone()]);
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::List(vec![]);
let mut rawOrders: Value = Value::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
rawOrders = response.clone();
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_814: bool = true;
while { if !__for_first_814 { i = add(&i, &Value::Int(1)); } __for_first_814 = false; is_less_than(&i, &get_array_length(&rawOrders)) } {
let mut order: Value = get_value(&rawOrders, &i);
let mut order: Value = get_value(&rawOrders, &i);
let mut extendOrder: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_equal(&self.safe_string_k(order.clone(), "status", &[]), &Value::Null) {
add_element_to_object(&mut extendOrder, &Value::Str("ccxtStatus".to_string()), Value::Str("open".to_string()));
}
append_to_array(&mut orderWithStatus, self.extend(order.clone(), &[extendOrder.clone()]));
}
}
return self.parse_orders(orderWithStatus.clone(), &[market.clone(), since.clone(), limit.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.fetch_orders(&[symbol.clone(), Value::Null, Value::Null, params.clone()]).await; // don't filter here because we don't want to catch open orders
let mut closedOrders: Value = self.filter_by_array(orders.clone(), Value::Str("status".to_string()), &[Value::List(vec![Value::Str("closed".to_string())]), Value::Bool(false)]);
return self.filter_by_symbol_since_limit(closedOrders.clone(), &[symbol.clone(), since.clone(), limit.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.fetch_orders(&[symbol.clone(), Value::Null, Value::Null, params.clone()]).await; // don't filter here because we don't want to catch open orders
let mut closedOrders: Value = self.filter_by_array(orders.clone(), Value::Str("status".to_string()), &[Value::List(vec![Value::Str("canceled".to_string())]), Value::Bool(false)]);
return self.filter_by_symbol_since_limit(closedOrders.clone(), &[symbol.clone(), since.clone(), limit.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.fetch_orders(&[symbol.clone(), Value::Null, Value::Null, params.clone()]).await; // don't filter here because we don't want to catch open orders
let mut closedOrders: Value = self.filter_by_array(orders.clone(), Value::Str("status".to_string()), &[Value::List(vec![Value::Str("canceled".to_string()), Value::Str("closed".to_string()), Value::Str("rejected".to_string())]), Value::Bool(false)]);
return self.filter_by_symbol_since_limit(closedOrders.clone(), &[symbol.clone(), since.clone(), limit.clone()]);
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 userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchOrders".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&self.markets, &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".to_string()));
m.insert("user".to_string(), userAddress.clone());
m
});
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
// check if is hip3 symbol
let mut dexName: Value = self.get_dex_from_hip3_symbol(market.clone());
if !is_equal(&dexName, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("dex".to_string()), dexName.clone());
}
}
let __ws_arg_24 = self.extend(request.clone(), &[params.clone()]);
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::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
historicalOrders = response.clone();
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_815: bool = true;
while { if !__for_first_815 { i = add(&i, &Value::Int(1)); } __for_first_815 = false; is_less_than(&i, &get_array_length(&historicalOrders)) } {
let mut rawOrder: Value = get_value(&historicalOrders, &i);
let mut rawOrder: Value = get_value(&historicalOrders, &i);
let mut entry: Value = self.safe_dict_k(rawOrder.clone(), "order", &[]);
if is_equal(&entry, &Value::Null) {
entry = rawOrder.clone();
}
let mut oid: Value = self.safe_string_k(entry.clone(), "oid", &[]);
if !is_equal(&oid, &Value::Null) {
if !is_true(&(Value::Bool(in_op(&deduplicatedByOid, &oid)))) {
add_element_to_object(&mut deduplicatedByOid, &oid, rawOrder.clone());
} else {
let mut existingTimestamp: Value = self.safe_integer_k(get_value(&deduplicatedByOid, &oid), "statusTimestamp", &[]);
let mut currentTimestamp: Value = self.safe_integer_k(rawOrder.clone(), "statusTimestamp", &[]);
if !is_equal(¤tTimestamp, &Value::Null) && is_true(&(is_equal(&existingTimestamp, &Value::Null) || is_greater_than(¤tTimestamp, &existingTimestamp))) {
add_element_to_object(&mut deduplicatedByOid, &oid, rawOrder.clone());
}
}
}
}
}
let mut deduplicated: Value = object_values(&deduplicatedByOid);
return self.parse_orders(deduplicated.clone(), &[market.clone(), since.clone(), limit.clone()]);
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 __destr_tmp = self.handle_public_address(Value::Str("fetchOrder".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut clientOrderId: Value = self.safe_string_k(params.clone(), "clientOrderId", &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("orderStatus".to_string()));
m.insert("user".to_string(), userAddress.clone());
m
});
if !is_equal(&clientOrderId, &Value::Null) {
params = self.omit(params.clone(), Value::Str("clientOrderId".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("oid".to_string()), clientOrderId.clone());
} else {
let mut isClientOrderId: bool = is_greater_than_or_equal(&get_array_length(&id), &Value::Int(34));
add_element_to_object(&mut request, &Value::Str("oid".to_string()), ternary(is_true(&isClientOrderId), id.clone(), self.parse_to_numeric(id.clone())));
}
let __ws_arg_25 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "order", &[]);
return self.parse_order(data.clone(), &[market.clone()]);
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: Value = self.safe_string_k(order.clone(), "error", &[]);
if !is_equal(&error, &Value::Null) {
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.clone());
m.insert("status".to_string(), Value::Str("rejected".to_string()));
m
}), &[]);
}
let mut entry: Value = self.safe_dict_n(order.clone(), Value::List(vec![Value::Str("order".to_string()), Value::Str("resting".to_string()), Value::Str("filled".to_string())]), &[]);
if is_equal(&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 !is_equal(&coin, &Value::Null) {
marketId = self.coin_to_market_id(coin.clone());
}
if is_equal(&self.safe_string_k(entry.clone(), "id", &[]), &Value::Null) {
market = self.safe_market(&[marketId.clone()]);
} else {
market = self.safe_market(&[marketId.clone(), market.clone()]);
}
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut timestamp: Value = self.safe_integer_k(entry.clone(), "timestamp", &[]);
let mut status: Value = self.safe_string2(order.clone(), Value::Str("status".to_string()), Value::Str("ccxtStatus".to_string()), &[]);
order = self.omit(order.clone(), Value::List(vec![Value::Str("ccxtStatus".to_string())]), &[]);
let mut side: Value = self.safe_string_k(entry.clone(), "side", &[]);
if !is_equal(&side, &Value::Null) {
side = ternary(is_true(&(is_equal(&side, &Value::Str("A".to_string())))), Value::Str("sell".to_string()), Value::Str("buy".to_string()));
}
let mut totalAmount: Value = self.safe_string2(entry.clone(), Value::Str("origSz".to_string()), Value::Str("totalSz".to_string()), &[]);
let mut remaining: Value = self.safe_string_k(entry.clone(), "sz", &[]);
let mut tif: Value = self.safe_string_upper(entry.clone(), Value::Str("tif".to_string()), &[]);
let mut postOnly: Value = Value::Null;
if !is_equal(&tif, &Value::Null) {
postOnly = Value::Bool(is_equal(&tif, &Value::Str("ALO".to_string())));
}
let mut isTrigger: bool = is_equal(&self.safe_bool_k(entry.clone(), "isTrigger", &[]), &Value::Bool(true));
let mut triggerPx: Value = ternary(is_true(&isTrigger), self.safe_number_k(entry.clone(), "triggerPx", &[]), 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(entry.clone(), Value::Str("orderType".to_string()), &[Value::Str("".to_string())]);
let mut stopLossPrice: Value = Value::Null;
let mut takeProfitPrice: Value = Value::Null;
if !is_equal(&triggerPx, &Value::Null) {
if is_greater_than_or_equal(&get_index_of(&orderTypeRaw, &Value::Str("stop".to_string())), &Value::Int(0)) {
stopLossPrice = triggerPx.clone();
} else if is_greater_than_or_equal(&get_index_of(&orderTypeRaw, &Value::Str("take profit".to_string())), &Value::Int(0)) {
takeProfitPrice = triggerPx.clone();
}
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.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.clone()));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), self.safe_integer_k(order.clone(), "statusTimestamp", &[]));
m.insert("symbol".to_string(), symbol.clone());
m.insert("type".to_string(), self.parse_order_type(self.safe_string_lower(entry.clone(), Value::Str("orderType".to_string()), &[])));
m.insert("timeInForce".to_string(), tif.clone());
m.insert("postOnly".to_string(), postOnly.clone());
m.insert("reduceOnly".to_string(), self.safe_bool_k(entry.clone(), "reduceOnly", &[]));
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), self.safe_string_k(entry.clone(), "limitPx", &[]));
m.insert("triggerPrice".to_string(), triggerPx.clone());
m.insert("stopLossPrice".to_string(), stopLossPrice.clone());
m.insert("takeProfitPrice".to_string(), takeProfitPrice.clone());
m.insert("amount".to_string(), totalAmount.clone());
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), self.safe_string_k(entry.clone(), "avgPx", &[]));
m.insert("filled".to_string(), self.safe_string_k(filled.clone(), "totalSz", &[crate::precise::Precise::stringSub(&totalAmount, &remaining)]));
m.insert("remaining".to_string(), remaining.clone());
m.insert("status".to_string(), self.parse_order_status(status.clone()));
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[market.clone()]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
if is_equal(&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".to_string()));
m.insert("filled".to_string(), Value::Str("closed".to_string()));
m.insert("open".to_string(), Value::Str("open".to_string()));
m.insert("canceled".to_string(), Value::Str("canceled".to_string()));
m.insert("rejected".to_string(), Value::Str("rejected".to_string()));
m.insert("marginCanceled".to_string(), Value::Str("canceled".to_string()));
m
});
if is_true(&Value::Bool(ends_with(&status, &Value::Str("Rejected".to_string())))) {
return Value::Str("rejected".to_string());
}
if is_true(&Value::Bool(ends_with(&status, &Value::Str("Canceled".to_string())))) {
return Value::Str("canceled".to_string());
}
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_order_type(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stop limit".to_string(), Value::Str("limit".to_string()));
m.insert("stop market".to_string(), Value::Str("market".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
/*
* @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 userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchMyTrades".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("user".to_string(), userAddress.clone());
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("type".to_string()), Value::Str("userFillsByTime".to_string()));
add_element_to_object(&mut request, &Value::Str("startTime".to_string()), since.clone());
} else {
add_element_to_object(&mut request, &Value::Str("type".to_string()), Value::Str("userFills".to_string()));
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
params = self.omit(params.clone(), Value::Str("until".to_string()), &[]);
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), until.clone());
}
let __ws_arg_26 = self.extend(request.clone(), &[params.clone()]);
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::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
myFills = response.clone();
}
return self.parse_trades(myFills.clone(), &[market.clone(), since.clone(), limit.clone()]);
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.clone());
market = self.safe_market(&[marketId.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut id: Value = self.safe_string_k(trade.clone(), "tid", &[]);
let mut side: Value = self.safe_string_k(trade.clone(), "side", &[]);
if !is_equal(&side, &Value::Null) {
side = ternary(is_true(&(is_equal(&side, &Value::Str("A".to_string())))), Value::Str("sell".to_string()), Value::Str("buy".to_string()));
}
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 !is_equal(&crossed, &Value::Null) {
takerOrMaker = ternary(is_true(&crossed), Value::Str("taker".to_string()), Value::Str("maker".to_string()));
}
let mut builderFee: Value = self.safe_string_k(trade.clone(), "builderFee", &[]);
if !is_equal(&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.clone()));
m.insert("symbol".to_string(), symbol.clone());
m.insert("id".to_string(), id.clone());
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.clone());
m.insert("takerOrMaker".to_string(), takerOrMaker.clone());
m.insert("price".to_string(), price.clone());
m.insert("amount".to_string(), amount.clone());
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.clone());
m.insert("currency".to_string(), self.safe_string_k(trade.clone(), "feeToken", &[]));
m.insert("rate".to_string(), Value::Null);
m
}));
m
}), &[market.clone()]);
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::List(vec![symbol.clone()]), params.clone()]).await;
return self.safe_dict(positions.clone(), 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 is_equal(&symbols, &Value::Null) {
return Value::Null;
}
let mut symbolsLength: Value = get_array_length(&symbols);
if is_equal(&symbolsLength, &Value::Int(0)) {
return Value::Null;
}
let mut dexName: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_816: bool = true;
while { if !__for_first_816 { i = add(&i, &Value::Int(1)); } __for_first_816 = false; is_less_than(&i, &symbolsLength) } {
if is_equal(&dexName, &Value::Null) {
let mut market: Value = self.market(get_value(&symbols, &i));
dexName = self.get_dex_from_hip3_symbol(market.clone());
} else {
let mut market: Value = self.market(get_value(&symbols, &i));
let mut currentDexName: Value = self.get_dex_from_hip3_symbol(market.clone());
if !is_equal(¤tDexName, &dexName) {
panic!("{}", crate::exchange_errors::not_supported(add(&add(&add(&self.id, &Value::Str(" ".to_string())), &methodName), &Value::Str(" only supports fetching positions for one DEX at a time for HIP3 markets".to_string()))));
}
}
}
}
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchPositions".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
symbols = self.market_symbols(&[symbols.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("clearinghouseState".to_string()));
m.insert("user".to_string(), userAddress.clone());
m
});
let mut dexName: Value = self.get_dex_from_symbols(Value::Str("fetchPositions".to_string()), &[symbols.clone()]);
if !is_equal(&dexName, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("dex".to_string()), dexName.clone());
}
let __ws_arg_27 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "assetPositions", &[Value::List(vec![])]);
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_817: bool = true;
while { if !__for_first_817 { i = add(&i, &Value::Int(1)); } __for_first_817 = false; is_less_than(&i, &get_array_length(&data)) } {
append_to_array(&mut result, self.parse_position(get_value(&data, &i), &[]));
}
}
return self.filter_by_array_positions(result.clone(), Value::Str("symbol".to_string()), &[symbols.clone(), Value::Bool(false)]);
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.clone());
market = self.safe_market(&[marketId.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
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(is_equal(&marginMode, &Value::Str("isolated".to_string())));
let mut rawSize: Value = self.safe_string_k(entry.clone(), "szi", &[]);
let mut size: Value = rawSize.clone();
let mut side: Value = Value::Null;
if !is_equal(&size, &Value::Null) {
side = ternary(is_true(&crate::precise::Precise::stringGt(&rawSize, &Value::Str("0".to_string()))), Value::Str("long".to_string()), Value::Str("short".to_string()));
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 is_true(&isIsolated) {
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".to_string()));
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol.clone());
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("isolated".to_string(), isIsolated.clone());
m.insert("hedged".to_string(), Value::Null);
m.insert("side".to_string(), side.clone());
m.insert("contracts".to_string(), self.parse_number(size.clone(), &[]));
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.clone(), "value", &[]));
m.insert("collateral".to_string(), self.parse_number(marginUsed.clone(), &[]));
m.insert("initialMargin".to_string(), self.parse_number(initialMargin.clone(), &[]));
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.clone(), &[]));
m.insert("liquidationPrice".to_string(), self.safe_number_k(entry.clone(), "liquidationPx", &[]));
m.insert("marginMode".to_string(), marginMode.clone());
m.insert("percentage".to_string(), self.parse_number(percentage.clone(), &[]));
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 is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" setMarginMode() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut leverage: Value = self.safe_integer_k(params.clone(), "leverage", &[]);
if is_equal(&leverage, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" setMarginMode() requires a leverage parameter".to_string()))));
}
let mut asset: Value = self.parse_to_int(get_value(&market, &Value::Str("baseId".to_string())));
let mut isCross: Value = Value::Bool(is_equal(&marginMode, &Value::Str("cross".to_string())));
let mut nonce: Value = self.milliseconds();
params = self.omit(params.clone(), Value::List(vec![Value::Str("leverage".to_string())]), &[]);
let mut updateAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("updateLeverage".to_string()));
m.insert("asset".to_string(), asset.clone());
m.insert("isCross".to_string(), isCross.clone());
m.insert("leverage".to_string(), leverage.clone());
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("setMarginMode".to_string()), Value::Str("vaultAddress".to_string()), Value::Str("subAccountAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if !is_equal(&vaultAddress, &Value::Null) {
if is_true(&Value::Bool(starts_with(&vaultAddress, &Value::Str("0x".to_string())))) {
vaultAddress = replace_str(&vaultAddress, &Value::Str("0x".to_string()), &Value::Str("".to_string()));
}
}
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.clone());
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), signature.clone());
m
});
if !is_equal(&vaultAddress, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("vaultAddress".to_string()), vaultAddress.clone());
}
let mut response: Value = self.private_post_exchange(&[request.clone()]).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 is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" setLeverage() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut marginMode: Value = self.safe_string_k(params.clone(), "marginMode", &[Value::Str("cross".to_string())]);
let mut isCross: Value = Value::Bool(is_equal(&marginMode, &Value::Str("cross".to_string())));
let mut asset: Value = self.parse_to_int(get_value(&market, &Value::Str("baseId".to_string())));
let mut nonce: Value = self.milliseconds();
params = self.omit(params.clone(), Value::Str("marginMode".to_string()), &[]);
let mut updateAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("updateLeverage".to_string()));
m.insert("asset".to_string(), asset.clone());
m.insert("isCross".to_string(), isCross.clone());
m.insert("leverage".to_string(), leverage.clone());
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("setLeverage".to_string()), Value::Str("vaultAddress".to_string()), Value::Str("subAccountAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
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.clone());
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), signature.clone());
m
});
if !is_equal(&vaultAddress, &Value::Null) {
params = self.omit(params.clone(), Value::Str("vaultAddress".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("vaultAddress".to_string()), vaultAddress.clone());
}
let mut response: Value = self.private_post_exchange(&[request.clone()]).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.clone(), amount.clone(), Value::Str("add".to_string()), &[params.clone()]).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.clone(), amount.clone(), Value::Str("reduce".to_string()), &[params.clone()]).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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut asset: Value = self.parse_to_int(get_value(&market, &Value::Str("baseId".to_string())));
let mut sz: Value = self.parse_to_int(crate::precise::Precise::stringMul(&self.amount_to_precision(symbol.clone(), amount.clone()), &Value::Str("1000000".to_string())));
if is_equal(&type_var, &Value::Str("reduce".to_string())) {
sz = negate(&sz);
}
let mut nonce: Value = self.milliseconds();
let mut updateAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("updateIsolatedMargin".to_string()));
m.insert("asset".to_string(), asset.clone());
m.insert("isBuy".to_string(), Value::Bool(true));
m.insert("ntli".to_string(), sz.clone());
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("modifyMargin".to_string()), Value::Str("vaultAddress".to_string()), Value::Str("subAccountAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
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.clone());
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), signature.clone());
m
});
if !is_equal(&vaultAddress, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("vaultAddress".to_string()), vaultAddress.clone());
}
let mut response: Value = self.private_post_exchange(&[request.clone()]).await;
let __ws_arg_28 = self.parse_margin_modification(response.clone(), &[market.clone()]);
let __ws_arg_29 = self.safe_string_k(response.clone(), "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.clone());
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".to_string()));
m.insert("amount".to_string(), Value::Null);
m.insert("total".to_string(), Value::Null);
m.insert("code".to_string(), self.safe_string_k(market.clone(), "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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut isSandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[]);
let mut nonce: Value = self.milliseconds();
if is_true(&self.in_array(fromAccount.clone(), Value::List(vec![Value::Str("spot".to_string()), Value::Str("swap".to_string()), Value::Str("perp".to_string())]))) {
// handle swap <> spot account transfer
if !is_true(&self.in_array(toAccount.clone(), Value::List(vec![Value::Str("spot".to_string()), Value::Str("swap".to_string()), Value::Str("perp".to_string())]))) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" transfer() only support spot <> swap transfer".to_string()))));
}
let mut strAmount: Value = self.number_to_string(amount.clone());
let mut vaultAddress: Value = self.safe_string2(params.clone(), Value::Str("vaultAddress".to_string()), Value::Str("subAccountAddress".to_string()), &[]);
if !is_equal(&vaultAddress, &Value::Null) {
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
strAmount = add(&add(&strAmount, &Value::Str(" subaccount:".to_string())), &vaultAddress);
}
let mut strAmountFinal: Value = strAmount.clone(); // java req
let mut toPerp: Value = Value::Bool(is_true(&(is_equal(&toAccount, &Value::Str("perp".to_string())))) || is_true(&(is_equal(&toAccount, &Value::Str("swap".to_string())))));
let mut transferPayload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), ternary(is_true(&(is_equal(&isSandboxMode, &Value::Bool(true)))), Value::Str("Testnet".to_string()), Value::Str("Mainnet".to_string())));
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(), get_value(&transferPayload, &Value::Str("hyperliquidChain".to_string())));
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".to_string()));
m.insert("type".to_string(), Value::Str("usdClassTransfer".to_string()));
m.insert("amount".to_string(), strAmountFinal.clone());
m.insert("toPerp".to_string(), toPerp.clone());
m.insert("nonce".to_string(), nonce.clone());
m
}));
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), transferSig.clone());
m
});
let mut transferResponse: Value = self.private_post_exchange(&[transferRequest.clone()]).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.clone(), &[currency.clone()]);
}
// transfer between main account and subaccount
let mut isDeposit: Value = Value::Bool(false);
let mut subAccountAddress: Value = Value::Null;
if is_equal(&fromAccount, &Value::Str("main".to_string())) {
subAccountAddress = toAccount.clone();
isDeposit = Value::Bool(true);
} else if is_equal(&toAccount, &Value::Str("main".to_string())) {
subAccountAddress = fromAccount.clone();
} else {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" transfer() only support main <> subaccount transfer".to_string()))));
}
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: Value = self.safe_string_k(params.clone(), "type", &[]);
params = self.omit(params.clone(), Value::Str("type".to_string()), &[]);
let mut isUsdc: bool = is_true(&(is_equal(&code, &Value::Null))) || is_true(&(is_equal(&to_upper(&code), &Value::Str("USDC".to_string()))));
if is_true(&isUsdc) && is_true(&(!is_equal(&transferType, &Value::Str("spot".to_string())))) {
// 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".to_string())));
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("subAccountTransfer".to_string()));
m.insert("subAccountUser".to_string(), subAccountAddress.clone());
m.insert("isDeposit".to_string(), isDeposit.clone());
m.insert("usd".to_string(), usd.clone());
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 is_equal(&code, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" transfer() requires a currency code for spot sub-account transfers".to_string()))));
}
let mut currency: Value = self.currency(code.clone());
let mut currencyInfo: Value = self.safe_dict_k(currency.clone(), "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.clone(), "tokenId", &[]);
let mut token: Value = add(&add(&tokenName, &Value::Str(":".to_string())), &tokenId);
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("subAccountSpotTransfer".to_string()));
m.insert("subAccountUser".to_string(), subAccountAddress.clone());
m.insert("isDeposit".to_string(), isDeposit.clone());
m.insert("token".to_string(), token.clone());
m.insert("amount".to_string(), self.number_to_string(amount.clone()));
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(), &[]);
}
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.clone()]));
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.clone(), "status", &[Value::Str("ok".to_string())]));
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
self.check_address(&[address.clone()]);
if !is_equal(&code, &Value::Null) {
code = to_upper(&code);
if !is_equal(&code, &Value::Str("USDC".to_string())) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" withdraw() only support USDC".to_string()))));
}
}
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("withdraw".to_string()), Value::Str("vaultAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
params = self.omit(params.clone(), Value::Str("vaultAddress".to_string()), &[]);
let mut nonce: Value = self.milliseconds();
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut sig: Value = Value::Null;
if !is_equal(&vaultAddress, &Value::Null) {
action = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("vaultTransfer".to_string()));
m.insert("vaultAddress".to_string(), add(&Value::Str("0x".to_string()), &vaultAddress));
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(), ternary(is_true(&(is_equal(&isSandboxMode, &Value::Bool(true)))), Value::Str("Testnet".to_string()), Value::Str("Mainnet".to_string())));
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(), get_value(&payload, &Value::Str("hyperliquidChain".to_string())));
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".to_string()));
m.insert("destination".to_string(), address.clone());
m.insert("amount".to_string(), to_string_val(&amount));
m.insert("time".to_string(), nonce.clone());
m.insert("type".to_string(), Value::Str("withdraw3".to_string()));
m
});
}
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_transaction(response.clone(), &[]);
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 !is_equal(&feeCost, &Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Str("USDC".to_string()));
m.insert("cost".to_string(), feeCost.clone());
m
});
}
let mut internal: Value = Value::Null;
let mut type_var: Value = self.safe_string_k(delta.clone(), "type", &[]);
if !is_equal(&type_var, &Value::Null) {
internal = Value::Bool(is_equal(&type_var, &Value::Str("internalTransfer".to_string())));
}
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.clone()));
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.clone(), "usdc", &[]));
m.insert("currency".to_string(), Value::Null);
m.insert("status".to_string(), self.safe_string_k(transaction.clone(), "status", &[]));
m.insert("updated".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("internal".to_string(), internal.clone());
m.insert("fee".to_string(), fee.clone());
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchTradingFee".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
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("userFees".to_string()));
m.insert("user".to_string(), userAddress.clone());
m
});
let __ws_arg_30 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "userAddRate", &[]));
m
});
return self.parse_trading_fee(data.clone(), &[market.clone()]);
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.clone()]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), fee.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("maker".to_string(), self.safe_number_k(fee.clone(), "userAddRate", &[]));
m.insert("taker".to_string(), self.safe_number_k(fee.clone(), "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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchLedger".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userNonFundingLedgerUpdates".to_string()));
m.insert("user".to_string(), userAddress.clone());
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("startTime".to_string()), since.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), until.clone());
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
}
let __ws_arg_31 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_31]).await;
return self.parse_ledger(response.clone(), &[Value::Null, since.clone(), limit.clone()]);
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 !is_equal(&feeCost, &Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Str("USDC".to_string()));
m.insert("cost".to_string(), feeCost.clone());
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.clone(), "user", &[]));
m.insert("referenceId".to_string(), self.safe_string_k(item.clone(), "hash", &[]));
m.insert("type".to_string(), self.parse_ledger_entry_type(type_var.clone()));
m.insert("currency".to_string(), Value::Null);
m.insert("amount".to_string(), self.parse_number(amount.clone(), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
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.clone());
m
}), &[currency.clone()]);
Value::Null
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Value {
let mut ledgerType: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("internalTransfer".to_string(), Value::Str("transfer".to_string()));
m.insert("accountClassTransfer".to_string(), Value::Str("transfer".to_string()));
m
});
return self.safe_string(ledgerType.clone(), type_var.clone(), &[type_var.clone()]);
Value::Null
}
/*
* @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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchDepositsWithdrawals".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userNonFundingLedgerUpdates".to_string()));
m.insert("user".to_string(), userAddress.clone());
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("startTime".to_string()), since.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
if is_equal(&since, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchDeposits requires since while until is set".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), until.clone());
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
}
let __ws_arg_32 = self.extend(request.clone(), &[params.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::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
depositLedger = response.clone();
}
let mut records: Value = self.extract_type_from_delta(&[depositLedger.clone()]);
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchDepositsWithdrawals".to_string()), Value::Str("vaultAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
let mut deposits: Value = Value::List(vec![]);
if !is_equal(&vaultAddress, &Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_818: bool = true;
while { if !__for_first_818 { i = add(&i, &Value::Int(1)); } __for_first_818 = false; is_less_than(&i, &get_array_length(&records)) } {
let mut record: Value = get_value(&records, &i);
let mut record: Value = get_value(&records, &i);
if is_equal(&get_value(&record, &Value::Str("type".to_string())), &Value::Str("vaultDeposit".to_string())) {
let mut delta: Value = self.safe_dict_k(record.clone(), "delta", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if is_equal(&get_value(&delta, &Value::Str("vault".to_string())), &add(&Value::Str("0x".to_string()), &vaultAddress)) {
append_to_array(&mut deposits, record.clone());
}
}
}
}
} else {
deposits = self.filter_by_array(records.clone(), Value::Str("type".to_string()), &[Value::List(vec![Value::Str("deposit".to_string())]), Value::Bool(false)]);
}
return self.parse_transactions(deposits.clone(), &[Value::Null, since.clone(), limit.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchDepositsWithdrawals".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userNonFundingLedgerUpdates".to_string()));
m.insert("user".to_string(), userAddress.clone());
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("startTime".to_string()), since.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), until.clone());
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
}
let __ws_arg_33 = self.extend(request.clone(), &[params.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::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
withdrawalLedger = response.clone();
}
let mut records: Value = self.extract_type_from_delta(&[withdrawalLedger.clone()]);
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchDepositsWithdrawals".to_string()), Value::Str("vaultAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
let mut withdrawals: Value = Value::List(vec![]);
if !is_equal(&vaultAddress, &Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_819: bool = true;
while { if !__for_first_819 { i = add(&i, &Value::Int(1)); } __for_first_819 = false; is_less_than(&i, &get_array_length(&records)) } {
let mut record: Value = get_value(&records, &i);
let mut record: Value = get_value(&records, &i);
if is_equal(&get_value(&record, &Value::Str("type".to_string())), &Value::Str("vaultWithdraw".to_string())) {
let mut delta: Value = self.safe_dict_k(record.clone(), "delta", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if is_equal(&get_value(&delta, &Value::Str("vault".to_string())), &add(&Value::Str("0x".to_string()), &vaultAddress)) {
append_to_array(&mut withdrawals, record.clone());
}
}
}
}
} else {
withdrawals = self.filter_by_array(records.clone(), Value::Str("type".to_string()), &[Value::List(vec![Value::Str("withdraw".to_string())]), Value::Bool(false)]);
}
return self.parse_transactions(withdrawals.clone(), &[Value::Null, since.clone(), limit.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut swapMarkets: Value = self.fetch_swap_markets(&[]).await;
return self.parse_open_interests(swapMarkets.clone(), &[symbols.clone()]);
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
}));
symbol = self.symbol(symbol.clone());
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut ois: Value = self.fetch_open_interests(&[Value::List(vec![symbol.clone()]), params.clone()]).await;
return get_value(&ois, &symbol);
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
// }
//
interest = self.safe_dict_k(interest.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut coin: Value = self.safe_string_k(interest.clone(), "name", &[]);
let mut marketId: Value = Value::Null;
if !is_equal(&coin, &Value::Null) {
marketId = self.coin_to_market_id(coin.clone());
}
return self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[]));
m.insert("openInterestAmount".to_string(), self.safe_number_k(interest.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(), interest.clone());
m
}), &[market.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut userAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_public_address(Value::Str("fetchFundingHistory".to_string()), params.clone()); userAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("user".to_string(), userAddress.clone());
m.insert("type".to_string(), Value::Str("userFunding".to_string()));
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("startTime".to_string()), since.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
params = self.omit(params.clone(), Value::Str("until".to_string()), &[]);
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), until.clone());
}
let __ws_arg_34 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_34]).await;
return self.parse_incomes(response.clone(), &[market.clone(), since.clone(), limit.clone()]);
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 !is_equal(&coin, &Value::Null) {
marketId = self.coin_to_market_id(coin.clone());
}
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut amount: Value = self.safe_string_k(delta.clone(), "usdc", &[]);
let mut code: Value = self.safe_string_k(market.clone(), "settle", &[Value::Str("USDC".to_string())]);
let mut rate: Value = self.safe_number_k(delta.clone(), "fundingRate", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), income.clone());
m.insert("symbol".to_string(), get_value(&market, &Value::Str("symbol".to_string())));
m.insert("code".to_string(), code.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("id".to_string(), id.clone());
m.insert("amount".to_string(), self.parse_number(amount.clone(), &[]));
m.insert("rate".to_string(), rate.clone());
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.milliseconds();
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".to_string()));
m.insert("weight".to_string(), weight.clone());
m
});
let mut signature: Value = self.sign_l1_action(action.clone(), nonce.clone(), &[]);
add_element_to_object(&mut request, &Value::Str("action".to_string()), action.clone());
add_element_to_object(&mut request, &Value::Str("signature".to_string()), signature.clone());
let __ws_arg_35 = self.extend(request.clone(), &[params.clone()]);
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.milliseconds();
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".to_string()));
m.insert("name".to_string(), name.clone());
m
});
let mut expiresAfter: Value = self.safe_integer_k(params.clone(), "expiresAfter", &[]);
if !is_equal(&expiresAfter, &Value::Null) {
params = self.omit(params.clone(), Value::Str("expiresAfter".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("expiresAfter".to_string()), expiresAfter.clone());
}
let mut signature: Value = self.sign_l1_action(action.clone(), nonce.clone(), &[Value::Null, expiresAfter.clone()]);
add_element_to_object(&mut request, &Value::Str("action".to_string()), action.clone());
add_element_to_object(&mut request, &Value::Str("signature".to_string()), signature.clone());
let __ws_arg_36 = self.extend(request.clone(), &[params.clone()]);
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::List(vec![]));
let mut records: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_820: bool = true;
while { if !__for_first_820 { i = add(&i, &Value::Int(1)); } __for_first_820 = false; is_less_than(&i, &get_array_length(&data)) } {
let mut record: Value = get_value(&data, &i);
let mut record: Value = get_value(&data, &i);
{ let __be_tmp = get_value(&get_value(&record, &Value::Str("delta".to_string())), &Value::Str("type".to_string())); add_element_to_object(&mut record, &Value::Str("type".to_string()), __be_tmp); };
append_to_array(&mut records, record.clone());
}
}
return records;
Value::Null
}
pub fn format_vault_address(&self, optional_args: &[Value]) -> Value {
let mut address = get_arg(optional_args, 0, Value::Null);
if is_equal(&address, &Value::Null) {
return Value::Null;
}
if is_true(&Value::Bool(starts_with(&address, &Value::Str("0x".to_string())))) {
return replace_str(&address, &Value::Str("0x".to_string()), &Value::Str("".to_string()));
}
return address;
Value::Null
}
pub fn handle_public_address(&self, mut methodName: Value, mut params: Value) -> Value {
let mut userAux: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), methodName.clone(), Value::Str("user".to_string()), Value::Str("subAccountAddress".to_string()), &[]); userAux = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut user: Value = userAux.clone();
{ let __destr_tmp = self.handle_option_and_params(params.clone(), methodName.clone(), Value::Str("address".to_string()), &[userAux.clone()]); user = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&(!is_equal(&user, &Value::Null))) && is_true(&(!is_equal(&user, &Value::Str("".to_string())))) {
return Value::List(vec![user.clone(), params.clone()]);
}
if is_true(&(!is_equal(&self.walletAddress, &Value::Null))) && is_true(&(!is_equal(&self.walletAddress, &Value::Str("".to_string())))) {
return Value::List(vec![self.walletAddress.clone(), params.clone()]);
}
panic!("{}", crate::exchange_errors::arguments_required(add(&add(&add(&self.id, &Value::Str(" ".to_string())), &methodName), &Value::Str("() requires a user parameter inside 'params' or the wallet address set".to_string()))));
Value::Null
}
pub fn coin_to_market_id(&self, mut coin: Value) -> Value {
// handle also hip3 tokens like flx:CRCL
if is_equal(&coin, &Value::Null) {
return Value::Null;
}
let mut hi3TokensByname: Value = self.safe_dict_k(self.options.clone(), "hip3TokensByName", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if !is_equal(&self.safe_dict(hi3TokensByname.clone(), coin.clone(), &[]), &Value::Null) {
let mut hip3Dict: Value = self.safe_dict(hi3TokensByname.clone(), coin.clone(), &[]);
let mut quote: Value = self.safe_string_k(hip3Dict.clone(), "quote", &[Value::Str("USDC".to_string())]);
let mut code: Value = self.safe_string_k(hip3Dict.clone(), "code", &[coin.clone()]);
return add(&add(&add(&add(&code, &Value::Str("/".to_string())), "e), &Value::Str(":".to_string())), "e);
}
if is_greater_than(&get_index_of(&coin, &Value::Str("/".to_string())), &negate(&Value::Int(1))) || is_greater_than(&get_index_of(&coin, &Value::Str("@".to_string())), &negate(&Value::Int(1))) {
return coin;
}
if is_greater_than(&get_index_of(&coin, &Value::Str(":".to_string())), &negate(&Value::Int(1))) {
coin = replace_str(&coin, &Value::Str(":".to_string()), &Value::Str("-".to_string())); // hip3
}
return add(&self.safe_currency_code(coin.clone(), &[]), &Value::Str("/USDC:USDC".to_string()));
Value::Null
}
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 is_true(&(is_equal(&response, &Value::Null))) || is_true(&(is_equal(&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: Value = self.safe_string_k(response.clone(), "status", &[Value::Str("".to_string())]);
let mut error: Value = self.safe_string_k(response.clone(), "error", &[]);
let mut message: Value = Value::Null;
if is_equal(&status, &Value::Str("err".to_string())) {
message = self.safe_string_k(response.clone(), "response", &[]);
} else if is_equal(&status, &Value::Str("unknownOid".to_string())) {
panic!("{}", crate::exchange_errors::order_not_found(add(&add(&self.id, &Value::Str(" ".to_string())), &body)));
} else if !is_equal(&error, &Value::Null) {
message = error.clone();
} else {
let mut responsePayload: Value = self.safe_dict_k(response.clone(), "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(responsePayload.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut statuses: Value = self.safe_list_k(data.clone(), "statuses", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_821: bool = true;
while { if !__for_first_821 { i = add(&i, &Value::Int(1)); } __for_first_821 = false; is_less_than(&i, &get_array_length(&statuses)) } {
message = self.safe_string_k(get_value(&statuses, &i), "error", &[]);
if !is_equal(&message, &Value::Null) {
break;
}
}
}
if is_true(&Value::Bool(in_op(&data, &Value::Str("status".to_string())))) {
let mut errorStatus: Value = self.safe_dict_k(data.clone(), "status", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut errorMsg: Value = self.safe_string_k(errorStatus.clone(), "error", &[]);
if !is_equal(&errorStatus, &Value::Null) {
message = errorMsg.clone();
}
}
}
let mut feedback: Value = add(&add(&self.id, &Value::Str(" ".to_string())), &body);
let mut nonEmptyMessage: bool = is_true(&(!is_equal(&message, &Value::Null))) && is_true(&(!is_equal(&message, &Value::Str("".to_string()))));
if is_true(&nonEmptyMessage) {
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), message.clone(), feedback.clone());
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), message.clone(), feedback.clone());
}
if is_true(&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".to_string()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".to_string()));
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 url: Value = add(&add(&self.implode_hostname(get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &api)), &Value::Str("/".to_string())), &path);
if is_equal(&method, &Value::Str("POST".to_string())) {
headers = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Content-Type".to_string(), Value::Str("application/json".to_string()));
m
});
body = self.json(params.clone());
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), body.clone());
m.insert("headers".to_string(), headers.clone());
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
}));
if is_true(&(Value::Bool(in_op(&config, &Value::Str("byType".to_string()))))) && is_true(&(Value::Bool(in_op(¶ms, &Value::Str("type".to_string()))))) {
let mut type_var: Value = get_value(¶ms, &Value::Str("type".to_string()));
let mut byType: Value = get_value(&config, &Value::Str("byType".to_string()));
if is_true(&Value::Bool(in_op(&byType, &type_var))) {
return get_value(&byType, &type_var);
}
}
return self.safe_value_k(config.clone(), "cost", &[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.clone());
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("createOrder".to_string()), Value::Str("vaultAddress".to_string()), Value::Str("subAccountAddress".to_string()), &[]); vaultAddress = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]);
symbol = get_value(&market, &Value::Str("symbol".to_string()));
let mut order: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.clone());
m.insert("type".to_string(), type_var.clone());
m.insert("side".to_string(), side.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("price".to_string(), price.clone());
m.insert("params".to_string(), params.clone());
m
});
let mut globalParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&vaultAddress, &Value::Null) {
add_element_to_object(&mut globalParams, &Value::Str("vaultAddress".to_string()), vaultAddress.clone());
}
if !is_equal(&id, &Value::Null) {
add_element_to_object(&mut order, &Value::Str("id".to_string()), id.clone());
}
return Value::List(vec![order.clone(), globalParams.clone()]);
Value::Null
}
}