// 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;
use crate::pro::*;
use crate::prediction_exchange_generated::PredictionBase;
use crate::prediction_exchange::PredictionRuntime;
pub struct HyperliquidCore {
pub exchange: crate::prediction_exchange::PredictionExchange,
}
impl HyperliquidCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { exchange: crate::prediction_exchange::PredictionExchange::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_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_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_prediction_trade(self, trade, &[market.clone()])
}
fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_prediction_order(self, order, &[market.clone()])
}
fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HyperliquidCore.
HyperliquidCore::parse_prediction_position(self, position, &[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)),
"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_outcome_parent_symbol" => self.build_outcome_parent_symbol(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()[..]),
"build_outcome_symbol" => self.build_outcome_symbol(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_price_precision" => self.calculate_price_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).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_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,
"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,
"fetch_balance" => self.fetch_balance(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_events" => self.fetch_events(&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_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_positions" => self.fetch_positions(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_tickers" => self.fetch_tickers(&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,
"find_outcome_in_market" => self.find_outcome_in_market(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"format_vault_address" => self.format_vault_address(&args.get(0..).unwrap_or(&[]).to_vec()[..]),
"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,
"outcome_asset_id" => self.outcome_asset_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"outcome_coin" => self.outcome_coin(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"outcome_encoding" => self.outcome_encoding(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"outcome_token" => self.outcome_token(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_event" => self.parse_event(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_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_outcome_description" => self.parse_outcome_description(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_outcome_input_side_hint" => self.parse_outcome_input_side_hint(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_outcome_market" => self.parse_outcome_market(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()[..]),
"parse_prediction_order" => self.parse_prediction_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_prediction_position" => self.parse_prediction_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_prediction_ticker" => self.parse_prediction_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_prediction_trade" => self.parse_prediction_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_time_in_force" => self.parse_time_in_force(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"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)),
"resolve_outcome_input" => self.resolve_outcome_input(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"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)),
// Prediction Core: fall through to prediction base methods (then Exchange base).
_ => self.call_dynamic_prediction_base(method, args).await,
}
})
}
}
impl crate::prediction_exchange_generated::PredictionBase for HyperliquidCore {
fn pred(&self) -> &crate::prediction_exchange::PredictionExchange { &self.exchange }
fn pred_mut(&mut self) -> &mut crate::prediction_exchange::PredictionExchange { &mut self.exchange }
}
impl std::ops::Deref for HyperliquidCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.exchange) }
}
impl std::ops::DerefMut for HyperliquidCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&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("rateLimit".to_string(), Value::Int(50));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(false));
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(false));
m.insert("margin".to_string(), Value::Bool(false));
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("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchCurrencies".to_string(), Value::Bool(false));
m.insert("fetchEvents".to_string(), Value::Bool(true));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".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("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("prediction".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("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.hyperliquid.xyz".to_string()));
m.insert("private".to_string(), Value::Str("https://api.hyperliquid.xyz".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("spotClearinghouseState".to_string(), Value::Int(2));
m.insert("candleSnapshot".to_string(), Value::Int(4));
m.insert("orderStatus".to_string(), Value::Int(2));
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("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("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("maker".to_string(), Value::Float(0.0002));
m.insert("taker".to_string(), Value::Float(0.0005));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultType".to_string(), Value::Str("prediction".to_string()));
m.insert("loadAllOutcomes".to_string(), Value::Bool(true));
m.insert("sandboxMode".to_string(), Value::Bool(false));
m.insert("outcomeQuoteCurrency".to_string(), Value::Str("USDH".to_string()));
m.insert("defaultSlippage".to_string(), Value::Float(0.05));
m.insert("zeroAddress".to_string(), Value::Str("0x0000000000000000000000000000000000000000".to_string()));
m.insert("builderFee".to_string(), Value::Bool(true));
m.insert("builder".to_string(), Value::Str("0x6530512A6c89C7cfCEbC3BA7fcD9aDa5f30827a6".to_string()));
m.insert("feeRate".to_string(), Value::Str("0%".to_string()));
m.insert("feeInt".to_string(), Value::Int(0));
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.insert("Order was never placed, already canceled, or filled.".to_string(), Value::Str("OrderNotFound".to_string()));
m.insert("Insufficient spot balance".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("Too many cumulative requests sent".to_string(), Value::Str("RateLimitExceeded".to_string()).clone());
m.insert("Order has zero size.".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("No liquidity available for market order.".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Insufficient".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m
}));
m
}));
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());
}
/*
* @ignore
* @method
* @name hyperliquid#outcomeEncoding
* @description computes the encoding for an outcome side: encoding = 10 * outcomeId + side (side 0 = YES, side 1 = NO)
* @param {int} outcomeId integer outcome id
* @param {int} side outcome side, 0 = YES, 1 = NO
* @returns {int} the outcome side encoding
*/
pub fn outcome_encoding(&self, mut outcomeId: Value, mut side: Value) -> Value {
return self.sum(&[multiply(&Value::Int(10), &outcomeId), side.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#outcomeAssetId
* @description returns the asset id used for orders: 100_000_000 + encoding, e.g. 100000010
* @param {int} encoding outcome side encoding
* @returns {int} the asset id
*/
pub fn outcome_asset_id(&self, mut encoding: Value) -> Value {
return self.sum(&[Value::Int(100000000), encoding.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#outcomeCoin
* @description returns the coin name used in API calls: #<encoding>, e.g. #10 for outcome 1 side 0
* @param {int} encoding outcome side encoding
* @returns {string} the coin name
*/
pub fn outcome_coin(&self, mut encoding: Value) -> Value {
return add(&Value::Str("#".to_string()), &to_string_val(&encoding));
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#outcomeToken
* @description returns the token name: +<encoding>, e.g. +10
* @param {int} encoding outcome side encoding
* @returns {string} the token name
*/
pub fn outcome_token(&self, mut encoding: Value) -> Value {
return add(&Value::Str("+".to_string()), &to_string_val(&encoding));
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#parseOutcomeDescription
* @description parses a description string of the form class:priceBinary|underlying:BTC|expiry:20260503-0600|targetPrice:78213|period:1d into a dict
* @param {string} description the raw outcome description string
* @returns {object} a dict of the parsed key/value pairs
*/
pub fn parse_outcome_description(&self, mut description: Value) -> Value {
if is_true(&(is_equal(&description, &Value::Null))) || is_true(&(is_equal(&description, &Value::Str("".to_string())))) {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
let mut parts: Value = split(&description, &Value::Str("|".to_string()));
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_1178: bool = true;
while { if !__for_first_1178 { i = add(&i, &Value::Int(1)); } __for_first_1178 = false; is_less_than(&i, &get_array_length(&parts)) } {
let mut part: Value = get_value(&parts, &i);
let mut part: Value = get_value(&parts, &i);
let mut colonIndex: Value = get_index_of(&part, &Value::Str(":".to_string()));
if is_greater_than(&colonIndex, &negate(&Value::Int(1))) {
let mut key: Value = slice(&part, &Value::Int(0), &colonIndex);
let mut value: Value = slice(&part, &add(&colonIndex, &Value::Int(1)), &Value::Null);
add_element_to_object(&mut result, &key, value.clone());
}
}
}
return result;
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#buildOutcomeSymbol
* @description builds a human-readable outcome from a parsed description and side, e.g. BTC_ABOVE_78213_20260503:YES for side 0 and BTC_ABOVE_78213_20260503:NO for side 1
* @param {object} desc parsed outcome description
* @param {int} side outcome side, 0 = YES, 1 = NO
* @param {int} outcomeId integer outcome id
* @returns {string} the outcome
*/
pub fn build_outcome_symbol(&self, mut desc: Value, mut side: Value, mut outcomeId: Value) -> Value {
let mut underlying: Value = self.safe_string_k(desc.clone(), "underlying", &[add(&Value::Str("OUTCOME".to_string()), &to_string_val(&outcomeId))]);
let mut targetPrice: Value = self.safe_string_k(desc.clone(), "targetPrice", &[]);
let mut expiry: Value = self.safe_string_k(desc.clone(), "expiry", &[Value::Str("".to_string())]);
// Parse expiry: "20260503-0600" → "20260503"
let mut expiryDate: Value = ternary(is_true(&(!is_equal(&expiry, &Value::Str("".to_string())))), get_value(&split(&expiry, &Value::Str("-".to_string())), &Value::Int(0)), Value::Str("".to_string()));
let mut label: Value = ternary(is_true(&(is_equal(&side, &Value::Int(0)))), Value::Str("YES".to_string()), Value::Str("NO".to_string()));
let mut base: Value = to_upper(&underlying);
if is_true(&(!is_equal(&targetPrice, &Value::Null))) && is_true(&(!is_equal(&targetPrice, &Value::Str("".to_string())))) {
base = add(&add(&base, &Value::Str("_ABOVE_".to_string())), &targetPrice);
}
if is_true(&(!is_equal(&expiryDate, &Value::Null))) && is_true(&(!is_equal(&expiryDate, &Value::Str("".to_string())))) {
base = add(&add(&base, &Value::Str("_".to_string())), &expiryDate);
}
return add(&add(&base, &Value::Str(":".to_string())), &label);
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#buildOutcomeParentSymbol
* @description builds a market id (parent outcome without YES/NO) from a parsed description, e.g. BTC_ABOVE_78213_20260503 for priceBinary outcomes or OUTCOME_9345 for non-priceBinary outcomes using the name field
* @param {object} desc parsed outcome description
* @param {int} outcomeId integer outcome id
* @param {string} [name] outcome name
* @param {object} [question] linked question object from outcomeMeta
* @returns {string} the parent market outcome
*/
pub fn build_outcome_parent_symbol(&self, mut desc: Value, mut outcomeId: Value, optional_args: &[Value]) -> Value {
let mut name = get_arg(optional_args, 0, Value::Str("".to_string()));
let mut question = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut underlying: Value = self.safe_string_k(desc.clone(), "underlying", &[]);
if is_true(&(!is_equal(&underlying, &Value::Null))) && is_true(&(!is_equal(&underlying, &Value::Str("".to_string())))) {
let mut targetPrice: Value = self.safe_string_k(desc.clone(), "targetPrice", &[]);
let mut expiry: Value = self.safe_string_k(desc.clone(), "expiry", &[Value::Str("".to_string())]);
let mut expiryDate: Value = ternary(is_true(&(!is_equal(&expiry, &Value::Str("".to_string())))), get_value(&split(&expiry, &Value::Str("-".to_string())), &Value::Int(0)), Value::Str("".to_string()));
let mut base: Value = to_upper(&underlying);
if is_true(&(!is_equal(&targetPrice, &Value::Null))) && is_true(&(!is_equal(&targetPrice, &Value::Str("".to_string())))) {
base = add(&add(&base, &Value::Str("_ABOVE_".to_string())), &targetPrice);
}
if is_true(&(!is_equal(&expiryDate, &Value::Null))) && is_true(&(!is_equal(&expiryDate, &Value::Str("".to_string())))) {
base = add(&add(&base, &Value::Str("_".to_string())), &expiryDate);
}
return base;
}
let mut questionDescription: Value = self.safe_string_k(question.clone(), "description", &[]);
if is_true(&(!is_equal(&questionDescription, &Value::Null))) && is_true(&(!is_equal(&questionDescription, &Value::Str("".to_string())))) {
let mut questionDesc: Value = self.parse_outcome_description(questionDescription.clone());
let mut questionClass: Value = self.safe_string_lower(questionDesc.clone(), Value::Str("class".to_string()), &[]);
if is_equal(&questionClass, &Value::Str("pricebucket".to_string())) {
let mut questionUnderlying: Value = self.safe_string_k(questionDesc.clone(), "underlying", &[]);
let mut questionExpiry: Value = self.safe_string_k(questionDesc.clone(), "expiry", &[Value::Str("".to_string())]);
let mut expiryDate: Value = ternary(is_true(&(!is_equal(&questionExpiry, &Value::Str("".to_string())))), get_value(&split(&questionExpiry, &Value::Str("-".to_string())), &Value::Int(0)), Value::Str("".to_string()));
let mut thresholdsRaw: Value = self.safe_string_k(questionDesc.clone(), "priceThresholds", &[Value::Str("".to_string())]);
let mut indexStr: Value = self.safe_string_k(desc.clone(), "index", &[]);
let mut rawDescription: Value = self.safe_string_lower(desc.clone(), Value::Str("description".to_string()), &[Value::Str("".to_string())]);
let mut nameLower: Value = to_lower(&name);
if is_true(&(!is_equal(&questionUnderlying, &Value::Null) && !is_equal(&questionUnderlying, &Value::Str("".to_string())))) && is_true(&(!is_equal(&thresholdsRaw, &Value::Str("".to_string())))) && !is_equal(&indexStr, &Value::Null) {
let mut thresholdParts: Value = split(&thresholdsRaw, &Value::Str(",".to_string()));
let mut thresholds: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1179: bool = true;
while { if !__for_first_1179 { i = add(&i, &Value::Int(1)); } __for_first_1179 = false; is_less_than(&i, &get_array_length(&thresholdParts)) } {
let mut trimmed: Value = trim(&get_value(&thresholdParts, &i));
if is_greater_than(&get_array_length(&trimmed), &Value::Int(0)) {
append_to_array(&mut thresholds, trimmed.clone());
}
}
}
let mut thresholdsLength: Value = get_array_length(&thresholds);
let mut index: Value = self.parse_to_int(indexStr.clone());
if is_greater_than(&thresholdsLength, &Value::Int(0)) && !is_equal(&index, &Value::Null) {
let mut bucketLabel: Value = Value::Null;
if is_less_than_or_equal(&index, &Value::Int(0)) {
bucketLabel = add(&Value::Str("BELOW_".to_string()), &get_value(&thresholds, &Value::Int(0)));
} else if is_greater_than_or_equal(&index, &thresholdsLength) {
let mut lastIdx: Value = subtract(&thresholdsLength, &Value::Int(1));
bucketLabel = add(&Value::Str("ABOVE_".to_string()), &get_value(&thresholds, &lastIdx));
} else {
bucketLabel = add(&add(&add(&Value::Str("BETWEEN_".to_string()), &get_value(&thresholds, &subtract(&index, &Value::Int(1)))), &Value::Str("_".to_string())), &get_value(&thresholds, &index));
}
let mut base: Value = add(&add(&to_upper(&questionUnderlying), &Value::Str("_".to_string())), &bucketLabel);
if is_true(&(!is_equal(&expiryDate, &Value::Null))) && is_true(&(!is_equal(&expiryDate, &Value::Str("".to_string())))) {
base = add(&add(&base, &Value::Str("_".to_string())), &expiryDate);
}
return base;
}
}
let mut isFallbackLike: bool = is_true(&(is_equal(&rawDescription, &Value::Str("other".to_string())))) || is_true(&(is_greater_than_or_equal(&get_index_of(&nameLower, &Value::Str("fallback".to_string())), &Value::Int(0)))) || is_true(&(is_greater_than_or_equal(&get_index_of(&nameLower, &Value::Str("other".to_string())), &Value::Int(0))));
if is_true(&(!is_equal(&questionUnderlying, &Value::Null) && !is_equal(&questionUnderlying, &Value::Str("".to_string())))) && is_true(&isFallbackLike) {
let mut base: Value = add(&to_upper(&questionUnderlying), &Value::Str("_OTHER".to_string()));
if is_true(&(!is_equal(&expiryDate, &Value::Null))) && is_true(&(!is_equal(&expiryDate, &Value::Str("".to_string())))) {
base = add(&add(&base, &Value::Str("_".to_string())), &expiryDate);
}
return base;
}
}
}
let mut questionName: Value = self.safe_string_k(question.clone(), "name", &[]);
if is_true(&(!is_equal(&questionName, &Value::Null))) && is_true(&(!is_equal(&questionName, &Value::Str("".to_string())))) {
let mut questionSlug: Value = self.shorten_slug(questionName.clone());
if is_true(&(!is_equal(&questionSlug, &Value::Null))) && is_true(&(!is_equal(&questionSlug, &Value::Str("".to_string())))) {
let mut outcomeSlug: Value = self.shorten_slug(name.clone());
let mut genericOutcomeNames: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("RECURRING".to_string(), Value::Bool(true));
m.insert("RECURRING_FALLBACK".to_string(), Value::Bool(true));
m.insert("RECURRING_NAMED_OUTCOME".to_string(), Value::Bool(true));
m
});
if is_true(&Value::Bool(in_op(&genericOutcomeNames, &outcomeSlug))) {
if is_greater_than_or_equal(&get_index_of(&outcomeSlug, &Value::Str("FALLBACK".to_string())), &Value::Int(0)) {
outcomeSlug = Value::Str("OTHER".to_string());
} else {
outcomeSlug = Value::Str("".to_string());
}
}
if is_true(&(!is_equal(&outcomeSlug, &Value::Null))) && is_true(&(!is_equal(&outcomeSlug, &Value::Str("".to_string())))) {
return add(&add(&add(&add(&questionSlug, &Value::Str("_".to_string())), &outcomeSlug), &Value::Str("_".to_string())), &to_string_val(&outcomeId));
}
return add(&add(&questionSlug, &Value::Str("_".to_string())), &to_string_val(&outcomeId));
}
}
// Fallback: use name slugified, or OUTCOME-<id>
if is_true(&(!is_equal(&name, &Value::Null))) && is_true(&(!is_equal(&name, &Value::Str("".to_string())))) {
return add(&add(&self.shorten_slug(name.clone()), &Value::Str("_".to_string())), &to_string_val(&outcomeId));
}
return add(&Value::Str("OUTCOME_".to_string()), &to_string_val(&outcomeId));
Value::Null
}
/*
* @method
* @name hyperliquid#fetchMarkets
* @description Retrieves all Hyperliquid outcome markets from outcomeMeta.
* Each binary outcome becomes one CCXT prediction market with two outcomes: YES and NO.
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/asset-ids#outcomes
* @param {object} [params] extra parameters
* @returns {Market[]} array of market structures
*/
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
}));
//
// outcomeMeta response:
//
// {
// "outcomes": [
// {
// "outcome": 9345,
// "name": "Recurring",
// "description": "class:priceBinary|underlying:BTC|expiry:20260513-0300|targetPrice:81023|period:1d",
// "sideSpecs": [
// { "name": "Yes" },
// { "name": "No" }
// ]
// },
// ...
// ],
// "questions": [
// {
// "question": 182,
// "name": "What will Hypurr eat the most of in May 2026?",
// "description": "...",
// "fallbackOutcome": 7002,
// "namedOutcomes": [7003, 7004, 7005],
// "settledNamedOutcomes": []
// },
// ...
// ]
// }
//
let __ws_arg_0 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("outcomeMeta".to_string()));
m
}), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_0]).await;
let mut outcomesList: Value = self.safe_list_k(response.clone(), "outcomes", &[Value::List(vec![])]);
let mut questionsList: Value = self.safe_list_k(response.clone(), "questions", &[Value::List(vec![])]);
let mut outcomesToQuestions: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut qi: Value = Value::Int(0);
let mut __for_first_1181: bool = true;
while { if !__for_first_1181 { qi = add(&qi, &Value::Int(1)); } __for_first_1181 = false; is_less_than(&qi, &get_array_length(&questionsList)) } {
let mut question: Value = self.safe_dict(questionsList.clone(), qi.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fallbackOutcome: Value = self.safe_integer_k(question.clone(), "fallbackOutcome", &[]);
if !is_equal(&fallbackOutcome, &Value::Null) {
let mut fallbackKey: Value = to_string_val(&fallbackOutcome);
add_element_to_object(&mut outcomesToQuestions, &fallbackKey, question.clone());
}
let mut namedOutcomes: Value = self.safe_list_k(question.clone(), "namedOutcomes", &[Value::List(vec![])]);
{
let mut ni: Value = Value::Int(0);
let mut __for_first_1180: bool = true;
while { if !__for_first_1180 { ni = add(&ni, &Value::Int(1)); } __for_first_1180 = false; is_less_than(&ni, &get_array_length(&namedOutcomes)) } {
let mut namedOutcomeId: Value = self.safe_integer(namedOutcomes.clone(), ni.clone(), &[]);
if !is_equal(&namedOutcomeId, &Value::Null) {
let mut namedKey: Value = to_string_val(&namedOutcomeId);
add_element_to_object(&mut outcomesToQuestions, &namedKey, question.clone());
}
}
}
}
}
let mut markets: Value = Value::List(vec![]);
if is_equal(&self.exchange.outcomes, &Value::Null) {
self.exchange.outcomes = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
if is_equal(&self.exchange.outcomes_by_id, &Value::Null) {
self.exchange.outcomes_by_id = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1183: bool = true;
while { if !__for_first_1183 { i = add(&i, &Value::Int(1)); } __for_first_1183 = false; is_less_than(&i, &get_array_length(&outcomesList)) } {
let mut outcomeInfo: Value = self.safe_dict(outcomesList.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut outcomeId: Value = self.safe_integer_k(outcomeInfo.clone(), "outcome", &[i.clone()]);
let mut linkedQuestion: Value = self.safe_dict(outcomesToQuestions.clone(), to_string_val(&outcomeId), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut market: Value = self.parse_outcome_market(outcomeInfo.clone(), outcomeId.clone(), &[linkedQuestion.clone()]);
append_to_array(&mut markets, market.clone());
// Build outcomes dictionary from market outcomes
let mut marketOutcomes: Value = self.safe_list_k(market.clone(), "outcomes", &[Value::List(vec![])]);
{
let mut oi: Value = Value::Int(0);
let mut __for_first_1182: bool = true;
while { if !__for_first_1182 { oi = add(&oi, &Value::Int(1)); } __for_first_1182 = false; is_less_than(&oi, &get_array_length(&marketOutcomes)) } {
let mut outcome: Value = self.safe_dict(marketOutcomes.clone(), oi.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut outcomeSymbol: Value = self.safe_string2(outcome.clone(), Value::Str("outcome".to_string()), Value::Str("symbol".to_string()), &[]);
let mut outcomeId_: Value = self.safe_string2(outcome.clone(), Value::Str("outcomeId".to_string()), Value::Str("id".to_string()), &[]);
if !is_equal(&outcomeSymbol, &Value::Null) {
add_element_to_object(&mut self.exchange.outcomes, &outcomeSymbol, outcome.clone());
}
if !is_equal(&outcomeId_, &Value::Null) {
add_element_to_object(&mut self.exchange.outcomes_by_id, &outcomeId_, outcome.clone());
}
}
}
}
}
return markets;
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#parseOutcomeMarket
* @description parses a single binary outcome market into a CCXT market structure with outcomes[]
* @param {object} outcomeInfo raw entry from outcomeMeta outcomes array
* @param {int} outcomeId integer outcome id
* @param {object} [question] linked question object from outcomeMeta questions array
* @returns {object} a [market structure](https://docs.ccxt.com/#/?id=market-structure)
*/
pub fn parse_outcome_market(&self, mut outcomeInfo: Value, mut outcomeId: Value, optional_args: &[Value]) -> Value {
let mut question = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut description: Value = self.safe_string_k(outcomeInfo.clone(), "description", &[Value::Str("".to_string())]);
let mut name: Value = self.safe_string_k(outcomeInfo.clone(), "name", &[Value::Str("".to_string())]);
let mut sideSpecs: Value = self.safe_list_k(outcomeInfo.clone(), "sideSpecs", &[Value::List(vec![])]);
let mut desc: Value = self.parse_outcome_description(description.clone());
let mut parentSymbol: Value = self.build_outcome_parent_symbol(desc.clone(), outcomeId.clone(), &[name.clone(), question.clone()]);
let mut yesEncoding: Value = self.outcome_encoding(outcomeId.clone(), Value::Int(0));
let mut noEncoding: Value = self.outcome_encoding(outcomeId.clone(), Value::Int(1));
let mut yesOutcomeSymbol: Value = add(&parentSymbol, &Value::Str(":YES".to_string()));
let mut noOutcomeSymbol: Value = add(&parentSymbol, &Value::Str(":NO".to_string()));
// Parse expiry from description
let mut expiry: Value = self.safe_string_k(desc.clone(), "expiry", &[]);
let mut expiryMs: Value = Value::Null;
let mut expiryDatetime: Value = Value::Null;
if is_true(&(!is_equal(&expiry, &Value::Null))) && is_true(&(!is_equal(&expiry, &Value::Str("".to_string())))) {
// e.g. "20260503-0600" → "2026-05-03T06:00:00Z"
let mut expParts: Value = split(&expiry, &Value::Str("-".to_string()));
let mut expPartsLength: Value = get_array_length(&expParts);
if is_greater_than_or_equal(&expPartsLength, &Value::Int(1)) && is_equal(&get_array_length(&get_value(&expParts, &Value::Int(0))), &Value::Int(8)) {
let mut ymd: Value = get_value(&expParts, &Value::Int(0));
let mut hm: Value = ternary(is_true(&(is_greater_than_or_equal(&expPartsLength, &Value::Int(2)))), get_value(&expParts, &Value::Int(1)), Value::Str("0000".to_string()));
let mut isoStr: Value = add(&add(&add(&add(&add(&add(&add(&add(&add(&slice(&ymd, &Value::Int(0), &Value::Int(4)), &Value::Str("-".to_string())), &slice(&ymd, &Value::Int(4), &Value::Int(6))), &Value::Str("-".to_string())), &slice(&ymd, &Value::Int(6), &Value::Int(8))), &Value::Str("T".to_string())), &slice(&hm, &Value::Int(0), &Value::Int(2))), &Value::Str(":".to_string())), &slice(&hm, &Value::Int(2), &Value::Int(4))), &Value::Str(":00Z".to_string()));
expiryMs = self.parse8601(isoStr.clone());
expiryDatetime = isoStr.clone();
}
}
// Side labels from sideSpecs (e.g. "Yes"/"No", but use YES/NO normalised)
let mut yesLabel: Value = self.safe_string_upper(self.safe_dict(sideSpecs.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("name".to_string()), &[Value::Str("YES".to_string())]);
let mut noLabel: Value = self.safe_string_upper(self.safe_dict(sideSpecs.clone(), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("name".to_string()), &[Value::Str("NO".to_string())]);
let mut quoteCurrency: Value = self.safe_string_k(self.options.clone(), "outcomeQuoteCurrency", &[Value::Str("USDH".to_string())]);
let mut szDecimals: Value = Value::Int(4); // outcomes use 4 decimal places
let mut active: Value = Value::Bool(true);
let mut outcomePrecision: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.parse_number(self.parse_precision(&[to_string_val(&szDecimals)]), &[]));
m.insert("price".to_string(), Value::Float(0.0001));
m
});
let mut outcomes: Value = Value::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.outcome_coin(yesEncoding.clone()));
m.insert("outcomeId".to_string(), self.outcome_coin(yesEncoding.clone()));
m.insert("outcome".to_string(), yesOutcomeSymbol.clone());
m.insert("market".to_string(), parentSymbol.clone());
m.insert("label".to_string(), yesLabel.clone());
m.insert("active".to_string(), active.clone());
m.insert("precision".to_string(), outcomePrecision.clone());
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("encoding".to_string(), yesEncoding.clone());
m.insert("assetId".to_string(), self.outcome_asset_id(yesEncoding.clone()));
m.insert("coinName".to_string(), self.outcome_coin(yesEncoding.clone()));
m.insert("tokenName".to_string(), self.outcome_token(yesEncoding.clone()));
m.insert("side".to_string(), Value::Int(0));
m.insert("outcomeId".to_string(), outcomeId.clone());
m.insert("name".to_string(), name.clone());
m.insert("description".to_string(), description.clone());
m.insert("parsedDescription".to_string(), desc.clone());
m
}));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.outcome_coin(noEncoding.clone()));
m.insert("outcomeId".to_string(), self.outcome_coin(noEncoding.clone()));
m.insert("outcome".to_string(), noOutcomeSymbol.clone());
m.insert("market".to_string(), parentSymbol.clone());
m.insert("label".to_string(), noLabel.clone());
m.insert("active".to_string(), active.clone());
m.insert("precision".to_string(), outcomePrecision.clone());
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("encoding".to_string(), noEncoding.clone());
m.insert("assetId".to_string(), self.outcome_asset_id(noEncoding.clone()));
m.insert("coinName".to_string(), self.outcome_coin(noEncoding.clone()));
m.insert("tokenName".to_string(), self.outcome_token(noEncoding.clone()));
m.insert("side".to_string(), Value::Int(1));
m.insert("outcomeId".to_string(), outcomeId.clone());
m.insert("name".to_string(), name.clone());
m.insert("description".to_string(), description.clone());
m.insert("parsedDescription".to_string(), desc.clone());
m
}));
m
})]);
let mut marketRow: Value = self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), to_string_val(&outcomeId));
m.insert("market".to_string(), parentSymbol.clone());
m.insert("base".to_string(), get_value(&split(&parentSymbol, &Value::Str("/".to_string())), &Value::Int(0)));
m.insert("quote".to_string(), quoteCurrency.clone());
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), to_string_val(&outcomeId));
m.insert("quoteId".to_string(), quoteCurrency.clone());
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("prediction".to_string()));
m.insert("marketType".to_string(), Value::Str("binary".to_string()));
m.insert("executionModel".to_string(), Value::Str("clob".to_string()));
m.insert("spot".to_string(), Value::Bool(false));
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("prediction".to_string(), Value::Bool(true));
m.insert("active".to_string(), active.clone());
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(), Value::Float(0.0005));
m.insert("maker".to_string(), Value::Float(0.0002));
m.insert("contractSize".to_string(), Value::Null);
m.insert("expiry".to_string(), expiryMs.clone());
m.insert("expiryDatetime".to_string(), expiryDatetime.clone());
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("feeSide".to_string(), Value::Str("get".to_string()));
m.insert("precision".to_string(), outcomePrecision.clone());
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::Float(0.0001));
m.insert("max".to_string(), Value::Float(0.9999));
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.parse_number(Value::Str("1".to_string()), &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("outcomes".to_string(), outcomes.clone());
m.insert("info".to_string(), self.extend(outcomeInfo.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcomeId".to_string(), outcomeId.clone());
m.insert("parentSymbol".to_string(), parentSymbol.clone());
m.insert("description".to_string(), description.clone());
m.insert("parsedDescription".to_string(), desc.clone());
m
})]));
m.insert("created".to_string(), Value::Null);
m
})]);
return self.omit(marketRow.clone(), Value::Str("symbol".to_string()), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#calculatePricePrecision
* @description calculates an appropriate price precision tick size given midPx and szDecimals
* @param {float} midPx the mid price
* @param {int} szDecimals the number of size decimals
* @returns {float} the price tick size
*/
pub fn calculate_price_precision(&self, mut midPx: Value, mut szDecimals: Value) -> Value {
if is_less_than_or_equal(&midPx, &Value::Int(0)) {
return Value::Float(0.0001);
}
let mut midStr: Value = self.number_to_string(midPx.clone());
let mut parts: Value = split(&midStr, &Value::Str(".".to_string()));
let mut intPart: Value = get_value(&parts, &Value::Int(0));
let mut significantDigits: Value = crate::runtime::Math::max(&Value::Int(5), &get_array_length(&intPart));
let mut maxDecimals: Value = subtract(&Value::Int(8), &szDecimals);
let mut pricePrecisionDecimals: Value = crate::runtime::Math::max(&Value::Int(1), &crate::runtime::Math::min(&maxDecimals, &subtract(&significantDigits, &get_array_length(&intPart))));
let mut zeros: Value = Value::Str("".to_string());
let mut zeroCount: Value = subtract(&pricePrecisionDecimals, &Value::Int(1));
{
let mut zi: Value = Value::Int(0);
let mut __for_first_1184: bool = true;
while { if !__for_first_1184 { zi = add(&zi, &Value::Int(1)); } __for_first_1184 = false; is_less_than(&zi, &zeroCount) } {
zeros = add(&zeros, &Value::Str("0".to_string()));
}
}
return self.parse_to_numeric(add(&add(&Value::Str("0.".to_string()), &zeros), &Value::Str("1".to_string())));
Value::Null
}
/*
* @method
* @name hyperliquid#fetchTicker
* @description fetches a ticker for a single outcome market using the L2 order book snapshot
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#l2-book-snapshot
* @param {string} outcome unified outcome (e.g. 'BTC_ABOVE_78213_20260503:YES')
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub async fn fetch_ticker(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut coin: Value = self.safe_string_k(info.clone(), "coinName", &[]);
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(), coin.clone());
m
});
let __ws_arg_1 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_1]).await;
//
// {
// "coin": "#10",
// "levels": [
// [ { "n": "2", "px": "0.44", "sz": "500" } ], // bids [0]
// [ { "n": "2", "px": "0.46", "sz": "400" } ] // asks [1]
// ],
// "time": 1704290104840
// }
//
// l2Book returns null for coins without an order book; coerce to an empty dict
let mut tickerData: Value = self.safe_dict(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("book".to_string(), response.clone());
m
}), Value::Str("book".to_string()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_prediction_ticker(tickerData.clone(), &[outcomeObj.clone()]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchTickers
* @description fetches all outcome market tickers using allMids then optionally enriches with l2Book
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-all-mids-for-all-actively-traded-coins
* @param {string[]} [outcomes] filter by outcome ids or outcomes
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [prediction ticker structures](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = 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 requestedOutcomeSymbols: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&outcomes, &Value::Null) {
// one warm-up for the whole list (a cold cache bulk-loads once via loadAllOutcomes),
// then identities resolve synchronously
self.load_outcomes(&[outcomes.clone()]).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_1185: bool = true;
while { if !__for_first_1185 { i = add(&i, &Value::Int(1)); } __for_first_1185 = false; is_less_than(&i, &get_array_length(&outcomes)) } {
let mut requested: Value = get_value(&outcomes, &i);
let mut requested: Value = get_value(&outcomes, &i);
let mut requestedOutcomeObj: Value = self.safe_outcome(requested.clone(), &[]);
let mut requestedOutcome: Value = self.safe_string_k(requestedOutcomeObj.clone(), "outcome", &[requested.clone()]);
add_element_to_object(&mut requestedOutcomeSymbols, &requestedOutcome, Value::Bool(true));
}
}
} else {
// no filter — warm the whole outcome set so identities resolve from the cache
self.load_outcomes(&[]).await;
}
let __ws_arg_2 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("allMids".to_string()));
m
}), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_2]).await;
//
// { "mids": { "#10": "0.45", "#11": "0.55", ... } }
//
let mut allMids: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_true(&(!is_string(&response))) && !is_true(&Value::Bool(is_array(&response))) {
allMids = response.clone();
}
let mut mids: Value = self.safe_dict_k(allMids.clone(), "mids", &[allMids.clone()]);
let mut tickers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut outcomesMap: Value = ternary(is_true(&(!is_equal(&self.exchange.outcomes, &Value::Null))), self.exchange.outcomes.clone(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeHandles: Value = object_keys(&outcomesMap);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1186: bool = true;
while { if !__for_first_1186 { i = add(&i, &Value::Int(1)); } __for_first_1186 = false; is_less_than(&i, &get_array_length(&outcomeHandles)) } {
let mut outcomeHandle: Value = get_value(&outcomeHandles, &i);
let mut outcomeHandle: Value = get_value(&outcomeHandles, &i);
if !is_equal(&outcomes, &Value::Null) && !is_true(&(Value::Bool(in_op(&requestedOutcomeSymbols, &outcomeHandle)))) {
continue;
}
let mut outcomeObj: Value = self.safe_dict(outcomesMap.clone(), outcomeHandle.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut coin: Value = self.safe_string_k(info.clone(), "coinName", &[]);
let mut mid: Value = self.safe_number(mids.clone(), coin.clone(), &[]);
if is_equal(&mid, &Value::Null) {
continue;
}
// Build minimal ticker from mid price
let mut ticker: Value = self.parse_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("levels".to_string(), Value::List(vec![Value::List(vec![]), Value::List(vec![])]));
m.insert("mid".to_string(), mid.clone());
m.insert("time".to_string(), self.milliseconds());
m
}), &[outcomeObj.clone()]);
add_element_to_object(&mut tickers, &outcomeHandle, ticker.clone());
}
}
return tickers;
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#parsePredictionTicker
* @description parses a raw l2Book response (or a synthetic mid dict) into a unified ticker object
* @param {object} raw l2Book response or { mid, time } object
* @param {object} [market] the market the ticker belongs to
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub fn parse_prediction_ticker(&self, mut raw: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "coin": "#10",
// "levels": [
// [ { "n": "2", "px": "0.44", "sz": "500" } ], // bids [0]
// [ { "n": "2", "px": "0.46", "sz": "400" } ] // asks [1]
// ],
// "time": 1704290104840
// }
//
let mut now: Value = self.milliseconds();
let mut timestamp: Value = self.safe_integer_k(raw.clone(), "time", &[now.clone()]);
// the 2nd arg carries the outcome object (callers pass the resolved outcome)
let mut mkt: Value = self.safe_outcome(Value::Null, &[market.clone()]);
let mut outcome: Value = self.safe_string_k(mkt.clone(), "outcome", &[]);
let mut levels: Value = self.safe_list_k(raw.clone(), "levels", &[Value::List(vec![])]);
let mut rawBids: Value = self.safe_list(levels.clone(), Value::Int(0), &[Value::List(vec![])]);
let mut rawAsks: Value = self.safe_list(levels.clone(), Value::Int(1), &[Value::List(vec![])]);
let mut topBid: Value = self.safe_dict(rawBids.clone(), Value::Int(0), &[]);
let mut topAsk: Value = self.safe_dict(rawAsks.clone(), Value::Int(0), &[]);
let mut bid: Value = ternary(is_true(&(!is_equal(&topBid, &Value::Null))), self.safe_number_k(topBid.clone(), "px", &[]), Value::Null);
let mut ask: Value = ternary(is_true(&(!is_equal(&topAsk, &Value::Null))), self.safe_number_k(topAsk.clone(), "px", &[]), Value::Null);
let mut bidVolume: Value = ternary(is_true(&(!is_equal(&topBid, &Value::Null))), self.safe_number_k(topBid.clone(), "sz", &[]), Value::Null);
let mut askVolume: Value = ternary(is_true(&(!is_equal(&topAsk, &Value::Null))), self.safe_number_k(topAsk.clone(), "sz", &[]), Value::Null);
// Use synthetic mid if no l2Book
let mut mid: Value = self.safe_number_k(raw.clone(), "mid", &[]);
if is_equal(&mid, &Value::Null) && !is_equal(&bid, &Value::Null) && !is_equal(&ask, &Value::Null) {
mid = divide(&self.sum(&[bid.clone(), ask.clone()]), &Value::Int(2));
}
// day volume lives on the parent market's ctx; resolve it from the outcome's parent market
let mut parentSymbol: Value = self.safe_string_k(mkt.clone(), "market", &[]);
let mut parentMarket: Value = ternary(is_true(&(!is_equal(&parentSymbol, &Value::Null))), self.safe_market(&[parentSymbol.clone()]), Value::Null);
let mut ctx: Value = ternary(is_true(&(!is_equal(&parentMarket, &Value::Null))), self.safe_dict(self.safe_dict_k(parentMarket.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("ctx".to_string()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut dayVolume: Value = self.safe_number_k(ctx.clone(), "dayNtlVlm", &[]);
return self.safe_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), outcome.clone());
m.insert("outcomeId".to_string(), self.safe_string2(mkt.clone(), Value::Str("outcomeId".to_string()), Value::Str("id".to_string()), &[]));
m.insert("label".to_string(), self.safe_string_k(mkt.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(mkt.clone(), "market", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), bid.clone());
m.insert("bidVolume".to_string(), bidVolume.clone());
m.insert("ask".to_string(), ask.clone());
m.insert("askVolume".to_string(), askVolume.clone());
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), mid.clone());
m.insert("last".to_string(), mid.clone());
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), mid.clone());
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), dayVolume.clone());
m.insert("info".to_string(), raw.clone());
m
}), &[market.clone()]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchOrderBook
* @description fetches the L2 order book for an outcome market
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#l2-book-snapshot
* @param {string} outcome unified outcome
* @param {int} [limit] max depth levels (not used by hyperliquid but accepted)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order book structure](https://docs.ccxt.com/#/?id=prediction-order-book-structure)
*/
pub async fn fetch_order_book(&mut self, mut outcome: 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
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[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("l2Book".to_string()));
m.insert("coin".to_string(), self.safe_string_k(info.clone(), "coinName", &[]));
m
});
let __ws_arg_3 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_3]).await;
//
// {
// "coin": "#10",
// "levels": [
// [ { "n": "5", "px": "0.44", "sz": "500" }, ... ], // bids [0]
// [ { "n": "5", "px": "0.46", "sz": "400" }, ... ] // asks [1]
// ],
// "time": 1704290104840
// }
//
let mut timestamp: Value = self.safe_integer_k(response.clone(), "time", &[]);
let mut levels: Value = self.safe_list_k(response.clone(), "levels", &[Value::List(vec![])]);
let mut rawBids: Value = self.safe_list(levels.clone(), Value::Int(0), &[Value::List(vec![])]);
let mut rawAsks: Value = self.safe_list(levels.clone(), Value::Int(1), &[Value::List(vec![])]);
let mut bids: Value = Value::List(vec![]);
let mut asks: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1187: bool = true;
while { if !__for_first_1187 { i = add(&i, &Value::Int(1)); } __for_first_1187 = false; is_less_than(&i, &get_array_length(&rawBids)) } {
let mut entry: Value = get_value(&rawBids, &i);
let mut entry: Value = get_value(&rawBids, &i);
append_to_array(&mut bids, Value::List(vec![self.safe_number_k(entry.clone(), "px", &[]), self.safe_number_k(entry.clone(), "sz", &[])]));
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1188: bool = true;
while { if !__for_first_1188 { i = add(&i, &Value::Int(1)); } __for_first_1188 = false; is_less_than(&i, &get_array_length(&rawAsks)) } {
let mut entry: Value = get_value(&rawAsks, &i);
let mut entry: Value = get_value(&rawAsks, &i);
append_to_array(&mut asks, Value::List(vec![self.safe_number_k(entry.clone(), "px", &[]), self.safe_number_k(entry.clone(), "sz", &[])]));
}
}
let mut orderbook: Value = self.parse_order_book(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("bids".to_string(), bids.clone());
m.insert("asks".to_string(), asks.clone());
m
}), self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome.clone()]), &[timestamp.clone()]);
return self.safe_prediction_order_book(orderbook.clone(), &[outcomeObj.clone()]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchOHLCV
* @description fetches candlestick OHLCV data for an outcome market
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#candle-snapshot
* @param {string} outcome unified outcome
* @param {string} timeframe '1m', '5m', '15m', '1h', '4h', '1d', etc.
* @param {int} [since] timestamp in ms of earliest candle
* @param {int} [limit] max number of candles
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] end timestamp in ms
* @returns {int[][]} a list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut outcome: 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
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
// markets are keyed by the parent market outcome, not the outcome handle ("MARKET:LABEL")
let mut market: Value = self.market(self.safe_string_k(outcomeObj.clone(), "market", &[]));
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[self.milliseconds()]);
let mut startTime: Value = since.clone();
if is_equal(&since, &Value::Null) {
let mut tf: Value = self.parse_timeframe(timeframe.clone());
let mut candleCount: Value = ternary(is_true(&(!is_equal(&limit, &Value::Null))), limit.clone(), Value::Int(100));
let mut startOffset: Value = multiply(&multiply(&tf, &candleCount), &negate(&Value::Int(1000)));
startTime = self.sum(&[until.clone(), startOffset.clone()]);
if is_equal(&startTime, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchOHLCV() missing startTime".to_string()))));
}
if is_less_than(&startTime, &Value::Int(0)) {
startTime = Value::Int(0);
}
}
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(), self.safe_string_k(info.clone(), "coinName", &[]));
m.insert("interval".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m.insert("startTime".to_string(), startTime.clone());
m.insert("endTime".to_string(), until.clone());
m
}));
m
});
params = self.omit(params.clone(), Value::Str("until".to_string()), &[]);
let __ws_arg_4 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_4]).await;
//
// [
// {
// "T": 1704287699999, // close time
// "c": "0.45",
// "h": "0.47",
// "i": "1m",
// "l": "0.43",
// "n": 46, // number of trades
// "o": "0.44",
// "s": "#10",
// "t": 1704286800000, // open time
// "v": "1234.5"
// }
// ]
//
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(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#parseOHLCV
* @description parses a single hyperliquid candle object into a CCXT OHLCV tuple
* @param {object} ohlcv the raw candle object
* @param {object} [market] the market the candle belongs to
* @returns {int[]} a candle ordered as timestamp, open, high, low, close, volume
*/
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#fetchBalance
* @description Fetches spot balance (outcomes use spot-like balance).
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-a-users-token-balances
* @param {object} [params] extra parameters
* @param {string} [params.user] wallet address (defaults to this.walletAddress)
* @returns {Balances} 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
}));
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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("spotClearinghouseState".to_string()));
m.insert("user".to_string(), userAddress.clone());
m
});
let __ws_arg_5 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_5]).await;
//
// {
// "balances": [
// { "coin": "USDC", "hold": "0.0", "total": "100.0" },
// { "coin": "+10", "hold": "0.0", "total": "50.0" }, // outcome token
// { "coin": "+11", "hold": "0.0", "total": "25.0" }
// ]
// }
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut balances: Value = self.safe_list_k(response.clone(), "balances", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1189: bool = true;
while { if !__for_first_1189 { i = add(&i, &Value::Int(1)); } __for_first_1189 = 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 coin: Value = self.safe_string_k(balance.clone(), "coin", &[]);
let mut total: Value = self.safe_string_k(balance.clone(), "total", &[]);
let mut used: Value = self.safe_string_k(balance.clone(), "hold", &[]);
let mut account: Value = self.account();
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(&coin, &Value::Null) {
add_element_to_object(&mut result, &coin, account.clone());
}
}
}
return self.safe_balance(result.clone());
Value::Null
}
/*
* @method
* @name hyperliquid#fetchPositions
* @description fetches the user's outcome positions; outcome positions are spot token balances under the "+<encoding>" coin form (size and entry notional), the value/entry/mark price/pnl are computed from the current mid prices
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-a-users-token-balances
* @param {string[]} [outcomes] filter by outcome ids or outcomes
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] wallet address
* @returns {object[]} a list of [prediction position structures](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = 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 requestedOutcomeSymbols: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&outcomes, &Value::Null) {
// one warm-up for the whole list (a cold cache bulk-loads once via loadAllOutcomes),
// then identities resolve synchronously
self.load_outcomes(&[outcomes.clone()]).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_1190: bool = true;
while { if !__for_first_1190 { i = add(&i, &Value::Int(1)); } __for_first_1190 = false; is_less_than(&i, &get_array_length(&outcomes)) } {
let mut requested: Value = get_value(&outcomes, &i);
let mut requested: Value = get_value(&outcomes, &i);
let mut requestedOutcomeObj: Value = self.safe_outcome(requested.clone(), &[]);
let mut requestedOutcome: Value = self.safe_string_k(requestedOutcomeObj.clone(), "outcome", &[requested.clone()]);
add_element_to_object(&mut requestedOutcomeSymbols, &requestedOutcome, Value::Bool(true));
}
}
} else {
// no filter — warm the whole outcome set so identities resolve from the cache
self.load_outcomes(&[]).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)); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("spotClearinghouseState".to_string()));
m.insert("user".to_string(), userAddress.clone());
m
});
// outcome positions are spot token balances under the "+<encoding>" coin form; they carry
// the size (total) and entry notional (entryNtl). hyperliquid does not return the position
// value / entry price / pnl, so they are computed from the current mid prices
let __ws_arg_6 = self.extend(request.clone(), &[params.clone()]);
let mut promises: Value = Value::List(vec![self.public_post_info(&[__ws_arg_6]).await, self.public_post_info(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("allMids".to_string()));
m
})]).await]);
let mut results: Value = promise_all(&promises).await;
let mut response: Value = get_value(&results, &Value::Int(0));
let mut midsResponse: Value = get_value(&results, &Value::Int(1));
let mut balances: Value = self.safe_list_k(response.clone(), "balances", &[Value::List(vec![])]);
let mut allMids: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_true(&(!is_string(&midsResponse))) && !is_true(&Value::Bool(is_array(&midsResponse))) {
allMids = midsResponse.clone();
}
let mut mids: Value = self.safe_dict_k(allMids.clone(), "mids", &[allMids.clone()]);
let mut positions: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1191: bool = true;
while { if !__for_first_1191 { i = add(&i, &Value::Int(1)); } __for_first_1191 = false; is_less_than(&i, &get_array_length(&balances)) } {
let mut balance: Value = self.safe_dict(balances.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut coin: Value = self.safe_string_k(balance.clone(), "coin", &[Value::Str("".to_string())]);
// outcome tokens use the "+<encoding>" balance form; skip regular spot tokens (USDC, ...)
if !is_equal(&get_index_of(&coin, &Value::Str("+".to_string())), &Value::Int(0)) {
continue;
}
let mut totalStr: Value = self.safe_string_k(balance.clone(), "total", &[]);
if is_true(&(is_equal(&totalStr, &Value::Null))) || is_true(&crate::precise::Precise::stringEq(&totalStr, &Value::Str("0".to_string()))) {
continue;
}
// the trade/orderbook form ("#<encoding>") resolves the outcome and the mid price
let mut tradeCoin: Value = add(&Value::Str("#".to_string()), &slice(&coin, &Value::Int(1), &Value::Null));
let mut outcomeObj: Value = self.safe_outcome(tradeCoin.clone(), &[]);
if !is_equal(&outcomes, &Value::Null) {
let mut outcomeHandle: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
if is_equal(&outcomeHandle, &Value::Null) || !is_true(&(Value::Bool(in_op(&requestedOutcomeSymbols, &outcomeHandle)))) {
continue;
}
}
let __ws_arg_7 = self.safe_string(mids.clone(), tradeCoin.clone(), &[]);
let mut enriched: Value = self.extend(balance.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("markPx".to_string(), __ws_arg_7);
m
})]);
append_to_array(&mut positions, self.parse_prediction_position(enriched.clone(), &[outcomeObj.clone()]));
}
}
return positions;
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#parsePredictionPosition
* @description parses a spot balance entry for an outcome token into a unified position object
* @param {object} position the raw balance entry
* @param {object} [market] the outcome object the position belongs to
* @returns {object} a [prediction position structure](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub fn parse_prediction_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
// `position` is a spotClearinghouseState balance entry ({ coin, total, hold, entryNtl })
// enriched with the current mid price (markPx); hyperliquid does not return the position
// value / entry price / pnl for outcome tokens, so they are computed here
let mut outcomeObj: Value = self.safe_outcome(Value::Null, &[market.clone()]);
let mut totalStr: Value = self.safe_string_k(position.clone(), "total", &[]);
let mut total: Value = self.parse_number(totalStr.clone(), &[]);
let mut entryNtlStr: Value = self.safe_string_k(position.clone(), "entryNtl", &[]);
let mut entryPrice: Value = Value::Null;
if is_true(&(!is_equal(&entryNtlStr, &Value::Null))) && is_true(&(!is_equal(&totalStr, &Value::Null))) && !is_true(&crate::precise::Precise::stringEq(&totalStr, &Value::Str("0".to_string()))) {
entryPrice = self.parse_number(crate::precise::Precise::stringDiv(&entryNtlStr, &totalStr), &[]);
}
let mut markPxStr: Value = self.safe_string_k(position.clone(), "markPx", &[]);
let mut notional: Value = Value::Null; // current position value = size * mark price
let mut unrealizedPnl: Value = Value::Null; // value - entry notional
if is_true(&(!is_equal(&markPxStr, &Value::Null))) && is_true(&(!is_equal(&totalStr, &Value::Null))) {
let mut notionalStr: Value = crate::precise::Precise::stringMul(&totalStr, &markPxStr);
notional = self.parse_number(notionalStr.clone(), &[]);
if !is_equal(&entryNtlStr, &Value::Null) {
unrealizedPnl = self.parse_number(crate::precise::Precise::stringSub(¬ionalStr, &entryNtlStr), &[]);
}
}
return self.safe_prediction_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Null);
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".to_string()), Value::Str("id".to_string()), &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("isolated".to_string(), Value::Bool(false));
m.insert("hedged".to_string(), Value::Null);
m.insert("side".to_string(), Value::Str("long".to_string()));
m.insert("contracts".to_string(), total.clone());
m.insert("contractSize".to_string(), Value::Int(1));
m.insert("entryPrice".to_string(), entryPrice.clone());
m.insert("markPrice".to_string(), self.parse_number(markPxStr.clone(), &[]));
m.insert("notional".to_string(), notional.clone());
m.insert("leverage".to_string(), Value::Null);
m.insert("collateral".to_string(), self.safe_number_k(position.clone(), "hold", &[]));
m.insert("initialMargin".to_string(), Value::Null);
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(), unrealizedPnl.clone());
m.insert("realizedPnl".to_string(), Value::Null);
m.insert("liquidationPrice".to_string(), Value::Null);
m.insert("marginRatio".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Str("cross".to_string()));
m.insert("percentage".to_string(), Value::Null);
m.insert("info".to_string(), position.clone());
m
}));
Value::Null
}
pub fn find_outcome_in_market(&self, mut market: Value, optional_args: &[Value]) -> Value {
let mut sideHint = get_arg(optional_args, 0, Value::Null);
let mut outcomesList: Value = self.safe_list_k(market.clone(), "outcomes", &[Value::List(vec![])]);
let mut normalizedHint: Value = ternary(is_true(&(!is_equal(&sideHint, &Value::Null) && !is_equal(&sideHint, &Value::Str("".to_string())))), to_upper(&sideHint), Value::Null);
if !is_equal(&normalizedHint, &Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_1192: bool = true;
while { if !__for_first_1192 { i = add(&i, &Value::Int(1)); } __for_first_1192 = false; is_less_than(&i, &get_array_length(&outcomesList)) } {
let mut oc: Value = self.safe_dict(outcomesList.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ocSymbol: Value = self.safe_string2(oc.clone(), Value::Str("outcome".to_string()), Value::Str("symbol".to_string()), &[Value::Str("".to_string())]);
let mut ocLabel: Value = self.safe_string_upper(oc.clone(), Value::Str("label".to_string()), &[]);
if is_equal(&ocLabel, &normalizedHint) || is_true(&Value::Bool(ends_with(&ocSymbol, &add(&Value::Str(":".to_string()), &normalizedHint)))) {
return oc;
}
}
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1193: bool = true;
while { if !__for_first_1193 { i = add(&i, &Value::Int(1)); } __for_first_1193 = false; is_less_than(&i, &get_array_length(&outcomesList)) } {
let mut oc: Value = self.safe_dict(outcomesList.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut info: Value = self.safe_dict_k(oc.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if is_equal(&self.safe_integer_k(info.clone(), "side", &[]), &Value::Int(0)) {
return oc;
}
}
}
return self.safe_dict(outcomesList.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
Value::Null
}
pub fn parse_outcome_input_side_hint(&self, mut outcomeInput: Value) -> Value {
if is_true(&(is_equal(&outcomeInput, &Value::Null))) || is_true(&(is_equal(&outcomeInput, &Value::Str("".to_string())))) {
return Value::Null;
}
let mut colonIndex: Value = get_index_of(&outcomeInput, &Value::Str(":".to_string()));
if is_greater_than(&colonIndex, &negate(&Value::Int(1))) && is_less_than(&colonIndex, &subtract(&get_array_length(&outcomeInput), &Value::Int(1))) {
let mut side: Value = to_upper(&slice(&outcomeInput, &add(&colonIndex, &Value::Int(1)), &Value::Null));
if is_equal(&side, &Value::Str("YES".to_string())) || is_equal(&side, &Value::Str("NO".to_string())) {
return side;
}
}
let mut lower: Value = to_lower(&outcomeInput);
if is_true(&Value::Bool(ends_with(&lower, &Value::Str("-yes".to_string())))) {
return Value::Str("YES".to_string());
}
if is_true(&Value::Bool(ends_with(&lower, &Value::Str("-no".to_string())))) {
return Value::Str("NO".to_string());
}
return Value::Null;
Value::Null
}
pub fn resolve_outcome_input(&self, mut outcomeInput: Value) -> Value {
if is_equal(&outcomeInput, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" resolveOutcomeInput() requires an outcome symbol or id".to_string()))));
}
if is_equal(&self.exchange.outcomes, &Value::Null) || is_equal(&self.exchange.outcomes_by_id, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" outcomes not loaded".to_string()))));
}
let mut sideHint: Value = self.parse_outcome_input_side_hint(outcomeInput.clone());
let mut candidates: Value = Value::List(vec![outcomeInput.clone()]);
if is_true(&Value::Bool(starts_with(&outcomeInput, &Value::Str("+".to_string())))) {
append_to_array(&mut candidates, add(&Value::Str("#".to_string()), &slice(&outcomeInput, &Value::Int(1), &Value::Null)));
}
let mut digitChars: Value = Value::Str("0123456789".to_string());
let mut inputChars: Value = self.string_to_chars_array(outcomeInput.clone());
let mut inputCharsLength: Value = get_array_length(&inputChars);
let mut isNumericInput: bool = is_greater_than(&inputCharsLength, &Value::Int(0));
{
let mut di: Value = Value::Int(0);
let mut __for_first_1194: bool = true;
while { if !__for_first_1194 { di = add(&di, &Value::Int(1)); } __for_first_1194 = false; is_less_than(&di, &get_array_length(&inputChars)) } {
if is_less_than(&get_index_of(&digitChars, &get_value(&inputChars, &di)), &Value::Int(0)) {
isNumericInput = false;
break;
}
}
}
if is_true(&isNumericInput) {
append_to_array(&mut candidates, add(&Value::Str("#".to_string()), &outcomeInput)); // encoding id without #
let mut numeric: Value = self.parse_to_int(outcomeInput.clone());
if !is_equal(&numeric, &Value::Null) {
append_to_array(&mut candidates, self.outcome_coin(self.outcome_encoding(numeric.clone(), Value::Int(0)))); // raw outcome id -> YES encoding
append_to_array(&mut candidates, self.outcome_coin(self.outcome_encoding(numeric.clone(), Value::Int(1)))); // raw outcome id -> NO encoding
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1195: bool = true;
while { if !__for_first_1195 { i = add(&i, &Value::Int(1)); } __for_first_1195 = false; is_less_than(&i, &get_array_length(&candidates)) } {
let mut key: Value = get_value(&candidates, &i);
let mut key: Value = get_value(&candidates, &i);
if is_true(&Value::Bool(in_op(&self.exchange.outcomes, &key))) {
return self.safe_dict(self.exchange.outcomes.clone(), key.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
if is_true(&Value::Bool(in_op(&self.exchange.outcomes_by_id, &key))) {
return self.safe_dict(self.exchange.outcomes_by_id.clone(), key.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
}
}
if is_true(&(is_true(&(!is_equal(&self.markets, &Value::Null))) && is_true(&(Value::Bool(in_op(&self.markets, &outcomeInput)))))) || is_true(&(is_true(&(!is_equal(&self.markets_by_id, &Value::Null))) && is_true(&(Value::Bool(in_op(&self.markets_by_id, &outcomeInput)))))) {
let mut market: Value = self.safe_market(&[outcomeInput.clone()]);
let mut sideHintOrDefault: Value = ternary(is_true(&(!is_equal(&sideHint, &Value::Null))), sideHint.clone(), Value::Str("YES".to_string()));
let mut found: Value = self.find_outcome_in_market(market.clone(), &[sideHintOrDefault.clone()]);
if is_greater_than(&get_array_length(&object_keys(&found)), &Value::Int(0)) {
return found;
}
}
panic!("{}", crate::exchange_errors::arguments_required(add(&add(&add(&self.id, &Value::Str(" cannot resolve outcome from input: ".to_string())), &outcomeInput), &Value::Str(". Provide an outcome symbol (e.g. MARKET:YES), outcome id (#<encoding>), or market id with side.".to_string()))));
Value::Null
}
/*
* @method
* @name hyperliquid#createOrder
* @description creates a limit or market order for an outcome market
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
* @param {string} outcome unified outcome
* @param {string} type 'limit' or 'market'
* @param {string} side 'buy' or 'sell'
* @param {float} amount quantity of outcome tokens
* @param {float} [price] limit price (0–1 range for prediction markets)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.timeInForce] 'Gtc' | 'Ioc' | 'Alo' (default 'Gtc')
* @param {boolean} [params.postOnly] if true sets timeInForce to 'Alo'
* @param {boolean} [params.reduceOnly] if true, marks the order as reduce only so it can only decrease an existing position
* @param {string} [params.slippage] slippage for market orders (default 5%)
* @param {string} [params.clientOrderId] hex cloid
* @param {string} [params.vaultAddress] optional subaccount/vault address to trade on behalf of (master signer must be authorized)
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn create_order(&mut self, mut outcome: 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
}));
self.initialize_client().await;
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
// markets are keyed by the parent market outcome; the outcome handle ("MARKET:LABEL")
// is not a market id, so resolve the market and price/amount precision via outcomeObj['market']
let mut marketSymbol: Value = self.safe_string_k(outcomeObj.clone(), "market", &[]);
let mut market: Value = self.market(marketSymbol.clone());
let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut nonce: Value = self.milliseconds();
let mut isBuy: Value = Value::Bool(is_equal(&to_upper(&side), &Value::Str("BUY".to_string())));
let mut isMarket: bool = is_equal(&to_upper(&type_var), &Value::Str("MARKET".to_string()));
let mut assetId: Value = self.safe_integer_k(outcomeInfo.clone(), "assetId", &[]);
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clientOrderId".to_string()), Value::Str("client_id".to_string()), &[]);
let mut reduceOnly: Value = self.safe_bool_k(params.clone(), "reduceOnly", &[Value::Bool(false)]);
let mut postOnly: Value = self.safe_bool_k(params.clone(), "postOnly", &[Value::Bool(false)]);
let mut defaultSlippage: Value = self.safe_string_k(self.options.clone(), "defaultSlippage", &[Value::Str("0.05".to_string())]);
let mut slippage: Value = self.safe_string_k(params.clone(), "slippage", &[defaultSlippage.clone()]);
let mut defaultTif: Value = ternary(is_true(&isMarket), Value::Str("Ioc".to_string()), Value::Str("Gtc".to_string()));
if is_equal(&postOnly, &Value::Bool(true)) {
defaultTif = Value::Str("Alo".to_string());
}
let mut tif: Value = self.capitalize(self.safe_string_lower(params.clone(), Value::Str("timeInForce".to_string()), &[defaultTif.clone()])); // eslint-disable-line
if is_equal(&price, &Value::Null) {
if is_true(&isMarket) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" createOrder() requires a reference price for market orders on outcome markets in between 0 and 1. The exchange uses this reference price together with the configured slippage to derive the execution price.".to_string()))));
}
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" createOrder() requires a limit price for outcome markets in between 0 and 1.".to_string()))));
}
let mut px: Value = Value::Null;
if is_true(&isMarket) {
let mut priceStr: Value = self.number_to_string(price.clone());
px = ternary(is_true(&isBuy), crate::precise::Precise::stringMul(&priceStr, &crate::precise::Precise::stringAdd(&Value::Str("1".to_string()), &slippage)), crate::precise::Precise::stringMul(&priceStr, &crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &slippage)));
px = self.price_to_precision(marketSymbol.clone(), px.clone());
} else {
px = self.price_to_precision(marketSymbol.clone(), price.clone());
}
if is_equal(&px, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" createOrder() could not determine price".to_string()))));
}
let mut sz: Value = self.amount_to_precision(marketSymbol.clone(), amount.clone());
let mut orderType: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tif".to_string(), tif.clone());
m
}));
m
});
let mut orderObj: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("a".to_string(), assetId.clone());
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());
}
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(), Value::List(vec![orderObj.clone()]));
m.insert("grouping".to_string(), Value::Str("na".to_string()));
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())]);
// feeInt defaults to 0: the builder is attached for statistics purposes only and the
// user is not charged; set options.feeInt (tenths of a bp) together with feeRate to charge
let mut feeInt: Value = self.safe_integer_k(self.options.clone(), "feeInt", &[Value::Int(0)]);
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) {
add_element_to_object(&mut request, &Value::Str("vaultAddress".to_string()), vaultAddress.clone());
}
let mut response: Value = self.private_post_exchange(&[request.clone()]).await;
//
// {
// "status": "ok",
// "response": {
// "type": "order",
// "data": { "statuses": [ { "resting": { "oid": 12345 } } ] }
// }
// }
//
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 firstStatus: Value = self.safe_dict(statuses.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut resting: Value = self.safe_dict_k(firstStatus.clone(), "resting", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut filled: Value = self.safe_dict_k(firstStatus.clone(), "filled", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut oid: Value = self.safe_string_k(resting.clone(), "oid", &[self.safe_string(filled.clone(), Value::Str("oid".to_string()), &[])]);
let mut restingOid: Value = self.safe_string_k(resting.clone(), "oid", &[]);
let mut orderStatus: Value = Value::Str("closed".to_string());
if !is_equal(&restingOid, &Value::Null) {
orderStatus = Value::Str("open".to_string());
}
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), oid.clone());
m.insert("clientOrderId".to_string(), clientOrderId.clone());
m.insert("info".to_string(), response.clone());
m.insert("timestamp".to_string(), nonce.clone());
m.insert("datetime".to_string(), self.iso8601(nonce.clone()));
m.insert("status".to_string(), orderStatus.clone());
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome.clone()]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "id", &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("type".to_string(), type_var.clone());
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), price.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("filled".to_string(), self.safe_number_k(filled.clone(), "totalSz", &[]));
m.insert("remaining".to_string(), Value::Null);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::List(vec![]));
m
}), &[market.clone()]);
Value::Null
}
/*
* @method
* @name hyperliquid#cancelOrder
* @description cancels a single open order
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
* @param {string} id order id
* @param {string} [outcome] unified outcome
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] cancel by client order id
* @param {string} [params.vaultAddress] optional subaccount/vault address to cancel on behalf of
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = 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 orders: Value = self.cancel_orders(Value::List(vec![id.clone()]), &[outcome.clone(), params.clone()]).await;
return self.safe_dict(orders.clone(), Value::Int(0), &[]);
Value::Null
}
/*
* @method
* @name hyperliquid#cancelOrders
* @description cancels multiple open orders
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
* @param {string[]} ids order ids
* @param {string} [outcome] unified outcome (required)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut outcome = 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(&outcome, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelOrders() requires an outcome argument".to_string()))));
}
self.initialize_client().await;
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut assetId: Value = self.safe_integer_k(outcomeInfo.clone(), "assetId", &[]);
let mut nonce: Value = self.milliseconds();
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 cancelReq: Value = Value::List(vec![]);
let mut cancelAction: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("cancel".to_string()));
m.insert("cancels".to_string(), Value::List(vec![]));
m
});
if !is_equal(&clientOrderId, &Value::Null) {
let mut cloids: Value = ternary(is_true(&Value::Bool(is_array(&clientOrderId))), clientOrderId.clone(), 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_1196: bool = true;
while { if !__for_first_1196 { i = add(&i, &Value::Int(1)); } __for_first_1196 = false; is_less_than(&i, &get_array_length(&cloids)) } {
append_to_array(&mut cancelReq, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), assetId.clone());
m.insert("cloid".to_string(), get_value(&cloids, &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_1197: bool = true;
while { if !__for_first_1197 { i = add(&i, &Value::Int(1)); } __for_first_1197 = false; is_less_than(&i, &get_array_length(&ids)) } {
append_to_array(&mut cancelReq, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("a".to_string(), assetId.clone());
m.insert("o".to_string(), self.parse_to_numeric(get_value(&ids, &i)));
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_params(params.clone(), Value::Str("cancelOrders".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(cancelAction.clone(), nonce.clone(), &[vaultAddress.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), cancelAction.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 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 outcomeSymbol: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome.clone()]);
let mut requestIds: Value = ids.clone();
if !is_equal(&clientOrderId, &Value::Null) {
if is_true(&Value::Bool(is_array(&clientOrderId))) {
requestIds = clientOrderId.clone();
} else {
requestIds = Value::List(vec![clientOrderId.clone()]);
}
}
let mut orders: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1198: bool = true;
while { if !__for_first_1198 { i = add(&i, &Value::Int(1)); } __for_first_1198 = 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);
let mut error: Value = self.safe_string_k(status.clone(), "error", &[]);
if !is_equal(&error, &Value::Null) {
panic!("{}", crate::exchange_errors::order_not_found(add(&add(&add(&add(&self.id, &Value::Str(" cancelOrders() failed for ".to_string())), &self.safe_string(requestIds.clone(), i.clone(), &[self.safe_string(requestIds.clone(), Value::Int(0), &[])])), &Value::Str(": ".to_string())), &error)));
}
let mut success: bool = is_true(&(is_equal(&status, &Value::Str("success".to_string())))) || is_true(&(is_equal(&self.safe_string_k(status.clone(), "status", &[]), &Value::Str("success".to_string()))));
if !is_true(&success) {
panic!("{}", crate::exchange_errors::exchange_error(add(&add(&self.id, &Value::Str(" cancelOrders() received an unexpected status: ".to_string())), &self.json(status.clone()))));
}
let mut requestId: Value = self.safe_string(requestIds.clone(), i.clone(), &[self.safe_string(requestIds.clone(), Value::Int(0), &[])]);
let mut order: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("clientOrderId".to_string(), ternary(is_true(&(!is_equal(&clientOrderId, &Value::Null))), requestId.clone(), Value::Null));
m.insert("info".to_string(), status.clone());
m.insert("status".to_string(), Value::Str("canceled".to_string()));
m.insert("outcome".to_string(), outcomeSymbol.clone());
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "id", &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("timestamp".to_string(), self.milliseconds());
m.insert("datetime".to_string(), self.iso8601(self.milliseconds()));
m
});
append_to_array(&mut orders, self.safe_prediction_order(order.clone(), &[]));
}
}
return orders;
Value::Null
}
/*
* @method
* @name hyperliquid#fetchOpenOrders
* @description fetches currently open orders for the user
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-open-orders
* @param {string} [outcome] filter by outcome
* @param {int} [since] only return orders updated since this timestamp in ms
* @param {int} [limit] max number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] wallet address
* @param {string} [params.method] 'openOrders' | 'frontendOpenOrders' (default)
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = 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)); }
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 __ws_arg_8 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_8]).await;
let mut ordersWithStatus: 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_1199: bool = true;
while { if !__for_first_1199 { i = add(&i, &Value::Int(1)); } __for_first_1199 = 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);
append_to_array(&mut ordersWithStatus, self.extend(order.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ccxtStatus".to_string(), Value::Str("open".to_string()));
m
})]));
}
}
let mut parsed: Value = self.parse_prediction_orders(ordersWithStatus.clone(), &[Value::Null, since.clone()]);
let mut outcomeHandle: Value = Value::Null;
if !is_equal(&outcome, &Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
outcomeHandle = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
}
return self.filter_by_outcome_since_limit(parsed.clone(), &[outcomeHandle.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchOrders
* @description fetches all historical orders for the user
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-historical-orders
* @param {string} [outcome] filter by outcome
* @param {int} [since] only return orders updated since this timestamp in ms
* @param {int} [limit] max number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] wallet address
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = 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)); }
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
});
let __ws_arg_9 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_9]).await;
// Deduplicate by oid keeping most recent statusTimestamp
let mut deduped: 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_1200: bool = true;
while { if !__for_first_1200 { i = add(&i, &Value::Int(1)); } __for_first_1200 = false; is_less_than(&i, &get_array_length(&historicalOrders)) } {
let mut raw: Value = get_value(&historicalOrders, &i);
let mut raw: Value = get_value(&historicalOrders, &i);
let mut entry: Value = self.safe_dict_k(raw.clone(), "order", &[]);
if is_equal(&entry, &Value::Null) {
entry = raw.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(&deduped, &oid)))) {
add_element_to_object(&mut deduped, &oid, raw.clone());
} else {
let mut existingTs: Value = self.safe_integer_k(get_value(&deduped, &oid), "statusTimestamp", &[]);
let mut currentTs: Value = self.safe_integer_k(raw.clone(), "statusTimestamp", &[]);
if !is_equal(¤tTs, &Value::Null) && is_true(&(is_equal(&existingTs, &Value::Null) || is_greater_than(¤tTs, &existingTs))) {
add_element_to_object(&mut deduped, &oid, raw.clone());
}
}
}
}
}
let mut dedupedValues: Value = object_values(&deduped);
let mut parsed: Value = self.parse_prediction_orders(dedupedValues.clone(), &[Value::Null, since.clone()]);
let mut outcomeHandle: Value = Value::Null;
if !is_equal(&outcome, &Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
outcomeHandle = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
}
return self.filter_by_outcome_since_limit(parsed.clone(), &[outcomeHandle.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchOrder
* @description fetches a single order by id
* @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} [outcome] outcome
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] wallet address
* @param {string} [params.clientOrderId] fetch by client order id instead
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = 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)); }
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 isCloid: 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(&isCloid), id.clone(), self.parse_to_numeric(id.clone())));
}
let __ws_arg_10 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_10]).await;
let mut orderStatus: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_true(&(!is_string(&response))) && !is_true(&Value::Bool(is_array(&response))) {
orderStatus = response.clone();
}
let mut orderWrapper: Value = self.safe_dict_k(orderStatus.clone(), "order", &[orderStatus.clone()]);
let mut parsed: Value = self.parse_prediction_order(orderWrapper.clone(), &[Value::Null]);
if !is_equal(&outcome, &Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut expected: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
if !is_equal(&self.safe_string_k(parsed.clone(), "outcome", &[]), &expected) {
panic!("{}", crate::exchange_errors::order_not_found(add(&add(&add(&add(&self.id, &Value::Str(" fetchOrder() order ".to_string())), &id), &Value::Str(" is not in outcome ".to_string())), &expected)));
}
}
return parsed;
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#parsePredictionOrder
* @description parses a raw hyperliquid order object into a unified order object
* @param {object} order the raw order object
* @param {object} [market] the market the order belongs to
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub fn parse_prediction_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// from frontendOpenOrders:
// {
// "coin": "#10",
// "limitPx": "0.44",
// "oid": 12345,
// "origSz": "100",
// "side": "B",
// "sz": "100",
// "timestamp": 1704346468838
// }
//
// from historicalOrders / orderStatus:
// {
// "order": { "coin": "#10", "limitPx": "0.44", "oid": "12345", "origSz": "100", "side": "B", "sz": "100", "tif": "Gtc", "timestamp": "1704346468838" },
// "status": "open",
// "statusTimestamp": 1704346468838
// }
//
let mut entry: Value = self.safe_dict_k(order.clone(), "order", &[order.clone()]); // eslint-disable-line
let mut status: Value = self.parse_order_status(self.safe_string2(order.clone(), Value::Str("ccxtStatus".to_string()), Value::Str("status".to_string()), &[]));
let mut coin: Value = self.safe_string_k(entry.clone(), "coin", &[]);
let mut outcomeObj: Value = self.safe_outcome(coin.clone(), &[market.clone()]);
let mut marketSymbol: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
let mut resolvedMarket: Value = ternary(is_true(&(!is_equal(&marketSymbol, &Value::Null) && !is_equal(&marketSymbol, &Value::Str("".to_string())))), self.safe_market(&[marketSymbol.clone(), market.clone()]), market.clone());
let mut sideRaw: Value = self.safe_string_k(entry.clone(), "side", &[]);
let mut side: Value = ternary(is_true(&(is_equal(&sideRaw, &Value::Str("B".to_string())))), Value::Str("buy".to_string()), Value::Str("sell".to_string()));
let mut totalAmount: Value = self.safe_string_k(entry.clone(), "origSz", &[]);
let mut remaining: Value = self.safe_string_k(entry.clone(), "sz", &[]);
let mut filled: Value = Value::Null;
if is_true(&(!is_equal(&remaining, &Value::Null))) && is_true(&(!is_equal(&totalAmount, &Value::Null))) {
filled = crate::precise::Precise::stringSub(&totalAmount, &remaining);
}
let mut timestamp: Value = self.safe_integer_k(entry.clone(), "timestamp", &[]);
let mut tifRaw: Value = self.safe_string_k(entry.clone(), "tif", &[]);
let mut tif: Value = self.parse_time_in_force(tifRaw.clone());
let mut postOnly: Value = Value::Bool(is_equal(&tif, &Value::Str("PO".to_string())));
let mut isTrigger: bool = is_equal(&self.safe_bool_k(entry.clone(), "isTrigger", &[]), &Value::Bool(true));
let mut triggerPrice: Value = ternary(is_true(&isTrigger), self.safe_number_k(entry.clone(), "triggerPx", &[]), Value::Null);
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
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("info".to_string(), order.clone());
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("status".to_string(), status.clone());
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "id", &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("type".to_string(), self.parse_order_type(self.safe_string_k(entry.clone(), "orderType", &[Value::Str("limit".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", &[Value::Bool(false)]));
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), self.safe_number_k(entry.clone(), "limitPx", &[]));
m.insert("triggerPrice".to_string(), triggerPrice.clone());
m.insert("amount".to_string(), self.parse_number(totalAmount.clone(), &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), self.safe_number_k(entry.clone(), "avgPx", &[]));
m.insert("filled".to_string(), self.parse_number(filled.clone(), &[]));
m.insert("remaining".to_string(), self.parse_number(remaining.clone(), &[]));
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::List(vec![]));
m
}), &[resolvedMarket.clone()]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
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_equal(&status, &Value::Null) {
return Value::Null;
}
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
});
let mut statusLower: Value = ternary(is_true(&(!is_equal(&status, &Value::Null) && !is_equal(&status, &Value::Str("".to_string())))), to_lower(&status), Value::Null);
return self.safe_string(statuses.clone(), statusLower.clone(), &[statusLower.clone()]);
Value::Null
}
pub fn parse_time_in_force(&self, mut timeInForce: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("gtc".to_string(), Value::Str("GTC".to_string()));
m.insert("ioc".to_string(), Value::Str("IOC".to_string()));
m.insert("fok".to_string(), Value::Str("FOK".to_string()));
m.insert("alo".to_string(), Value::Str("PO".to_string()));
m
});
let mut tifLower: Value = ternary(is_true(&(!is_equal(&timeInForce, &Value::Null) && !is_equal(&timeInForce, &Value::Str("".to_string())))), to_lower(&timeInForce), Value::Null);
return self.safe_string(statuses.clone(), tifLower.clone(), &[timeInForce.clone()]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchTrades
* @description fetches the most recent public trades for an outcome
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-coins-recent-trades
* @param {string} outcome unified outcome
* @param {int} [since] only return trades at or after this timestamp in ms
* @param {int} [limit] the maximum number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn fetch_trades(&mut self, mut outcome: 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
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[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("recentTrades".to_string()));
m.insert("coin".to_string(), self.safe_string_k(info.clone(), "coinName", &[]));
m
});
// recentTrades returns the coin's most recent public trades (newest first)
let __ws_arg_11 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_11]).await;
let mut trades: Value = Value::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
trades = response.clone();
} else if !is_string(&response) {
trades = self.to_array(response.clone());
}
return self.parse_prediction_trades(trades.clone(), &[outcomeObj.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchMyTrades
* @description fetches the authenticated user's fill history
* @see https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-fills
* @param {string} [outcome] filter by outcome
* @param {int} [since] start timestamp in ms
* @param {int} [limit] max number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.user] wallet address
* @param {int} [params.until] end timestamp in ms
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = 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 outcomeHandle: Value = Value::Null;
if !is_equal(&outcome, &Value::Null) {
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
outcomeHandle = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
} else {
// fills identify their outcome only by the raw coin handle (e.g. "#10") — warm the
// cache (one market load) so parsePredictionTrade can resolve the unified outcome identity
self.load_outcomes(&[]).await;
}
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)); }
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_12 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_12]).await;
let mut fills: Value = Value::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
fills = response.clone();
} else if !is_string(&response) {
fills = self.to_array(response.clone());
}
// parse without an outcome fallback — fills span every market the wallet traded, so a
// requested-outcome fallback would mislabel fills whose market is no longer listed
let mut parsedTrades: Value = self.parse_prediction_trades(fills.clone(), &[Value::Null]);
return self.filter_by_outcome_since_limit(parsedTrades.clone(), &[outcomeHandle.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#parsePredictionTrade
* @description parses a single hyperliquid fill into a unified trade object
* @param {object} trade the raw fill object
* @param {object} [market] the market the trade belongs to
* @returns {object} a [prediction trade structure](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub fn parse_prediction_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "closedPnl": "0.19343",
// "coin": "#10",
// "crossed": true,
// "dir": "Open Long",
// "fee": "0.050062",
// "feeToken": "USDC",
// "hash": "0x...",
// "liquidationMarkPx": null,
// "oid": 12345,
// "px": "0.44",
// "side": "B",
// "startPosition": "0",
// "sz": "100",
// "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 outcomeObj: Value = self.safe_outcome(coin.clone(), &[market.clone()]);
let mut marketSymbol: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
let mut resolvedMarket: Value = ternary(is_true(&(!is_equal(&marketSymbol, &Value::Null) && !is_equal(&marketSymbol, &Value::Str("".to_string())))), self.safe_market(&[marketSymbol.clone(), market.clone()]), market.clone());
let mut rawSide: Value = self.safe_string_k(trade.clone(), "side", &[]);
let mut side: Value = ternary(is_true(&(is_equal(&rawSide, &Value::Str("B".to_string())))), Value::Str("buy".to_string()), Value::Str("sell".to_string()));
let mut fee: Value = self.safe_number_k(trade.clone(), "fee", &[]);
let mut feeCurrency: Value = self.safe_string_k(trade.clone(), "feeToken", &[Value::Str("USDC".to_string())]);
let mut outcomeSymbol: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
let mut feeObject: Value = Value::Null;
if !is_equal(&fee, &Value::Null) {
feeObject = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), fee.clone());
m.insert("currency".to_string(), feeCurrency.clone());
m
});
}
let mut cost: Value = Value::Null;
if is_true(&(!is_equal(&price, &Value::Null))) && is_true(&(!is_equal(&amount, &Value::Null))) {
cost = self.parse_number(crate::precise::Precise::stringMul(&price, &amount), &[]);
}
let mut crossed: bool = is_equal(&self.safe_bool_k(trade.clone(), "crossed", &[]), &Value::Bool(true));
let mut takerOrMaker: Value = ternary(is_true(&crossed), Value::Str("taker".to_string()), Value::Str("maker".to_string()));
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "tid", &[]));
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("outcome".to_string(), outcomeSymbol.clone());
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "id", &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("order".to_string(), self.safe_string_k(trade.clone(), "oid", &[]));
m.insert("type".to_string(), Value::Str("limit".to_string()));
m.insert("side".to_string(), side.clone());
m.insert("takerOrMaker".to_string(), takerOrMaker.clone());
m.insert("price".to_string(), self.parse_number(price.clone(), &[]));
m.insert("amount".to_string(), self.parse_number(amount.clone(), &[]));
m.insert("cost".to_string(), cost.clone());
m.insert("fee".to_string(), feeObject.clone());
m
}), &[resolvedMarket.clone()]);
Value::Null
}
/*
* @method
* @name hyperliquid#fetchEvents
* @description Groups outcome markets by their underlying (e.g. BTC_ABOVE_78213) into event structures. Each event contains both the YES and NO markets.
* @param {object} [params] extra parameters
* @param {string} [params.query] a single query string to filter by (matches description/outcome)
* @param {string[]} [params.queries] multiple query strings (alternative to query)
* @returns {PredictionEvent[]} array of event structures
*/
pub async fn fetch_events(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.require_event_query(&[params.clone()]);
let mut queries: Value = self.parse_search_queries(&[params.clone()]);
// hyperliquid has no dedicated events endpoint - events are grouped from the outcome
// markets. use the cached load so the handles advertised here always match the
// outcome cache (hyperliquid re-assigns outcome ids over time; a fresh fetch could
// disagree with a previously warmed cache within the same session)
let mut marketsDict: Value = self.load_markets(&[]).await;
let mut marketValues: Value = self.to_array(marketsDict.clone());
// Group markets by parentSymbol
let mut groupMap: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_equal(&queries, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchEvents() missing queries".to_string()))));
}
let mut lowerQueries: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1201: bool = true;
while { if !__for_first_1201 { i = add(&i, &Value::Int(1)); } __for_first_1201 = false; is_less_than(&i, &get_array_length(&queries)) } {
let mut queryString: Value = get_value(&queries, &i);
let mut queryString: Value = get_value(&queries, &i);
append_to_array(&mut lowerQueries, to_lower(&queryString));
}
}
let mut lowerQueriesLength: Value = get_array_length(&lowerQueries);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1204: bool = true;
while { if !__for_first_1204 { i = add(&i, &Value::Int(1)); } __for_first_1204 = false; is_less_than(&i, &get_array_length(&marketValues)) } {
let mut mkt: Value = get_value(&marketValues, &i);
let mut mkt: Value = get_value(&marketValues, &i);
if !is_true(&self.safe_bool_k(mkt.clone(), "prediction", &[Value::Bool(false)])) {
continue;
}
let mut info: Value = self.safe_dict_k(mkt.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut parentSymbol: Value = self.safe_string_k(info.clone(), "parentSymbol", &[self.safe_string2(mkt.clone(), Value::Str("market".to_string()), Value::Str("symbol".to_string()), &[])]);
// Apply query filter
if is_greater_than(&lowerQueriesLength, &Value::Int(0)) {
let mut description: Value = to_lower(&self.safe_string_k(info.clone(), "description", &[Value::Str("".to_string())]));
let mut parentSymbolOrEmpty: Value = ternary(is_true(&(!is_equal(&parentSymbol, &Value::Null))), parentSymbol.clone(), Value::Str("".to_string()));
let mut symLower: Value = to_lower(&parentSymbolOrEmpty);
// the parentSymbol joins words with underscores (BTC_ABOVE_...), so match the haystack word-by-word
// and require every word of a query to appear, letting "BTC above" match BTC_ABOVE
let mut haystack: Value = add(&add(&description, &Value::Str(" ".to_string())), &symLower);
let mut matches: bool = false;
{
let mut qi: Value = Value::Int(0);
let mut __for_first_1203: bool = true;
while { if !__for_first_1203 { qi = add(&qi, &Value::Int(1)); } __for_first_1203 = false; is_less_than(&qi, &get_array_length(&lowerQueries)) } {
let mut words: Value = split(&get_value(&lowerQueries, &qi), &Value::Str(" ".to_string()));
let mut wordsLength: Value = get_array_length(&words);
let mut allWords: bool = true;
{
let mut wi: Value = Value::Int(0);
let mut __for_first_1202: bool = true;
while { if !__for_first_1202 { wi = add(&wi, &Value::Int(1)); } __for_first_1202 = false; is_less_than(&wi, &wordsLength) } {
let mut word: Value = get_value(&words, &wi);
let mut word: Value = get_value(&words, &wi);
// `< 0` (not `=== -1`) — the php transpiler maps `< 0` to `=== false`
if is_true(&(!is_equal(&word, &Value::Str("".to_string())))) && is_true(&(is_less_than(&get_index_of(&haystack, &word), &Value::Int(0)))) {
allWords = false;
break;
}
}
}
if is_true(&allWords) {
matches = true;
break;
}
}
}
if !is_true(&matches) {
continue;
}
}
if is_equal(&parentSymbol, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchEvents() missing parentSymbol".to_string()))));
}
if !is_true(&(Value::Bool(in_op(&groupMap, &parentSymbol)))) {
if !is_equal(&parentSymbol, &Value::Null) {
add_element_to_object(&mut groupMap, &parentSymbol, Value::List(vec![]));
}
}
// push through a local and write the slice back — the go transpiler's
// AppendToArray reassigns only a local copy of a map-stored array, so a
// direct push on groupMap[parentSymbol] loses the element in go
let mut parentMarkets: Value = self.safe_value(groupMap.clone(), parentSymbol.clone(), &[]);
append_to_array(&mut parentMarkets, mkt.clone());
if !is_equal(&parentSymbol, &Value::Null) {
add_element_to_object(&mut groupMap, &parentSymbol, parentMarkets.clone());
}
}
}
let mut events: Value = Value::List(vec![]);
let mut groupKeys: Value = object_keys(&groupMap);
{
let mut gi: Value = Value::Int(0);
let mut __for_first_1205: bool = true;
while { if !__for_first_1205 { gi = add(&gi, &Value::Int(1)); } __for_first_1205 = false; is_less_than(&gi, &get_array_length(&groupKeys)) } {
let mut key: Value = get_value(&groupKeys, &gi);
let mut key: Value = get_value(&groupKeys, &gi);
let mut groupMarkets: Value = get_value(&groupMap, &key);
let mut groupMarkets: Value = get_value(&groupMap, &key);
let mut event: Value = self.parse_event(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("parentSymbol".to_string(), key.clone());
m.insert("markets".to_string(), groupMarkets.clone());
m
}));
append_to_array(&mut events, event.clone());
}
}
return self.apply_event_fetch_params(events.clone(), &[params.clone(), queries.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name hyperliquid#parseEvent
* @description parses a grouped set of outcome markets into a unified prediction event object
* @param {object} raw a dict with parentSymbol and markets entries
* @returns {object} an event structure
*/
pub fn parse_event(&self, mut raw: Value) -> Value {
let mut parentSymbol: Value = self.safe_string_k(raw.clone(), "parentSymbol", &[]);
let mut markets: Value = self.safe_list_k(raw.clone(), "markets", &[Value::List(vec![])]);
// Extract info from first market
let mut marketsLength: Value = get_array_length(&markets);
let mut firstMarket: Value = ternary(is_true(&(is_greater_than(&marketsLength, &Value::Int(0)))), get_value(&markets, &Value::Int(0)), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut firstInfo: Value = self.safe_dict_k(firstMarket.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut desc: Value = self.safe_dict_k(firstInfo.clone(), "parsedDescription", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut underlying: Value = self.safe_string_k(desc.clone(), "underlying", &[]);
let mut targetPrice: Value = self.safe_string_k(desc.clone(), "targetPrice", &[]);
let mut expiryRaw: Value = self.safe_string_k(desc.clone(), "expiry", &[]);
let mut expiryMs: Value = Value::Null;
let mut expiryDatetime: Value = Value::Null;
if is_true(&(!is_equal(&expiryRaw, &Value::Null))) && is_true(&(!is_equal(&expiryRaw, &Value::Str("".to_string())))) {
let mut parts: Value = split(&expiryRaw, &Value::Str("-".to_string()));
let mut partsLength: Value = get_array_length(&parts);
if is_greater_than_or_equal(&partsLength, &Value::Int(1)) && is_equal(&get_array_length(&get_value(&parts, &Value::Int(0))), &Value::Int(8)) {
let mut ymd: Value = get_value(&parts, &Value::Int(0));
let mut hm: Value = ternary(is_true(&(is_greater_than_or_equal(&partsLength, &Value::Int(2)))), get_value(&parts, &Value::Int(1)), Value::Str("0000".to_string()));
let mut isoStr: Value = add(&add(&add(&add(&add(&add(&add(&add(&add(&slice(&ymd, &Value::Int(0), &Value::Int(4)), &Value::Str("-".to_string())), &slice(&ymd, &Value::Int(4), &Value::Int(6))), &Value::Str("-".to_string())), &slice(&ymd, &Value::Int(6), &Value::Int(8))), &Value::Str("T".to_string())), &slice(&hm, &Value::Int(0), &Value::Int(2))), &Value::Str(":".to_string())), &slice(&hm, &Value::Int(2), &Value::Int(4))), &Value::Str(":00Z".to_string()));
expiryMs = self.parse8601(isoStr.clone());
expiryDatetime = isoStr.clone();
}
}
let mut firstExpiry: Value = self.safe_integer_k(firstMarket.clone(), "expiry", &[]);
let mut title: Value = parentSymbol.clone();
if !is_equal(&underlying, &Value::Null) {
let mut titleSuffix: Value = Value::Str("".to_string());
if is_true(&(!is_equal(&targetPrice, &Value::Null))) && is_true(&(!is_equal(&targetPrice, &Value::Str("".to_string())))) {
titleSuffix = add(&add(&titleSuffix, &Value::Str(" ABOVE ".to_string())), &targetPrice);
}
if is_true(&(!is_equal(&expiryRaw, &Value::Null))) && is_true(&(!is_equal(&expiryRaw, &Value::Str("".to_string())))) {
titleSuffix = add(&add(&titleSuffix, &Value::Str(" @ ".to_string())), &expiryRaw);
}
title = add(&underlying, &titleSuffix);
}
let mut endValue: Value = ternary(is_true(&(!is_equal(&expiryMs, &Value::Null))), expiryMs.clone(), firstExpiry.clone());
let __ws_arg_13 = self.safe_string_k(desc.clone(), "class", &[]);
let __ws_arg_14 = self.safe_string_k(desc.clone(), "period", &[]);
return self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), parentSymbol.clone());
m.insert("slug".to_string(), parentSymbol.clone());
m.insert("event".to_string(), parentSymbol.clone());
m.insert("title".to_string(), title.clone());
m.insert("markets".to_string(), markets.clone());
m.insert("underlying".to_string(), underlying.clone());
m.insert("targetPrice".to_string(), targetPrice.clone());
m.insert("class".to_string(), __ws_arg_13);
m.insert("period".to_string(), __ws_arg_14);
m.insert("url".to_string(), Value::Null);
m.insert("image".to_string(), Value::Null);
m.insert("created".to_string(), Value::Null);
m.insert("createdDatetime".to_string(), Value::Null);
m.insert("end".to_string(), endValue.clone());
m.insert("endDatetime".to_string(), expiryDatetime.clone());
m.insert("category".to_string(), Value::Str("crypto".to_string()));
m.insert("lastUpdatedAt".to_string(), Value::Null);
m.insert("resolutionSource".to_string(), Value::Str("Hyperliquid mark price".to_string()));
m.insert("resolved".to_string(), Value::Null);
m.insert("info".to_string(), raw.clone());
m
}), &[]);
Value::Null
}
pub fn amount_to_precision(&self, mut outcome: Value, mut amount: Value) -> Value {
let mut market: Value = self.market(outcome.clone());
let mut prec: Value = self.safe_number(self.safe_dict_k(market.clone(), "precision", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("amount".to_string()), &[Value::Float(0.0001)]);
// Convert precision to decimal places
let mut decimals: Value = Value::Int(4);
if is_equal(&prec, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" amountToPrecision() missing prec".to_string()))));
}
if is_greater_than(&prec, &Value::Int(0)) {
decimals = self.precision_from_string(self.number_to_string(prec.clone()));
}
return self.decimal_to_precision(amount.clone(), Value::Int(1), decimals.clone(), &[Value::Int(2), self.paddingMode.clone()]);
Value::Null
}
pub fn price_to_precision(&self, mut outcome: Value, mut price: Value) -> Value {
let mut market: Value = self.market(outcome.clone());
let mut prec: Value = self.safe_number(self.safe_dict_k(market.clone(), "precision", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("price".to_string()), &[Value::Float(0.0001)]);
let mut decimals: Value = Value::Int(4);
if is_equal(&prec, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" priceToPrecision() missing prec".to_string()))));
}
if is_greater_than(&prec, &Value::Int(0)) {
decimals = self.precision_from_string(self.number_to_string(prec.clone()));
}
return self.decimal_to_precision(price.clone(), Value::Int(1), decimals.clone(), &[Value::Int(2), 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);
// assign to a bare local before padStart — `expr['key'].padStart()` leaks an undefined
// padStart() call in the PHP transpiler (it only rewrites padStart on a bare identifier)
let mut rRaw: Value = get_value(&signature, &Value::Str("r".to_string()));
let mut sRaw: Value = get_value(&signature, &Value::Str("s".to_string()));
let mut r: Value = pad_start(&rRaw, &Value::Int(64), &Value::Str("0".to_string()));
let mut s: Value = pad_start(&sRaw, &Value::Int(64), &Value::Str("0".to_string()));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("r".to_string(), add(&Value::Str("0x".to_string()), &r));
m.insert("s".to_string(), add(&Value::Str("0x".to_string()), &s));
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) -> Value {
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);
}
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 vaultAddress = get_arg(optional_args, 0, Value::Null);
self.check_required_credentials(&[]);
let mut hash: Value = self.action_hash(action.clone(), vaultAddress.clone(), nonce.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()]);
let mut zeroAddress: Value = self.safe_string_k(self.options.clone(), "zeroAddress", &[]);
let mut domain: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("chainId".to_string(), Value::Int(1337));
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());
return self.sign_message(msg.clone(), self.privateKey.clone());
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);
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_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
}
/*
* @method
* @name hyperliquid#approveBuilderFee
* @ignore
* @description approves the builder for the given max fee rate, required before orders can carry a builder attribution
* @param {string} builder the builder wallet address
* @param {string} maxFeeRate the maximum builder fee rate to approve, e.g. '0%'
* @returns {object} the raw exchange response
*/
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 {
// createOrder/createOrders call this before trading; load markets so the order builder can
// resolve the outcome's market and precision. loading them also keeps this method genuinely
// async for the PHP and typed transpilers, which mishandle an async body that never suspends
self.load_markets(&[]).await;
let mut buildFee: Value = self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(false)]);
if !is_equal(&buildFee, &Value::Bool(true)) {
return Value::Null;
}
if is_true(&self.safe_bool_k(self.options.clone(), "approvedBuilderFee", &[Value::Bool(false)])) {
return Value::Null;
}
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())]);
// the default feeRate is '0%': the builder is approved and attached for statistics
// purposes only and the user is not charged; set options.feeRate/feeInt to charge a fee
let mut maxFeeRate: Value = self.safe_string_k(self.options.clone(), "feeRate", &[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::Null;
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_equal(&user, &Value::Null) && !is_equal(&user, &Value::Str("".to_string())) {
return Value::List(vec![user.clone(), params.clone()]);
}
if !is_equal(&self.walletAddress, &Value::Null) && !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 or walletAddress to be set".to_string()))));
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;
}
let mut normalized: Value = address.clone();
if is_true(&Value::Bool(starts_with(&normalized, &Value::Str("0x".to_string())))) || is_true(&Value::Bool(starts_with(&normalized, &Value::Str("0X".to_string())))) {
normalized = slice(&normalized, &Value::Int(2), &Value::Null);
}
return to_lower(&normalized);
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("POST".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 apiGroup: Value = ternary(is_true(&Value::Bool(is_array(&api))), get_value(&api, &Value::Int(0)), api.clone());
let mut sandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut baseUrl: Value = Value::Null;
if is_equal(&sandboxMode, &Value::Bool(true)) {
let mut testUrls: Value = self.safe_dict_k(self.urls.clone(), "test", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
baseUrl = self.safe_string(testUrls.clone(), apiGroup.clone(), &[self.safe_string_k(testUrls.clone(), "public", &[Value::Str("".to_string())])]);
} else {
let mut apiUrls: Value = self.safe_dict_k(self.urls.clone(), "api", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
baseUrl = self.safe_string(apiUrls.clone(), apiGroup.clone(), &[self.safe_string_k(apiUrls.clone(), "public", &[Value::Str("".to_string())])]);
}
let mut url: Value = add(&add(&baseUrl, &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 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_equal(&response, &Value::Null) {
return Value::Null;
}
let mut status: Value = self.safe_string_k(response.clone(), "status", &[Value::Str("".to_string())]);
if is_equal(&status, &Value::Str("err".to_string())) {
let mut message: Value = self.safe_string_k(response.clone(), "response", &[body.clone()]);
let mut feedback: Value = add(&add(&self.id, &Value::Str(" ".to_string())), &body);
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());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
// Check for error statuses in order responses
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_1206: bool = true;
while { if !__for_first_1206 { i = add(&i, &Value::Int(1)); } __for_first_1206 = false; is_less_than(&i, &get_array_length(&statuses)) } {
let mut message: Value = self.safe_string_k(get_value(&statuses, &i), "error", &[]);
if !is_equal(&message, &Value::Null) {
let mut feedback: Value = add(&add(&self.id, &Value::Str(" ".to_string())), &body);
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());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
}
}
return Value::Null;
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
}
}