// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
use crate::pro::*;
pub struct HtxCore {
pub parent: crate::exchanges::htx::HtxCore,
}
impl HtxCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::htx::HtxCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = HtxCore::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 HtxCore {
fn nonce(&self, ) -> crate::Value {
crate::exchange::DerivedExchange::nonce(&self.parent)
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_ticker(&self.parent, ticker, market)
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_trade(&self.parent, trade, market)
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_order(&self.parent, order, market)
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_market(&self.parent, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_ohlcv(&self.parent, ohlcv, market)
}
fn parse_order_book(&self, ob: crate::Value, symbol: crate::Value, ts: crate::Value, bk: crate::Value, ak: crate::Value, pk: crate::Value, ak2: crate::Value, ck: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_order_book(&self.parent, ob, symbol, ts, bk, ak, pk, ak2, ck)
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_balance(&self.parent, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_position(&self.parent, position, market)
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_funding_rate(&self.parent, rate, market)
}
fn parse_deposit(&self, tx: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_deposit(&self.parent, tx, currency)
}
fn parse_deposit_address(&self, depositAddress: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_deposit_address(&self.parent, depositAddress, currency)
}
fn parse_last_price(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_last_price(&self.parent, entry, market)
}
fn parse_withdrawal(&self, tx: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_withdrawal(&self.parent, tx, currency)
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_ledger_entry(&self.parent, entry, currency)
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_transfer(&self.parent, transfer, currency)
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_currency(&self.parent, currency)
}
fn parse_bid_ask(&self, bidask: crate::Value, price_key: crate::Value, amount_key: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_bid_ask(&self.parent, bidask, price_key, amount_key, market)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_open_interest(&self.parent, interest, market)
}
fn parse_liquidation(&self, liquidation: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_liquidation(&self.parent, liquidation, market)
}
fn parse_funding_rate_history(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_funding_rate_history(&self.parent, entry, market)
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_margin_modification(&self.parent, data, market)
}
fn parse_account(&self, account: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_account(&self.parent, account)
}
fn parse_my_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_my_trade(&self.parent, trade, market)
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_transaction(&self.parent, transaction, currency)
}
fn parse_borrow_interest(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_borrow_interest(&self.parent, info, market)
}
fn parse_adl_rank(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_adl_rank(&self.parent, info, market)
}
fn parse_income(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_income(&self.parent, info, market)
}
fn parse_greeks(&self, greeks: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_greeks(&self.parent, greeks, market)
}
fn parse_margin_mode(&self, margin_mode: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_margin_mode(&self.parent, margin_mode, market)
}
fn parse_conversion(&self, conversion: crate::Value, from_currency: crate::Value, to_currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_conversion(&self.parent, conversion, from_currency, to_currency)
}
fn parse_borrow_rate(&self, info: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_borrow_rate(&self.parent, info, currency)
}
fn parse_leverage(&self, leverage: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_leverage(&self.parent, leverage, market)
}
fn parse_market_leverage_tiers(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_market_leverage_tiers(&self.parent, info, market)
}
fn parse_deposit_withdraw_fee(&self, fee: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_deposit_withdraw_fee(&self.parent, fee, currency)
}
fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_prediction_trade(&self.parent, trade, market)
}
fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_prediction_order(&self.parent, order, market)
}
fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_prediction_position(&self.parent, position, market)
}
fn create_expired_option_market(&self, symbol: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::create_expired_option_market(&self.parent, symbol)
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::sign(&self.parent, path, api, method, params, headers, body)
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::handle_errors(&self.parent, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for HtxCore {
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 {
"authenticate" => self.authenticate(&args[..]).await,
"get_order_channel_and_message_hash" => self.get_order_channel_and_message_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]),
"get_v5_linear_channel_and_message_hash" => self.get_v5_linear_channel_and_message_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"handle_error_message" => self.handle_error_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book_snapshot" => { self.handle_order_book_snapshot(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)).await; crate::Value::Null },
"handle_system_status" => self.handle_system_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_ticker" => self.handle_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_trades" => self.handle_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_order_trade" => self.parse_order_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_order" => self.parse_ws_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_trade" => self.parse_ws_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"pong" => self.pong(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"request_id" => self.request_id(),
"subscribe_private" => self.subscribe_private(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"subscribe_public" => self.subscribe_public(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"un_watch_ohlcv" => self.un_watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_order_book" => self.un_watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_ticker" => self.un_watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_trades" => self.un_watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"unsubscribe_public" => self.unsubscribe_public(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"watch_balance" => self.watch_balance(&args[..]).await,
"watch_my_trades" => self.watch_my_trades(&args[..]).await,
"watch_ohlcv" => self.watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book_snapshot" => self.watch_order_book_snapshot(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)).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_positions" => self.watch_positions(&args[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
// Go-style inheritance: an un-overridden method dispatches to the parent core.
_ => crate::exchange_generated::ExchangeBase::call_dynamic(&mut self.parent, method, args).await,
}
})
}
}
impl HtxCore {
/// Synchronous WS handler dispatch — routes a handler-name string (from the
/// venue's handle_message dispatch table) to the real handler method.
#[allow(dead_code, unreachable_patterns, clippy::all)]
pub fn dispatch_ws_handler(&mut self, __name: &crate::Value, args: &[crate::Value]) -> crate::Value {
let __n = match __name { crate::Value::Str(s) => s.as_ref(), _ => return crate::Value::Null };
match __n {
"authenticate" => { crate::exchange_stubs::enqueue_spawn("authenticate", args.to_vec()); crate::Value::Null },
"get_order_channel_and_message_hash" => self.get_order_channel_and_message_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]),
"get_v5_linear_channel_and_message_hash" => self.get_v5_linear_channel_and_message_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"handle_authenticate" => { self.handle_authenticate(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_balance" => { self.handle_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_delta" => { self.handle_delta(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_deltas" => { self.handle_deltas(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_error_message" => self.handle_error_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_my_trade" => { self.handle_my_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]); crate::Value::Null },
"handle_ohlcv" => { self.handle_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order" => { self.handle_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book" => { self.handle_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book_message" => { self.handle_order_book_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book_snapshot" => { crate::exchange_stubs::enqueue_spawn("handle_order_book_snapshot", args.to_vec()); crate::Value::Null },
"handle_order_book_subscription" => { self.handle_order_book_subscription(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)); crate::Value::Null },
"handle_ping" => { self.handle_ping(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_positions" => { self.handle_positions(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_subject" => { self.handle_subject(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_subscription_status" => { self.handle_subscription_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_system_status" => self.handle_system_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_ticker" => self.handle_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_trades" => self.handle_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_un_subscription" => { self.handle_un_subscription(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"parse_order_trade" => self.parse_order_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_order" => self.parse_ws_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_trade" => self.parse_ws_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"pong" => { crate::exchange_stubs::enqueue_spawn("pong", args.to_vec()); crate::Value::Null },
"request_id" => self.request_id(),
"subscribe_private" => { crate::exchange_stubs::enqueue_spawn("subscribe_private", args.to_vec()); crate::Value::Null },
"subscribe_public" => { crate::exchange_stubs::enqueue_spawn("subscribe_public", args.to_vec()); crate::Value::Null },
"un_watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("un_watch_ohlcv", args.to_vec()); crate::Value::Null },
"un_watch_order_book" => { crate::exchange_stubs::enqueue_spawn("un_watch_order_book", args.to_vec()); crate::Value::Null },
"un_watch_ticker" => { crate::exchange_stubs::enqueue_spawn("un_watch_ticker", args.to_vec()); crate::Value::Null },
"un_watch_trades" => { crate::exchange_stubs::enqueue_spawn("un_watch_trades", args.to_vec()); crate::Value::Null },
"unsubscribe_public" => { crate::exchange_stubs::enqueue_spawn("unsubscribe_public", args.to_vec()); crate::Value::Null },
"watch_balance" => { crate::exchange_stubs::enqueue_spawn("watch_balance", args.to_vec()); crate::Value::Null },
"watch_my_trades" => { crate::exchange_stubs::enqueue_spawn("watch_my_trades", args.to_vec()); crate::Value::Null },
"watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("watch_ohlcv", args.to_vec()); crate::Value::Null },
"watch_order_book" => { crate::exchange_stubs::enqueue_spawn("watch_order_book", args.to_vec()); crate::Value::Null },
"watch_order_book_snapshot" => { crate::exchange_stubs::enqueue_spawn("watch_order_book_snapshot", args.to_vec()); crate::Value::Null },
"watch_orders" => { crate::exchange_stubs::enqueue_spawn("watch_orders", args.to_vec()); crate::Value::Null },
"watch_positions" => { crate::exchange_stubs::enqueue_spawn("watch_positions", args.to_vec()); crate::Value::Null },
"watch_ticker" => { crate::exchange_stubs::enqueue_spawn("watch_ticker", args.to_vec()); crate::Value::Null },
"watch_trades" => { crate::exchange_stubs::enqueue_spawn("watch_trades", args.to_vec()); crate::Value::Null },
_ => crate::Value::Null,
}
}
}
impl std::ops::Deref for HtxCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for HtxCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl HtxCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.parent.describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Bool(true));
m.insert("createOrderWs".to_string(), Value::Bool(false));
m.insert("editOrderWs".to_string(), Value::Bool(false));
m.insert("fetchOpenOrdersWs".to_string(), Value::Bool(false));
m.insert("fetchOrderWs".to_string(), Value::Bool(false));
m.insert("cancelOrderWs".to_string(), Value::Bool(false));
m.insert("cancelOrdersWs".to_string(), Value::Bool(false));
m.insert("cancelAllOrdersWs".to_string(), Value::Bool(false));
m.insert("fetchTradesWs".to_string(), Value::Bool(false));
m.insert("fetchBalanceWs".to_string(), Value::Bool(false));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(false));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m.insert("watchTradesForSymbols".to_string(), Value::Bool(false));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchBalance".to_string(), Value::Bool(true));
m.insert("watchOHLCV".to_string(), Value::Bool(true));
m.insert("unWatchTicker".to_string(), Value::Bool(true));
m.insert("unWatchOHLCV".to_string(), Value::Bool(true));
m.insert("unWatchTrades".to_string(), Value::Bool(true));
m.insert("unWatchOrderBook".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("wss://{hostname}/ws".into()));
m.insert("private".to_string(), Value::Str("wss://{hostname}/ws/v2".into()));
m.insert("feed".to_string(), Value::Str("wss://{hostname}/feed".into()));
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("wss://api.hbdm.vn/linear-swap-ws".into()));
m.insert("private".to_string(), Value::Str("wss://api.hbdm.vn/linear-swap-notification".into()));
m.insert("privateV5".to_string(), Value::Str("wss://api.hbdm.vn/ws/v5/notification".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("wss://api.hbdm.vn/ws".into()));
m.insert("private".to_string(), Value::Str("wss://api.hbdm.vn/notification".into()));
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("wss://api.hbdm.vn/swap-ws".into()));
m.insert("private".to_string(), Value::Str("wss://api.hbdm.vn/swap-notification".into()));
m
}));
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("wss://api.hbdm.vn/linear-swap-ws".into()));
m.insert("private".to_string(), Value::Str("wss://api.hbdm.vn/linear-swap-notification".into()));
m.insert("privateV5".to_string(), Value::Str("wss://api.hbdm.vn/ws/v5/notification".into()));
m
}));
m
}));
m
}));
m.insert("api-aws".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("wss://api-aws.huobi.pro/ws".into()));
m.insert("private".to_string(), Value::Str("wss://api-aws.huobi.pro/ws/v2".into()));
m.insert("feed".to_string(), Value::Str("wss://{hostname}/feed".into()));
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("wss://api.hbdm.vn/linear-swap-ws".into()));
m.insert("private".to_string(), Value::Str("wss://api.hbdm.vn/linear-swap-notification".into()));
m.insert("privateV5".to_string(), Value::Str("wss://api.hbdm.vn/ws/v5/notification".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("wss://api.hbdm.vn/ws".into()));
m.insert("private".to_string(), Value::Str("wss://api.hbdm.vn/notification".into()));
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("wss://api.hbdm.vn/linear-swap-ws".into()));
m.insert("private".to_string(), Value::Str("wss://api.hbdm.vn/linear-swap-notification".into()));
m.insert("privateV5".to_string(), Value::Str("wss://api.hbdm.vn/ws/v5/notification".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("wss://api.hbdm.vn/swap-ws".into()));
m.insert("private".to_string(), Value::Str("wss://api.hbdm.vn/swap-notification".into()));
m
}));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tradesLimit".to_string(), Value::Int(1000));
m.insert("OHLCVLimit".to_string(), Value::Int(1000));
m.insert("api".to_string(), Value::Str("api".into()));
m.insert("watchOrderBook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("maxRetries".to_string(), Value::Int(3));
m.insert("checksum".to_string(), Value::Bool(true));
m.insert("depth".to_string(), Value::Int(150));
m
}));
m.insert("ws".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("gunzip".to_string(), Value::Bool(true));
m
}));
m.insert("watchTicker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("market.{marketId}.detail".into()));
m
}));
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".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("bad-request".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2002".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("2021".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2001".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("2011".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("2040".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("4007".to_string(), Value::Str("BadRequest".into()).clone());
m
}));
m
}));
m
}));
m
})]);
Value::Null
}
pub fn request_id(&mut self) -> Value {
self.lock_id(&[]);
let mut requestId: Value = self.sum(&[self.safe_integer_k(self.options.clone(), "requestId", &[Value::Int(0)]), Value::Int(1)]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("requestId".into(), requestId.clone()); }
self.unlock_id(&[]);
return to_string_val(&requestId);
Value::Null
}
/*
* @method
* @name htx#watchTicker
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://www.htx.com/en-us/opend/newApiPages/?id=7ec53561-7773-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=28c33ab2-77ae-11ed-9966-0242ac110003
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchTicker", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut topic: Value = self.safe_string_k(options, "name", &[Value::Str("market.{marketId}.detail".into())]);
if (topic.as_str() == Some("market.{marketId}.ticker")) && (market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null).as_str() != Some("spot")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" watchTicker() with name market.{marketId}.ticker is only allowed for spot markets, use market.{marketId}.detail instead".into()))));
}
let mut messageHash: Value = self.implode_params(topic, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
}));
let mut url: Value = self.get_url_by_market_type(market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null), &[market.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null)]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
return self.subscribe_public(url, symbol, messageHash, &[Value::Null, params]).await;
Value::Null
}
/*
* @method
* @name htx#unWatchTicker
* @description unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
* @see https://www.htx.com/en-us/opend/newApiPages/?id=7ec53561-7773-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=28c33ab2-77ae-11ed-9966-0242ac110003
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn un_watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut topic: Value = Value::Str("ticker".into());
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchTicker", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut channel: Value = self.safe_string_k(options, "name", &[Value::Str("market.{marketId}.detail".into())]);
if (channel.as_str() == Some("market.{marketId}.ticker")) && (market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null).as_str() != Some("spot")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" watchTicker() with name market.{marketId}.ticker is only allowed for spot markets, use market.{marketId}.detail instead".into()))));
}
let mut subMessageHash: Value = self.implode_params(channel, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
}));
return self.unsubscribe_public(market, subMessageHash, topic, &[params]).await;
Value::Null
}
pub fn handle_ticker(&mut self, mut client: Value, mut message: Value) -> Value {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// "market.btcusdt.detail"
// {
// "ch": "market.btcusdt.detail",
// "ts": 1583494163784,
// "tick": {
// "id": 209988464418,
// "low": 8988,
// "high": 9155.41,
// "open": 9078.91,
// "close": 9136.46,
// "vol": 237813910.5928412,
// "amount": 26184.202558551195,
// "version": 209988464418,
// "count": 265673
// }
// }
// "market.btcusdt.bbo"
// {
// "ch": "market.btcusdt.bbo",
// "ts": 1671941599613,
// "tick": {
// "seqId": 161499562790,
// "ask": 16829.51,
// "askSize": 0.707776,
// "bid": 16829.5,
// "bidSize": 1.685945,
// "quoteTime": 1671941599612,
// "symbol": "btcusdt"
// }
// }
//
let mut tick: Value = (match __pro_message.get("tick").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut ch: Value = (match __pro_message.get("ch").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (ch == Value::Null) {
return message;
}
let mut parts: Value = split(&ch, &Value::Str(".".into()));
let mut marketId: Value = self.safe_string(parts, Value::Int(1), &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut ticker: Value = self.parse_ticker(tick, &[market]);
let mut timestamp: Value = (match __pro_message.get("ts").cloned() { Some(Value::Int(__n)) => Value::Int(__n), Some(Value::Float(__f)) => Value::Int(__f as i64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
add_element_to_object(&mut ticker, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut ticker, &Value::Str("datetime".into()), self.iso8601(timestamp));
let mut symbol: Value = ticker.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut self.tickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker.clone()); }
}
client.resolve(&[ticker, ch]);
return message;
Value::Null
}
/*
* @method
* @name htx#watchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://www.htx.com/en-us/opend/newApiPages/?id=7ec53b69-7773-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=28c33c21-77ae-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=28c33cfe-77ae-11ed-9966-0242ac110003
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("market.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".trade.detail".into())).into());
let mut url: Value = self.get_url_by_market_type(market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null), &[market.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null)]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut trades: Value = self.subscribe_public(url, symbol.clone(), messageHash, &[Value::Null, params]).await;
if is_true(&self.newUpdates) {
limit = trades.get_limit(symbol, limit.clone());
}
return self.filter_by_since_limit(trades, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name htx#unWatchTrades
* @description unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
* @see https://www.htx.com/en-us/opend/newApiPages/?id=7ec53b69-7773-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=28c33c21-77ae-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=28c33cfe-77ae-11ed-9966-0242ac110003
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn un_watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut topic: Value = Value::Str("trades".into());
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchTrades", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut channel: Value = self.safe_string_k(options, "name", &[Value::Str("market.{marketId}.trade.detail".into())]);
let mut subMessageHash: Value = self.implode_params(channel, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
}));
return self.unsubscribe_public(market, subMessageHash, topic, &[params]).await;
Value::Null
}
pub fn handle_trades(&mut self, mut client: Value, mut message: Value) -> Value {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "ch": "market.btcusdt.trade.detail",
// "ts": 1583495834011,
// "tick": {
// "id": 105004645372,
// "ts": 1583495833751,
// "data": [
// {
// "id": 1.050046453727319e+22,
// "ts": 1583495833751,
// "tradeId": 102090727790,
// "amount": 0.003893,
// "price": 9150.01,
// "direction": "sell"
// }
// ]
// }
// }
//
let mut tick: Value = (match __pro_message.get("tick").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut data: Value = self.safe_list_k(tick, "data", &[Value::from(vec![])]);
let mut ch: Value = (match __pro_message.get("ch").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (ch == Value::Null) {
return message;
}
let mut parts: Value = split(&ch, &Value::Str(".".into()));
let mut marketId: Value = self.safe_string(parts, Value::Int(1), &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut tradesCache: Value = self.safe_value(self.trades.clone(), symbol.clone(), &[]);
if (tradesCache == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
tradesCache = ArrayCache::new(limit);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), tradesCache.clone()); }
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_378: bool = true;
while { if !__for_first_378 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_378 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut trade: Value = self.parse_trade(data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[market.clone()]);
tradesCache.append(trade);
}
}
client.resolve(&[tradesCache, ch]);
return message;
Value::Null
}
/*
* @method
* @name htx#watchOHLCV
* @description watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://www.htx.com/en-us/opend/newApiPages/?id=7ec53241-7773-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=28c3346a-77ae-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=28c33563-77ae-11ed-9966-0242ac110003
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn watch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut interval: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("market.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".kline.".into())).into()), interval).into());
let mut url: Value = self.get_url_by_market_type(market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null), &[market.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null)]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut ohlcv: Value = self.subscribe_public(url, symbol.clone(), messageHash, &[Value::Null, params]).await;
if is_true(&self.newUpdates) {
limit = ohlcv.get_limit(symbol, limit.clone());
}
return self.filter_by_since_limit(ohlcv, &[since, limit, Value::Int(0), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name htx#unWatchOHLCV
* @description unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://www.htx.com/en-us/opend/newApiPages/?id=7ec53241-7773-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=28c3346a-77ae-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=28c33563-77ae-11ed-9966-0242ac110003
* @param {string} symbol unified symbol of the market
* @param {string} timeframe the length of time each candle represents
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {object} [params.timezone] if provided, kline intervals are interpreted in that timezone instead of UTC, example '+08:00'
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn un_watch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut interval: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("market.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".kline.".into())).into()), interval).into());
let mut topic: Value = Value::Str("ohlcv".into());
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("symbolsAndTimeframes".into(), Value::from(vec![Value::from(vec![market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), timeframe])])); }
return self.unsubscribe_public(market, subMessageHash, topic, &[params]).await;
Value::Null
}
pub fn handle_ohlcv(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "ch": "market.btcusdt.kline.1min",
// "ts": 1583501786794,
// "tick": {
// "id": 1583501760,
// "open": 9094.5,
// "close": 9094.51,
// "low": 9094.5,
// "high": 9094.51,
// "amount": 0.44639786263800907,
// "vol": 4059.76919054,
// "count": 16
// }
// }
//
let mut ch: Value = (match message.get("ch") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (ch == Value::Null) {
return;
}
let mut parts: Value = split(&ch, &Value::Str(".".into()));
let mut marketId: Value = self.safe_string(parts.clone(), Value::Int(1), &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut interval: Value = self.safe_string(parts, Value::Int(3), &[]);
let mut timeframe: Value = self.find_timeframe(interval, &[]);
{ let __be_tmp = self.safe_dict(self.ohlcvs.clone(), symbol.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); if let Value::Dict(__d) = &mut self.ohlcvs { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
let mut stored: Value = self.safe_value(self.safe_value(self.ohlcvs.clone(), symbol.clone(), &[]), timeframe.clone(), &[]);
if (stored == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "OHLCVLimit", &[Value::Int(1000)]);
stored = ArrayCacheByTimestamp::new(limit);
if (symbol != Value::Null) && (timeframe != Value::Null) {
add_element_to_object(get_value_mut(&mut self.ohlcvs, &symbol), &timeframe, stored.clone());
}
}
let mut tick: Value = (match message.get("tick") { Some(__v) if !matches!(__v, Value::Null) && !matches!(__v, Value::Str(__s) if __s.is_empty()) => __v.clone(), _ => Value::Null });
let mut parsed: Value = self.parse_ohlcv(tick, &[market]);
stored.append(parsed);
client.resolve(&[stored, ch]);
}
/*
* @method
* @name htx#watchOrderBook
* @see https://huobiapi.github.io/docs/dm/v1/en/#subscribe-market-depth-data
* @see https://huobiapi.github.io/docs/coin_margined_swap/v1/en/#subscribe-incremental-market-depth-data
* @see https://huobiapi.github.io/docs/usdt_swap/v1/en/#general-subscribe-incremental-market-depth-data
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut allowedLimits: Value = Value::from(vec![Value::Int(5), Value::Int(20), Value::Int(150), Value::Int(400)]);
// 2) 5-level/20-level incremental MBP is a tick by tick feed,
// which means whenever there is an order book change at that level, it pushes an update;
// 150-levels/400-level incremental MBP feed is based on the gap
// between two snapshots at 100ms interval.
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchOrderBook", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (limit == Value::Null) {
limit = self.safe_integer_k(options, "depth", &[Value::Int(150)]);
}
if !(self.in_array(limit.clone(), allowedLimits).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" watchOrderBook market accepts limits of 5, 20, 150 or 400 only".into()))));
}
let mut messageHash: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("market.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".mbp.".into())).into()), self.number_to_string(limit.clone())).into());
} else {
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("market.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".depth.size_".into())).into()), self.number_to_string(limit.clone())).into()), Value::Str(".high_freq".into())).into());
}
let mut url: Value = self.get_url_by_market_type(market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null), &[market.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null), Value::Bool(false), Value::Bool(true)]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut method: Value = Value::Str("handle_order_book_subscription".into()).clone();
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
params = self.extend(params.clone(), &[]);
add_element_to_object(&mut params, &Value::Str("data_type".into()), Value::Str("incremental".into()));
method = Value::Null;
}
let mut orderbook: Value = self.subscribe_public(url, symbol, messageHash, &[method, params]).await;
return orderbook.limit();
Value::Null
}
/*
* @method
* @name htx#unWatchOrderBook
* @description unsubscribe from the orderbook channel
* @see https://huobiapi.github.io/docs/dm/v1/en/#subscribe-market-depth-data
* @see https://huobiapi.github.io/docs/coin_margined_swap/v1/en/#subscribe-incremental-market-depth-data
* @see https://huobiapi.github.io/docs/usdt_swap/v1/en/#general-subscribe-incremental-market-depth-data
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.limit] orderbook limit, default is undefined
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn un_watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut topic: Value = Value::Str("orderbook".into());
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchOrderBook", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut depth: Value = self.safe_integer_k(options, "depth", &[Value::Int(150)]);
let mut subMessageHash: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
subMessageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("market.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".mbp.".into())).into()), self.number_to_string(depth.clone())).into());
} else {
subMessageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("market.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".depth.size_".into())).into()), self.number_to_string(depth)).into()), Value::Str(".high_freq".into())).into());
}
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("data_type".into(), Value::Str("incremental".into())); }
}
return self.unsubscribe_public(market, subMessageHash, topic, &[params]).await;
Value::Null
}
pub async fn handle_order_book_snapshot(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "id": 1583473663565,
// "rep": "market.btcusdt.mbp.150",
// "status": "ok",
// "ts": 1698359289261,
// "data": {
// "seqNum": 104999417756,
// "bids": [
// [9058.27, 0],
// [9058.43, 0],
// [9058.99, 0],
// ],
// "asks": [
// [9084.27, 0.2],
// [9085.69, 0],
// [9085.81, 0],
// ]
// }
// }
//
let mut symbol: Value = self.safe_string_k(subscription.clone(), "symbol", &[]);
let mut messageHash: Value = self.safe_string_k(subscription.clone(), "messageHash", &[]);
if (messageHash == Value::Null) {
return;
}
let mut id: Value = (match __pro_message.get("id").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut lastTimestamp: Value = self.safe_integer_k(subscription.clone(), "lastTimestamp", &[]);
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut orderbook: Value = self.safe_value(self.orderbooks.clone(), symbol.clone(), &[]);
let mut data: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
let mut messages: Value = get_value(&orderbook, &Value::Str("cache".into()));
let mut firstMessage: Value = self.safe_dict(messages.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut snapshot: Value = self.parse_order_book(data.clone(), symbol.clone(), &[]);
let mut tick: Value = self.safe_dict_k(firstMessage, "tick", &[]);
let mut sequence: Value = self.safe_integer_k(tick, "prevSeqNum", &[]);
let mut nonce: Value = self.safe_integer_k(data, "seqNum", &[]);
if (nonce == Value::Null) {
return true;
}
add_element_to_object(&mut snapshot, &Value::Str("nonce".into()), nonce.clone());
let mut snapshotTimestamp: Value = (match __pro_message.get("ts").cloned() { Some(Value::Int(__n)) => Value::Int(__n), Some(Value::Float(__f)) => Value::Int(__f as i64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("lastTimestamp".into(), snapshotTimestamp.clone()); }
let mut snapshotLimit: Value = self.safe_integer_k(subscription.clone(), "limit", &[]);
let mut snapshotOrderBook: Value = self.order_book(&[snapshot.clone(), snapshotLimit]);
client.resolve(&[snapshotOrderBook, id.clone()]);
if (sequence == Value::Null) || (nonce.as_f64().unwrap_or(f64::NAN) < sequence.as_f64().unwrap_or(f64::NAN)) {
let mut maxAttempts: Value = self.handle_option(Value::Str("watchOrderBook".into()), Value::Str("maxRetries".into()), &[Value::Int(3)]);
let mut numAttempts: Value = self.safe_integer_k(subscription.clone(), "numAttempts", &[Value::Int(0)]);
// retry to synchronize if we have not reached maxAttempts yet
if numAttempts.as_f64().unwrap_or(f64::NAN) < maxAttempts.as_f64().unwrap_or(f64::NAN) {
// safety guard
if (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash)) {
numAttempts = self.sum(&[numAttempts.clone(), Value::Int(1)]);
let mut delayTime: Value = Value::Int(1000);
if (lastTimestamp != Value::Null) && (snapshotTimestamp != Value::Null) {
delayTime = self.sum(&[Value::Int(1000), (match (&(lastTimestamp), &(snapshotTimestamp)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })]);
}
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("numAttempts".into(), numAttempts); }
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash, subscription.clone());
self.delay(delayTime, &[Value::Str("watch_order_book_snapshot".into()).clone(), client.clone(), message, subscription]).await;
}
} else {
panic!("{}", crate::exchange_errors::invalid_nonce(format!("{}{}", add(&Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" failed to synchronize WebSocket feed with the snapshot for symbol ".into())).into()), symbol).into()), Value::Str(" in ".into())).into()), &to_string_val(&maxAttempts)), Value::Str(" attempts".into()))));
}
} else {
orderbook.reset(snapshot);
{
let mut i: Value = Value::Int(0);
let mut __for_first_379: bool = true;
while { if !__for_first_379 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_379 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&messages).as_f64().unwrap_or(f64::NAN) } {
self.handle_order_book_message(client.clone(), get_value(&messages, &i));
}
}
crate::set_value(&mut orderbook, &Value::Str("cache".into()), Value::from(vec![]));
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), orderbook.clone()); }
}
client.resolve(&[orderbook, messageHash.clone()]);
}
#[allow(unreachable_code)] { false }})).await;
match _try_result { Ok(__try_ret) => { if __try_ret { return; } } Err(_try_err) => { let e: Value = panic_to_value(_try_err);
if (messageHash != Value::Null) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
}
if (symbol != Value::Null) {
remove(&mut self.orderbooks, &symbol);
}
client.reject(&[e, messageHash]);
} }
}
pub async fn watch_order_book_snapshot(&mut self, mut client: Value, mut message: Value, mut subscription: Value) -> Value {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
let mut messageHash: Value = self.safe_string_k(subscription.clone(), "messageHash", &[]);
let mut symbol: Value = self.safe_string_k(subscription.clone(), "symbol", &[]);
let mut limit: Value = self.safe_integer_k(subscription.clone(), "limit", &[]);
let mut timestamp: Value = (match message.get("ts") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
let mut params: Value = self.safe_value_k(subscription.clone(), "params", &[]);
let mut attempts: Value = self.safe_integer_k(subscription, "numAttempts", &[Value::Int(0)]);
let mut market: Value = self.market(symbol.clone());
let mut url: Value = self.get_url_by_market_type(market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null), &[market.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null), Value::Bool(false), Value::Bool(true)]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut requestId: Value = self.request_id();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("req".to_string(), messageHash.clone());
m.insert("id".to_string(), requestId.clone());
m
});
// this is a temporary subscription by a specific requestId
// it has a very short lifetime until the snapshot is received over ws
let mut snapshotSubscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("messageHash".to_string(), messageHash.clone());
m.insert("symbol".to_string(), symbol);
m.insert("limit".to_string(), limit.clone());
m.insert("params".to_string(), params);
m.insert("numAttempts".to_string(), attempts);
m.insert("lastTimestamp".to_string(), timestamp);
m.insert("method".to_string(), Value::Str("handle_order_book_snapshot".into()).clone());
m
});
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut orderbook: Value = self.watch(url, requestId.clone(), &[request, requestId.clone(), snapshotSubscription]).await;
return orderbook.limit();
#[allow(unreachable_code)] { Value::Null }})).await;
match _try_result { Ok(__try_ok) => { if !matches!(__try_ok, Value::Null) { return __try_ok; } return Value::Null; } Err(_try_err) => { let e: Value = panic_to_value(_try_err);
if (messageHash != Value::Null) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
}
client.reject(&[e, messageHash]);
} }
return Value::Null;
Value::Null
}
pub fn handle_delta(&self, mut bookside: Value, mut delta: Value) {
let mut price: Value = self.safe_float(delta.clone(), Value::Int(0), &[]);
let mut amount: Value = self.safe_float(delta, Value::Int(1), &[]);
bookside.store(price, amount);
}
pub fn handle_deltas(&self, mut bookside: Value, mut deltas: Value) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_380: bool = true;
while { if !__for_first_380 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_380 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&deltas).as_f64().unwrap_or(f64::NAN) } {
self.handle_delta(bookside.clone(), get_value(&deltas, &i));
}
}
}
pub fn handle_order_book_message(&self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
// spot markets
//
// {
// "ch": "market.btcusdt.mbp.150",
// "ts": 1583472025885,
// "tick": {
// "seqNum": 104998984994,
// "prevSeqNum": 104998984977,
// "bids": [
// [9058.27, 0],
// [9058.43, 0],
// [9058.99, 0],
// ],
// "asks": [
// [9084.27, 0.2],
// [9085.69, 0],
// [9085.81, 0],
// ]
// }
// }
//
// non-spot market update
//
// {
// "ch":"market.BTC220218.depth.size_150.high_freq",
// "tick":{
// "asks":[],
// "bids":[
// [43445.74,1],
// [43444.48,0 ],
// [40593.92,9]
// ],
// "ch":"market.BTC220218.depth.size_150.high_freq",
// "event":"update",
// "id":152727500274,
// "mrid":152727500274,
// "ts":1645023376098,
// "version":37536690
// },
// "ts":1645023376098
// }
// non-spot market snapshot
//
// {
// "ch":"market.BTC220218.depth.size_150.high_freq",
// "tick":{
// "asks":[
// [43445.74,1],
// [43444.48,0 ],
// [40593.92,9]
// ],
// "bids":[
// [43445.74,1],
// [43444.48,0 ],
// [40593.92,9]
// ],
// "ch":"market.BTC220218.depth.size_150.high_freq",
// "event":"snapshot",
// "id":152727500274,
// "mrid":152727500274,
// "ts":1645023376098,
// "version":37536690
// },
// "ts":1645023376098
// }
//
let mut ch: Value = (match message.get("ch") { Some(__v) if !matches!(__v, Value::Null) && !matches!(__v, Value::Str(__s) if __s.is_empty()) => __v.clone(), _ => Value::Null });
let mut parts: Value = split(&ch, &Value::Str(".".into()));
let mut marketId: Value = self.safe_string(parts, Value::Int(1), &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
let mut tick: Value = (match message.get("tick") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut seqNum: Value = self.safe_integer_k(tick.clone(), "seqNum", &[]);
let mut prevSeqNum: Value = self.safe_integer_k(tick.clone(), "prevSeqNum", &[]);
let mut event: Option<String> = self.safe_string_k(tick.clone(), "event", &[]).as_str().map(str::to_owned);
let mut version: Value = self.safe_integer_k(tick.clone(), "version", &[]);
let mut timestamp: Value = (match message.get("ts") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
if (event.as_deref() == Some("snapshot")) {
let mut snapshot: Value = self.parse_order_book(tick.clone(), symbol.clone(), &[timestamp.clone()]);
orderbook.reset(snapshot);
add_element_to_object(&mut orderbook, &Value::Str("nonce".into()), version.clone());
}
if (prevSeqNum != Value::Null) && prevSeqNum.as_f64().unwrap_or(f64::NAN) > self.safe_integer_k(orderbook.clone(), "nonce", &[Value::Int(0)]).as_f64().unwrap_or(f64::NAN) {
let mut checksum: Value = self.handle_option(Value::Str("watchOrderBook".into()), Value::Str("checksum".into()), &[Value::Bool(true)]);
if is_equal(&checksum, &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::checksum_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), self.orderbook_checksum_message(symbol))));
}
}
let mut spotConditon: bool = (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) && (prevSeqNum.as_f64() == get_value(&orderbook, &Value::Str("nonce".into())).as_f64());
let mut nonSpotCondition: bool = (market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) && (version != Value::Null) && ((match (&(version), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }).as_f64() == get_value(&orderbook, &Value::Str("nonce".into())).as_f64());
if (spotConditon) || (nonSpotCondition) {
let mut asks: Value = self.safe_list_k(tick.clone(), "asks", &[Value::from(vec![])]);
let mut bids: Value = self.safe_list_k(tick, "bids", &[Value::from(vec![])]);
self.handle_deltas(get_value(&orderbook, &Value::Str("asks".into())), asks);
self.handle_deltas(get_value(&orderbook, &Value::Str("bids".into())), bids);
add_element_to_object(&mut orderbook, &Value::Str("nonce".into()), (if (spotConditon) { seqNum } else { version }));
add_element_to_object(&mut orderbook, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut orderbook, &Value::Str("datetime".into()), self.iso8601(timestamp));
}
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// deltas
//
// spot markets
//
// {
// "ch": "market.btcusdt.mbp.150",
// "ts": 1583472025885,
// "tick": {
// "seqNum": 104998984994,
// "prevSeqNum": 104998984977,
// "bids": [
// [9058.27, 0],
// [9058.43, 0],
// [9058.99, 0],
// ],
// "asks": [
// [9084.27, 0.2],
// [9085.69, 0],
// [9085.81, 0],
// ]
// }
// }
//
// non spot markets
//
// {
// "ch":"market.BTC220218.depth.size_150.high_freq",
// "tick":{
// "asks":[],
// "bids":[
// [43445.74,1],
// [43444.48,0 ],
// [40593.92,9]
// ],
// "ch":"market.BTC220218.depth.size_150.high_freq",
// "event":"update",
// "id":152727500274,
// "mrid":152727500274,
// "ts":1645023376098,
// "version":37536690
// },
// "ts":1645023376098
// }
//
let mut messageHash: Value = (match __pro_message.get("ch").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut tick: Value = (match __pro_message.get("tick").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
let mut event: Option<String> = self.safe_string_k(tick, "event", &[]).as_str().map(str::to_owned);
let mut ch: Value = (match __pro_message.get("ch").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (ch == Value::Null) {
return;
}
let mut parts: Value = split(&ch, &Value::Str(".".into()));
let mut marketId: Value = self.safe_string(parts.clone(), Value::Int(1), &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[]);
if !(in_op(&self.orderbooks, &symbol)) {
let mut size: Value = self.safe_string(parts, Value::Int(3), &[]);
if (size == Value::Null) {
return;
}
let mut sizeParts: Value = split(&size, &Value::Str("_".into()));
let mut limit: Value = self.safe_integer(sizeParts, Value::Int(1), &[]);
{ let __be_tmp = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), limit]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
}
let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
if (event.is_none()) && (get_value(&orderbook, &Value::Str("nonce".into())) == Value::Null) {
crate::runtime::append_to_object_array(&mut orderbook, &Value::Str("cache".into()), message.clone());
} else {
self.handle_order_book_message(client.clone(), message);
client.resolve(&[orderbook, messageHash]);
}
}
pub fn handle_order_book_subscription(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
let mut symbol: Value = self.safe_string_k(subscription.clone(), "symbol", &[]);
let mut market: Value = self.market(symbol.clone());
let mut limit: Value = self.safe_integer_k(subscription.clone(), "limit", &[]);
if (symbol != Value::Null) {
{ let __be_tmp = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), limit]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
}
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
self.spawn(&[Value::Str("watch_order_book_snapshot".into()).clone(), client, message, subscription]);
}
}
/*
* @method
* @name htx#watchMyTrades
* @description watches information on multiple trades made by the user
* @see https://www.htx.com/en-us/opend/newApiPages/?id=7ec53dd5-7773-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-195a35275ff
* @param {string} symbol unified market symbol of the market trades were made in
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trade structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut type_var: Value = Value::Null;
let mut marketId: Value = Value::Str("*".into()); // wildcard
let mut market: Value = Value::Null;
let mut messageHash: Value = Value::Null;
let mut channel: Value = Value::Null;
let mut trades: Value = Value::Null;
let mut subType: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
type_var = market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null);
subType = (if (market.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { Value::Str("linear".into()) } else { Value::Str("inverse".into()) });
marketId = market.as_map().and_then(|__m| __m.get("lowercaseId")).cloned().unwrap_or(Value::Null);
} else {
type_var = self.safe_string_k(self.options.clone(), "defaultType", &[Value::Str("spot".into())]);
type_var = self.safe_string_k(params.clone(), "type", &[type_var.clone()]);
subType = self.safe_string2(self.options.clone(), Value::Str("subType".into()), Value::Str("defaultSubType".into()), &[Value::Str("linear".into())]);
subType = self.safe_string_k(params.clone(), "subType", &[subType.clone()]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("type".into()), Value::Str("subType".into())]), &[]);
}
let mut linear: bool = subType.as_str() == Some("linear");
let mut swap: bool = type_var.as_str() == Some("swap");
let mut future: bool = type_var.as_str() == Some("future");
let mut isV5Linear: Value = Value::Bool(linear && (swap || future));
if (type_var.as_str() == Some("spot")) {
let mut mode: Value = Value::Null;
if (mode == Value::Null) {
mode = self.safe_string2(self.options.clone(), Value::Str("watchMyTrades".into()), Value::Str("mode".into()), &[Value::Str("0".into())]);
mode = self.safe_string_k(params.clone(), "mode", &[mode.clone()]);
params = self.omit(params.clone(), Value::Str("mode".into()), &[]);
}
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("trade.clearing".into()), Value::Str("#".into())).into()), marketId).into()), Value::Str("#".into())).into()), mode).into());
channel = messageHash.clone();
} else if matches!(&isV5Linear, Value::Bool(true)) {
let mut channelAndMessageHashAndParams: Value = self.get_v5_linear_channel_and_message_hash(Value::Str("trade".into()), &[market.clone(), params.clone()]);
channel = self.safe_string(channelAndMessageHashAndParams.clone(), Value::Int(0), &[]);
messageHash = self.safe_string(channelAndMessageHashAndParams.clone(), Value::Int(1), &[]);
params = self.safe_dict(channelAndMessageHashAndParams, Value::Int(2), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
} else {
let mut channelAndMessageHash: Value = self.get_order_channel_and_message_hash(type_var.clone(), subType.clone(), &[market, params.clone()]);
channel = self.safe_string(channelAndMessageHash.clone(), Value::Int(0), &[]);
let mut orderMessageHash: Value = self.safe_string(channelAndMessageHash, Value::Int(1), &[]);
// we will take advantage of the order messageHash because already handles stuff
// like symbol/margin/subtype/type variations
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", orderMessageHash, Value::Str(":".into())).into()), Value::Str("trade".into())).into());
}
let mut subscriptionParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("isV5".to_string(), isV5Linear);
m
});
trades = self.subscribe_private(channel, messageHash, type_var, subType, &[params, subscriptionParams]).await;
if (trades == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchMyTrades() trades is required".into()))));
}
if is_true(&self.newUpdates) {
limit = trades.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_symbol_since_limit(trades, &[symbol, since, limit, Value::Bool(true)]);
Value::Null
}
pub fn get_order_channel_and_message_hash(&self, mut type_var: Value, mut subType: Value, optional_args: &[Value]) -> Value {
let mut market = 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 messageHash: Value = Value::Null;
let mut channel: Value = Value::Null;
let mut orderType: Value = self.safe_string_k(self.options.clone(), "orderType", &[Value::Str("orders".into())]); // orders or matchOrders
orderType = self.safe_string_k(params.clone(), "orderType", &[orderType.clone()]);
params = self.omit(params.clone(), Value::Str("orderType".into()), &[]);
let mut marketCode: Value = Value::Null;
if (market != Value::Null) && (market.as_map().and_then(|__m| __m.get("lowercaseId")).cloned().unwrap_or(Value::Null) != Value::Null) {
marketCode = to_lower(&get_value(&market, &Value::Str("lowercaseId".into())));
}
let mut baseId: Value = (if (market != Value::Null) { market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null) } else { Value::Null });
let mut prefix: Value = orderType;
messageHash = prefix.clone();
if (subType.as_str() == Some("linear")) {
// USDT Margined Contracts Example: LTC/USDT:USDT
let mut marginMode: Option<String> = self.safe_string_k(params, "margin", &[Value::Str("cross".into())]).as_str().map(str::to_owned);
let mut marginPrefix: Value = (if (marginMode.as_deref() == Some("cross")) { Value::Str(format!("{}{}", prefix, Value::Str("_cross".into())).into()) } else { prefix.clone() });
messageHash = marginPrefix.clone();
if (marketCode != Value::Null) {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(format!("{}{}", Value::Str(".".into()), marketCode).into())).into());
channel = messageHash.clone();
} else {
channel = Value::Str(format!("{}{}", Value::Str(format!("{}{}", marginPrefix, Value::Str(".".into())).into()), Value::Str("*".into())).into());
}
} else if (type_var.as_str() == Some("future")) {
// inverse futures Example: BCH/USD:BCH-220408
if (baseId != Value::Null) {
channel = Value::Str(format!("{}{}", Value::Str(format!("{}{}", prefix, Value::Str(".".into())).into()), to_lower(&baseId)).into());
messageHash = channel.clone();
} else {
channel = Value::Str(format!("{}{}", Value::Str(format!("{}{}", prefix, Value::Str(".".into())).into()), Value::Str("*".into())).into());
}
} else {
// inverse swaps: Example: BTC/USD:BTC
if (marketCode != Value::Null) {
channel = Value::Str(format!("{}{}", Value::Str(format!("{}{}", prefix, Value::Str(".".into())).into()), marketCode).into());
messageHash = channel.clone();
} else {
channel = Value::Str(format!("{}{}", Value::Str(format!("{}{}", prefix, Value::Str(".".into())).into()), Value::Str("*".into())).into());
}
}
return Value::from(vec![channel, messageHash]);
Value::Null
}
pub fn get_v5_linear_channel_and_message_hash(&self, mut topic: Value, optional_args: &[Value]) -> Value {
let mut market = 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 contractCode: Value = (if (market != Value::Null) { market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null) } else { self.safe_string_k(params.clone(), "contract_code", &[Value::Str("*".into())]) });
let mut channel: Value = topic.clone();
let mut messageHash: Value = topic.clone();
if (contractCode != Value::Null) && (contractCode.as_str() != Some("*")) {
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", topic, Value::Str(".".into())).into()), to_lower(&contractCode)).into());
}
params = self.omit(params.clone(), Value::Str("contract_code".into()), &[]);
let mut requestParams: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("contract_code".to_string(), contractCode);
m
}), &[params]);
return Value::from(vec![channel, messageHash, requestParams]);
Value::Null
}
/*
* @method
* @name htx#watchOrders
* @description watches information on multiple orders made by the user
* @see https://www.htx.com/en-us/opend/newApiPages/?id=7ec53c8f-7773-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-195a208afe7
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn watch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut type_var: Value = Value::Null;
let mut subType: Value = Value::Null;
let mut market: Value = Value::Null;
let mut suffix: Value = Value::Str("*".into()); // wildcard
if (symbol != Value::Null) {
market = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
type_var = market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null);
suffix = market.as_map().and_then(|__m| __m.get("lowercaseId")).cloned().unwrap_or(Value::Null);
subType = (if (market.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { Value::Str("linear".into()) } else { Value::Str("inverse".into()) });
} else {
type_var = self.safe_string_k(self.options.clone(), "defaultType", &[Value::Str("spot".into())]);
type_var = self.safe_string_k(params.clone(), "type", &[type_var.clone()]);
subType = self.safe_string2(self.options.clone(), Value::Str("subType".into()), Value::Str("defaultSubType".into()), &[Value::Str("linear".into())]);
subType = self.safe_string_k(params.clone(), "subType", &[subType.clone()]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("type".into()), Value::Str("subType".into())]), &[]);
}
let mut linear: bool = subType.as_str() == Some("linear");
let mut swap: bool = type_var.as_str() == Some("swap");
let mut future: bool = type_var.as_str() == Some("future");
let mut isV5Linear: Value = Value::Bool(linear && (swap || future));
let mut messageHash: Value = Value::Null;
let mut channel: Value = Value::Null;
if (type_var.as_str() == Some("spot")) {
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("orders".into()), Value::Str("#".into())).into()), suffix).into());
channel = messageHash.clone();
} else if matches!(&isV5Linear, Value::Bool(true)) {
let mut channelAndMessageHashAndParams: Value = self.get_v5_linear_channel_and_message_hash(Value::Str("orders".into()), &[market.clone(), params.clone()]);
channel = self.safe_string(channelAndMessageHashAndParams.clone(), Value::Int(0), &[]);
messageHash = self.safe_string(channelAndMessageHashAndParams.clone(), Value::Int(1), &[]);
params = self.safe_dict(channelAndMessageHashAndParams, Value::Int(2), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
} else {
let mut channelAndMessageHash: Value = self.get_order_channel_and_message_hash(type_var.clone(), subType.clone(), &[market, params.clone()]);
channel = self.safe_string(channelAndMessageHash.clone(), Value::Int(0), &[]);
messageHash = self.safe_string(channelAndMessageHash, Value::Int(1), &[]);
}
let mut subscriptionParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("isV5".to_string(), isV5Linear);
m
});
let mut orders: Value = self.subscribe_private(channel, messageHash, type_var, subType, &[params, subscriptionParams]).await;
if is_true(&self.newUpdates) {
limit = orders.get_limit(symbol, limit.clone());
}
return self.filter_by_since_limit(orders, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
pub fn handle_order(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// spot
//
// for new order creation
//
// {
// "action":"push",
// "ch":"orders#btcusdt", // or "orders#*" for global subscriptions
// "data": {
// "orderStatus": "submitted",
// "eventType": "creation",
// "totalTradeAmount": 0 // for "submitted" order status
// "orderCreateTime": 1645116048355, // only when `submitted` status
// "orderSource": "spot-web",
// "accountId": 44234548,
// "orderPrice": "100",
// "orderSize": "0.05",
// "symbol": "ethusdt",
// "type": "buy-limit",
// "orderId": "478861479986886",
// "clientOrderId": '',
// }
// }
//
// for filled order, additional fields are present:
//
// "orderStatus": "filled",
// "eventType": "trade",
// "totalTradeAmount": "5.9892649859",
// "tradePrice": "0.676669",
// "tradeVolume": "8.8511",
// "tradeTime": 1760427775894,
// "aggressor": false,
// "execAmt": "8.8511",
// "tradeId": 100599712781,
// "remainAmt": "0",
//
// spot wrapped trade
//
// {
// "action": "push",
// "ch": "orders#ltcusdt",
// "data": {
// "tradePrice": "130.01",
// "tradeVolume": "0.0385",
// "tradeTime": 1648714741525,
// "aggressor": true,
// "execAmt": "0.0385",
// "orderSource": "spot-web",
// "orderSize": "0.0385",
// "remainAmt": "0",
// "tradeId": 101541578884,
// "symbol": "ltcusdt",
// "type": "sell-market",
// "eventType": "trade",
// "clientOrderId": '',
// "orderStatus": "filled",
// "orderId": 509835753860328
// }
// }
//
// non spot order
//
// {
// "contract_type": "swap",
// "pair": "LTC-USDT",
// "business_type": "swap",
// "op": "notify",
// "topic": "orders_cross.ltc-usdt",
// "ts": 1650354508696,
// "symbol": "LTC",
// "contract_code": "LTC-USDT",
// "volume": 1,
// "price": 110.34,
// "order_price_type": "lightning",
// "direction": "sell",
// "offset": "close",
// "status": 6,
// "lever_rate": 1,
// "order_id": "966002354015051776",
// "order_id_str": "966002354015051776",
// "client_order_id": null,
// "order_source": "web",
// "order_type": 1,
// "created_at": 1650354508649,
// "trade_volume": 1,
// "trade_turnover": 11.072,
// "fee": -0.005536,
// "trade_avg_price": 110.72,
// "margin_frozen": 0,
// "profit": -0.045,
// "trade": [
// {
// "trade_fee": -0.005536,
// "fee_asset": "USDT",
// "real_profit": 0.473,
// "profit": -0.045,
// "trade_id": 86678766507,
// "id": "86678766507-966002354015051776-1",
// "trade_volume": 1,
// "trade_price": 110.72,
// "trade_turnover": 11.072,
// "created_at": 1650354508656,
// "role": "taker"
// }
// ],
// "canceled_at": 0,
// "fee_asset": "USDT",
// "margin_asset": "USDT",
// "uid": "359305390",
// "liquidation_type": "0",
// "margin_mode": "cross",
// "margin_account": "USDT",
// "is_tpsl": 0,
// "real_profit": 0.473,
// "trade_partition": "USDT",
// "reduce_only": 1
// }
//
//
// linear v5 watchOrders
//
// {
// "op": "notify",
// "topic": "orders",
// "contract_code": "BTC-USDT",
// "ts": 1782367563267,
// "uid": "359305390",
// "data": {
// "side": "buy",
// "type": "limit",
// "price": "40000",
// "volume": "1",
// "state": "new",
// "profit": "0",
// "contract_code": "BTC-USDT",
// "position_side": "both",
// "price_match": null,
// "order_id": "1519705236917489664",
// "client_order_id": "1519705236917489664",
// "margin_mode": "cross",
// "lever_rate": 10,
// "order_source": "api",
// "reduce_only": false,
// "time_in_force": "gtc",
// "trade_avg_price": "0",
// "trade_volume": "0",
// "trade_turnover": "0",
// "fee_currency": null,
// "fee": "0",
// "tp_trigger_price": "",
// "tp_order_price": "",
// "tp_type": "",
// "tp_trigger_price_type": "",
// "sl_trigger_price": "",
// "sl_order_price": "",
// "sl_type": "",
// "sl_trigger_price_type": "",
// "contract_type": "swap",
// "cancel_reason": "",
// "created_time": "1782367563239",
// "updated_time": "1782367563239",
// "self_match_prevent": "cancel_taker",
// "amend_origin_volume": "",
// "amend_source": "",
// "amend_result": ""
// }
// }
//
let mut messageHash: Value = self.safe_string2(message.clone(), Value::Str("ch".into()), Value::Str("topic".into()), &[]);
let mut data: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
let mut marketId: Value = (match __pro_message.get("contract_code").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (marketId == Value::Null) {
marketId = self.safe_string2(data.clone(), Value::Str("contract_code".into()), Value::Str("symbol".into()), &[]);
}
let mut market: Value = self.safe_market(&[marketId.clone()]);
let mut parsedOrder: Value = Value::Null;
if (data != Value::Null) {
// spot updates
let mut eventType: Option<String> = self.safe_string_k(data.clone(), "eventType", &[]).as_str().map(str::to_owned);
if (eventType.as_deref() == Some("trade")) {
// when a spot order is filled we get an update message
// with the trade info
let mut parsedTrade: Value = self.parse_order_trade(data.clone(), &[market.clone()]);
// inject trade in existing order by faking an order object
let mut orderId: Value = self.safe_string_k(parsedTrade.clone(), "order", &[]);
let mut trades: Value = Value::from(vec![parsedTrade]);
let mut status: Value = self.parent.parse_order_status(self.safe_string2(data.clone(), Value::Str("orderStatus".into()), Value::Str("status".into()), &[Value::Str("closed".into())]));
let mut filled: Value = self.safe_string_k(data.clone(), "execAmt", &[]);
let mut remaining: Value = self.safe_string_k(data.clone(), "remainAmt", &[]);
let mut order: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), orderId);
m.insert("trades".to_string(), trades);
m.insert("status".to_string(), status);
m.insert("lastTradeTimestamp".to_string(), self.safe_integer_k(data.clone(), "tradeTime", &[]));
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("filled".to_string(), self.parse_number(filled, &[]));
m.insert("remaining".to_string(), self.parse_number(remaining, &[]));
m.insert("price".to_string(), self.safe_number_k(data.clone(), "orderPrice", &[]));
m.insert("amount".to_string(), self.safe_number_k(data.clone(), "orderSize", &[]));
m.insert("info".to_string(), data.clone());
m
});
parsedOrder = order;
} else {
parsedOrder = self.parse_ws_order(data, &[market.clone()]);
}
} else {
// contract branch
parsedOrder = self.parse_ws_order(message, &[market.clone()]);
let mut rawTrades: Value = (match __pro_message.get("trade").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
let mut tradesLength: f64 = ((rawTrades.len() as i64) as f64);
if tradesLength > ((0i64) as f64) {
let mut tradesObject: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trades".to_string(), rawTrades);
m.insert("ch".to_string(), messageHash.clone());
m.insert("symbol".to_string(), marketId.clone());
m
});
// inject order params in every trade
let mut extendTradeParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order".to_string(), self.safe_string_k(parsedOrder.clone(), "id", &[]));
m.insert("type".to_string(), self.safe_string_k(parsedOrder.clone(), "type", &[]));
m.insert("side".to_string(), self.safe_string_k(parsedOrder.clone(), "side", &[]));
m
});
// trades arrive inside an order update
// we're forwarding them to handleMyTrade
// so they can be properly resolved
self.handle_my_trade(client.clone(), tradesObject, &[extendTradeParams]);
}
}
if (self.orders.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCacheBySymbolById::new(limit);
}
let mut cachedOrders: Value = self.orders.clone();
cachedOrders.append(parsedOrder);
client.resolve(&[self.orders.clone(), messageHash.clone()]);
if (messageHash.as_str() == Some("orders")) && (marketId != Value::Null) {
let mut specificMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str(".".into())).into()), to_lower(&marketId)).into());
client.resolve(&[self.orders.clone(), specificMessageHash]);
}
// when we make a global subscription (for contracts only) our message hash can't have a symbol/currency attached
// so we're removing it here
if (messageHash == Value::Null) {
return;
}
let mut genericMessageHash: Value = replace_str(&messageHash, &Value::Str(format!("{}{}", Value::Str(".".into()), market.as_map().and_then(|__m| __m.get("lowercaseId")).cloned().unwrap_or(Value::Null)).into()), &Value::Str("".into()));
let mut lowerCaseBaseId: Value = self.safe_string_lower_k(market, "baseId", &[]);
genericMessageHash = replace_str(&genericMessageHash, &Value::Str(format!("{}{}", Value::Str(".".into()), lowerCaseBaseId).into()), &Value::Str("".into()));
client.resolve(&[self.orders.clone(), genericMessageHash]);
}
pub fn parse_ws_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// spot
//
// {
// "orderSource": "spot-web",
// "orderCreateTime": 1645116048355, // creating only
// "accountId": 44234548,
// "orderPrice": "100",
// "orderSize": "0.05",
// "orderValue": "3.71676361", // market-buy only
// "symbol": "ethusdt",
// "type": "buy-limit",
// "orderId": "478861479986886",
// "eventType": "creation",
// "clientOrderId": '',
// "orderStatus": "submitted"
// "lastActTime":1645118621810 // except creating
// "execAmt":"0"
// }
//
// swap order
//
// {
// "contract_type": "swap",
// "pair": "LTC-USDT",
// "business_type": "swap",
// "op": "notify",
// "topic": "orders_cross.ltc-usdt",
// "ts": 1648717911384,
// "symbol": "LTC",
// "contract_code": "LTC-USDT",
// "volume": 1,
// "price": 129.13,
// "order_price_type": "lightning",
// "direction": "sell",
// "offset": "close",
// "status": 6,
// "lever_rate": 5,
// "order_id": "959137967397068800",
// "order_id_str": "959137967397068800",
// "client_order_id": null,
// "order_source": "web",
// "order_type": 1,
// "created_at": 1648717911344,
// "trade_volume": 1,
// "trade_turnover": 12.952,
// "fee": -0.006476,
// "trade_avg_price": 129.52,
// "margin_frozen": 0,
// "profit": -0.005,
// "trade": [
// {
// "trade_fee": -0.006476,
// "fee_asset": "USDT",
// "real_profit": -0.005,
// "profit": -0.005,
// "trade_id": 83619995370,
// "id": "83619995370-959137967397068800-1",
// "trade_volume": 1,
// "trade_price": 129.52,
// "trade_turnover": 12.952,
// "created_at": 1648717911352,
// "role": "taker"
// }
// ],
// "canceled_at": 0,
// "fee_asset": "USDT",
// "margin_asset": "USDT",
// "uid": "359305390",
// "liquidation_type": "0",
// "margin_mode": "cross",
// "margin_account": "USDT",
// "is_tpsl": 0,
// "real_profit": -0.005,
// "trade_partition": "USDT",
// "reduce_only": 1
// }
//
// {
// "op":"notify",
// "topic":"orders.ada",
// "ts":1604388667226,
// "symbol":"ADA",
// "contract_type":"quarter",
// "contract_code":"ADA201225",
// "volume":1,
// "price":0.0905,
// "order_price_type":"post_only",
// "direction":"sell",
// "offset":"open",
// "status":6,
// "lever_rate":20,
// "order_id":773207641127878656,
// "order_id_str":"773207641127878656",
// "client_order_id":null,
// "order_source":"web",
// "order_type":1,
// "created_at":1604388667146,
// "trade_volume":1,
// "trade_turnover":10,
// "fee":-0.022099447513812154,
// "trade_avg_price":0.0905,
// "margin_frozen":0,
// "profit":0,
// "trade":[],
// "canceled_at":0,
// "fee_asset":"ADA",
// "uid":"123456789",
// "liquidation_type":"0",
// "is_tpsl": 0,
// "real_profit": 0
// }
//
// linear v5 watchOrders
//
// {
// "side": "buy",
// "type": "limit",
// "price": "40000",
// "volume": "1",
// "state": "new",
// "profit": "0",
// "contract_code": "BTC-USDT",
// "position_side": "both",
// "price_match": null,
// "order_id": "1519705236917489664",
// "client_order_id": "1519705236917489664",
// "margin_mode": "cross",
// "lever_rate": 10,
// "order_source": "api",
// "reduce_only": false,
// "time_in_force": "gtc",
// "trade_avg_price": "0",
// "trade_volume": "0",
// "trade_turnover": "0",
// "fee_currency": null,
// "fee": "0",
// "tp_trigger_price": "",
// "tp_order_price": "",
// "tp_type": "",
// "tp_trigger_price_type": "",
// "sl_trigger_price": "",
// "sl_order_price": "",
// "sl_type": "",
// "sl_trigger_price_type": "",
// "contract_type": "swap",
// "cancel_reason": "",
// "created_time": "1782367563239",
// "updated_time": "1782367563239",
// "self_match_prevent": "cancel_taker",
// "amend_origin_volume": "",
// "amend_source": "",
// "amend_result": ""
// }
//
let mut lastTradeTimestamp: Value = self.safe_integer_n(order.clone(), Value::from(vec![Value::Str("lastActTime".into()), Value::Str("updated_time".into()), Value::Str("ts".into())]), &[]);
let mut created: Value = self.safe_integer2(order.clone(), Value::Str("orderCreateTime".into()), Value::Str("created_time".into()), &[]);
let mut marketId: Value = self.safe_string2(order.clone(), Value::Str("contract_code".into()), Value::Str("symbol".into()), &[]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut symbol: Value = self.safe_symbol(marketId, &[market.clone()]);
let mut amount: Value = self.safe_string2(order.clone(), Value::Str("orderSize".into()), Value::Str("volume".into()), &[]);
let mut status: Value = self.parent.parse_order_status(self.safe_string_n(order.clone(), Value::from(vec![Value::Str("orderStatus".into()), Value::Str("state".into()), Value::Str("status".into())]), &[]));
let mut id: Value = self.safe_string2(order.clone(), Value::Str("orderId".into()), Value::Str("order_id".into()), &[]);
let mut clientOrderId: Value = self.safe_string2(order.clone(), Value::Str("clientOrderId".into()), Value::Str("client_order_id".into()), &[]);
let mut price: Value = self.safe_string2(order.clone(), Value::Str("orderPrice".into()), Value::Str("price".into()), &[]);
let mut filled: Value = self.safe_string2(order.clone(), Value::Str("execAmt".into()), Value::Str("trade_volume".into()), &[]);
let mut typeSide: Value = self.safe_string_k(order.clone(), "type", &[]);
let mut feeCost: Value = self.safe_string_k(order.clone(), "fee", &[]);
let mut fee: Value = Value::Null;
if (feeCost != Value::Null) {
let mut feeCurrencyId: Value = self.safe_string2(order.clone(), Value::Str("fee_asset".into()), Value::Str("fee_currency".into()), &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost);
m.insert("currency".to_string(), self.safe_currency_code(feeCurrencyId, &[]));
m
});
}
let mut avgPrice: Value = self.safe_string_k(order.clone(), "trade_avg_price", &[]);
let mut rawTrades: Value = self.safe_value_k(order.clone(), "trade", &[]);
let mut typeSideParts: Value = Value::from(vec![]);
let mut type_var: Value = Value::Null;
if (typeSide != Value::Null) {
if Value::Int(typeSide.as_str().and_then(|__s| __s.find("-")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
typeSideParts = split(&typeSide, &Value::Str("-".into()));
type_var = self.safe_string_lower(typeSideParts.clone(), Value::Int(1), &[]);
} else {
type_var = typeSide;
}
}
if (type_var == Value::Null) {
type_var = self.safe_string_k(order.clone(), "order_price_type", &[]);
}
let mut side: Value = self.safe_string_lower(typeSideParts, Value::Int(0), &[]);
if (side == Value::Null) {
side = self.safe_string2(order.clone(), Value::Str("direction".into()), Value::Str("side".into()), &[]);
}
let mut cost: Value = self.safe_string2(order.clone(), Value::Str("orderValue".into()), Value::Str("trade_turnover".into()), &[]);
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), id);
m.insert("clientOrderId".to_string(), clientOrderId);
m.insert("timestamp".to_string(), created.clone());
m.insert("datetime".to_string(), self.iso8601(created));
m.insert("lastTradeTimestamp".to_string(), lastTradeTimestamp);
m.insert("status".to_string(), status);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), type_var);
m.insert("timeInForce".to_string(), self.safe_string_upper_k(order.clone(), "time_in_force", &[]));
m.insert("postOnly".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("filled".to_string(), filled);
m.insert("remaining".to_string(), Value::Null);
m.insert("cost".to_string(), cost);
m.insert("fee".to_string(), fee);
m.insert("average".to_string(), avgPrice);
m.insert("trades".to_string(), rawTrades);
m.insert("reduceOnly".to_string(), self.safe_bool_k(order.clone(), "reduce_only", &[]));
m.insert("stopPrice".to_string(), Value::Null);
m.insert("triggerPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), self.safe_string2(order.clone(), Value::Str("tp_trigger_price".into()), Value::Str("tp_order_price".into()), &[]));
m.insert("stopLossPrice".to_string(), self.safe_string2(order, Value::Str("sl_trigger_price".into()), Value::Str("sl_order_price".into()), &[]));
m
}), &[market]);
Value::Null
}
pub fn parse_order_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
// spot private wrapped trade
//
// {
// "tradePrice": "130.01",
// "tradeVolume": "0.0385",
// "tradeTime": 1648714741525,
// "aggressor": true,
// "execAmt": "0.0385",
// "orderSource": "spot-web",
// "orderSize": "0.0385",
// "remainAmt": "0",
// "tradeId": 101541578884,
// "symbol": "ltcusdt",
// "type": "sell-market",
// "eventType": "trade",
// "clientOrderId": '',
// "orderStatus": "filled",
// "orderId": 509835753860328
// }
//
let mut marketResolved: Value = self.safe_market(&[Value::Null, market.clone()]);
market = marketResolved.clone();
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut tradeId: Value = self.safe_string_k(trade.clone(), "tradeId", &[]);
let mut price: Value = self.safe_string_k(trade.clone(), "tradePrice", &[]);
let mut amount: Value = self.safe_string_k(trade.clone(), "tradeVolume", &[]);
let mut order: Value = self.safe_string_k(trade.clone(), "orderId", &[]);
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "tradeTime", &[]);
let mut type_var: Value = self.safe_string_k(trade.clone(), "type", &[]);
let mut side: Value = Value::Null;
if (type_var != Value::Null) {
let mut typeParts: Value = split(&type_var, &Value::Str("-".into()));
side = typeParts.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
type_var = typeParts.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
}
let mut aggressor: Value = self.safe_bool_k(trade.clone(), "aggressor", &[]);
let mut takerOrMaker: Value = Value::Null;
if (aggressor != Value::Null) {
takerOrMaker = (if (aggressor.as_bool() == Some(true)) { Value::Str("taker".into()) } else { Value::Str("maker".into()) });
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), symbol);
m.insert("id".to_string(), tradeId);
m.insert("order".to_string(), order);
m.insert("type".to_string(), type_var);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name htx#watchPositions
* @description watch all open positions. Note: huobi has one channel for each marginMode and type
* @see https://www.huobi.com/en-in/opend/newApiPages/?id=28c34a7d-77ae-11ed-9966-0242ac110003
* @see https://www.huobi.com/en-in/opend/newApiPages/?id=5d5156b5-77b6-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-195a35d6034
* @param {string[]} [symbols] list of unified market symbols
* @param {int} [since] timestamp in ms of the earliest position to fetch
* @param {int} [limit] the maximum number of positions to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/en/latest/manual.html#position-structure}
*/
pub async fn watch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
let mut messageHash: Value = Value::Str("".into());
if (!(self.is_empty(symbols.clone()).as_bool() == Some(true))) && (symbols != Value::Null) {
market = self.get_market_from_symbols(&[symbols.clone()]);
messageHash = Value::Str(format!("{}{}", Value::Str("::".into()), join(&symbols, &Value::Str(",".into()))).into());
}
let mut type_var: Value = Value::Null;
let mut subType: Value = Value::Null;
if (market != Value::Null) {
type_var = market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null);
subType = (if (market.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { Value::Str("linear".into()) } else { Value::Str("inverse".into()) });
} else {
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchPositions".into()), &[market.clone(), params.clone()]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (type_var.as_str() == Some("spot")) {
type_var = Value::Str("future".into());
}
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchPositions".into()), Value::Str("subType".into()), &[subType.clone()]); subType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("watchPositions".into()), &[params.clone(), Value::Str("cross".into())]); marginMode = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut linear: bool = subType.as_str() == Some("linear");
let mut swap: bool = type_var.as_str() == Some("swap");
let mut future: bool = type_var.as_str() == Some("future");
let mut isV5Linear: Value = Value::Bool(linear && (swap || future));
let mut isLinear: Value = (Value::Bool(subType.as_str() == Some("linear")));
let mut url: Value = self.get_url_by_market_type(type_var.clone(), &[isLinear, Value::Bool(true), Value::Bool(false), isV5Linear.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", marginMode, Value::Str(":positions".into())).into()), messageHash).into());
let mut channel: Value = (if (marginMode.as_str() == Some("cross")) { Value::Str("positions_cross.*".into()) } else { Value::Str("positions.*".into()) });
if matches!(&isV5Linear, Value::Bool(true)) {
let mut v5Market: Value = Value::Null;
if (symbols != Value::Null) && (Value::Int(symbols.len() as i64).as_f64() == Some(1.0)) {
v5Market = market;
}
let mut channelAndMessageHashAndParams: Value = self.get_v5_linear_channel_and_message_hash(Value::Str("positions".into()), &[v5Market, params.clone()]);
channel = self.safe_string(channelAndMessageHashAndParams.clone(), Value::Int(0), &[]);
params = self.safe_dict(channelAndMessageHashAndParams, Value::Int(2), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
let mut subscriptionParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("isV5".to_string(), isV5Linear);
m.insert("margin".to_string(), marginMode.clone());
m
});
let mut newPositions: Value = self.subscribe_private(channel, messageHash, type_var, subType, &[params, subscriptionParams]).await;
if is_true(&self.newUpdates) {
return newPositions;
}
return self.filter_by_symbols_since_limit(self.safe_value(self.safe_value(self.positions.clone(), url, &[]), marginMode, &[]), &[symbols, since, limit, Value::Bool(false)]);
Value::Null
}
pub fn handle_positions(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// op: 'notify',
// topic: 'positions_cross',
// ts: 1696767149650,
// event: 'snapshot',
// data: [
// {
// contract_type: 'swap',
// pair: 'BTC-USDT',
// business_type: 'swap',
// liquidation_price: null,
// symbol: 'BTC',
// contract_code: 'BTC-USDT',
// volume: 1,
// available: 1,
// frozen: 0,
// cost_open: 27802.2,
// cost_hold: 27802.2,
// profit_unreal: 0.0175,
// profit_rate: 0.000629446590557581,
// profit: 0.0175,
// margin_asset: 'USDT',
// position_margin: 27.8197,
// lever_rate: 1,
// direction: 'buy',
// last_price: 27819.7,
// margin_mode: 'cross',
// margin_account: 'USDT',
// trade_partition: 'USDT',
// position_mode: 'dual_side'
// },
// ]
// }
//
// watchPositions linear v5
//
// {
// "op": "notify",
// "topic": "positions",
// "contract_code": "BTC-USDT",
// "ts": 1782460576073,
// "uid": "359305390",
// "event": "snapshot",
// "data": [
// {
// "contract_code": "BTC-USDT",
// "symbol": "BTC",
// "position_mode": "single_side",
// "position_side": "both",
// "direction": "buy",
// "margin_mode": "cross",
// "open_avg_price": "60547.9",
// "volume": "1",
// "available": "1",
// "fee": "0.03632874",
// "break_even_price": "60620.55748",
// "total_trade_fee": "0.03632874",
// "lever_rate": 10,
// "adl_risk_percent": 4,
// "liquidation_price": "-102094.847680676304309652",
// "initial_margin": "6.05807",
// "maintenance_margin": "0.20597438",
// "profit_unreal": "0.0328",
// "profit": "0",
// "profit_rate": "0.0054",
// "margin_rate": "0.0012",
// "state": "normal",
// "funding_fee": "0",
// "mark_price": "60580.7",
// "last_price": "60591.4",
// "contract_type": "swap",
// "version": 7,
// "created_time": "1782460515119",
// "updated_time": "1782460515119"
// }
// ]
// }
//
let mut url: Value = client.as_map().and_then(|__m| __m.get("url")).cloned().unwrap_or(Value::Null);
let mut topic: Option<String> = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) }).as_str().map(str::to_owned);
let mut defaultMarginMode: Value = (if (topic.as_deref() == Some("positions_cross")) { Value::Str("cross".into()) } else { Value::Str("isolated".into()) });
if (self.positions.clone() == Value::Null) {
self.positions = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
let mut clientPositions: Value = self.safe_dict(self.positions.clone(), url.clone(), &[]);
if (clientPositions == Value::Null) {
add_element_to_object(&mut self.positions, &url, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
}
let mut rawPositions: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
if self.is_empty(rawPositions.clone()).as_bool() == Some(true) {
let mut prefixes: Value = Value::from(vec![Value::Str("cross:positions".into()), Value::Str("isolated:positions".into())]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_382: bool = true;
while { if !__for_first_382 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_382 = false; i.as_f64().unwrap_or(f64::NAN) < ((prefixes.len() as i64) as f64) } {
let mut messageHashes: Value = self.find_message_hashes(client.clone(), prefixes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
{
let mut j: Value = Value::Int(0);
let mut __for_first_381: bool = true;
while { if !__for_first_381 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_381 = false; j.as_f64().unwrap_or(f64::NAN) < ((messageHashes.len() as i64) as f64) } {
client.resolve(&[Value::from(vec![]), messageHashes.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null)]);
}
}
}
}
return;
}
let mut newPositions: Value = Value::from(vec![]);
let mut positionsByMarginMode: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut timestamp: Value = (match message.get("ts") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
{
let mut i: Value = Value::Int(0);
let mut __for_first_383: bool = true;
while { if !__for_first_383 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_383 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawPositions.len() as i64) as f64) } {
let mut rawPosition: Value = rawPositions.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut position: Value = self.parse_position(rawPosition, &[]);
add_element_to_object(&mut position, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut position, &Value::Str("datetime".into()), self.iso8601(timestamp.clone()));
let mut marginMode: Value = self.safe_string_lower_k(position.clone(), "marginMode", &[defaultMarginMode.clone()]);
if (marginMode.as_str() != Some("cross")) && (marginMode.as_str() != Some("isolated")) {
marginMode = defaultMarginMode.clone();
}
let mut cache: Value = self.safe_value(get_value(&self.positions, &url), marginMode.clone(), &[]);
if (cache == Value::Null) {
cache = ArrayCacheBySymbolBySide::new(Value::Null);
add_element_to_object(get_value_mut(&mut self.positions, &url), &marginMode, cache.clone());
}
append_to_array(&mut newPositions, position.clone());
{ let __be_tmp = self.safe_list(positionsByMarginMode.clone(), marginMode.clone(), &[Value::from(vec![])]); if let Value::Dict(__d) = &mut positionsByMarginMode { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&marginMode), __be_tmp); } }
crate::runtime::append_to_object_array(&mut positionsByMarginMode, &marginMode, position.clone());
cache.append(position);
}
}
let mut marginModes: Value = object_keys(&positionsByMarginMode);
{
let mut i: Value = Value::Int(0);
let mut __for_first_385: bool = true;
while { if !__for_first_385 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_385 = false; i.as_f64().unwrap_or(f64::NAN) < ((marginModes.len() as i64) as f64) } {
let mut marginMode: Value = marginModes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut marginModePositions: Value = self.safe_list(positionsByMarginMode.clone(), marginMode.clone(), &[Value::from(vec![])]);
let mut messageHashes: Value = self.find_message_hashes(client.clone(), Value::Str(format!("{}{}", marginMode, Value::Str(":positions::".into())).into()));
{
let mut j: Value = Value::Int(0);
let mut __for_first_384: bool = true;
while { if !__for_first_384 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_384 = false; j.as_f64().unwrap_or(f64::NAN) < ((messageHashes.len() as i64) as f64) } {
let mut messageHash: Value = messageHashes.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut parts: Value = split(&messageHash, &Value::Str("::".into()));
let mut symbolsString: Value = parts.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut symbols: Value = split(&symbolsString, &Value::Str(",".into()));
let mut positions: Value = self.filter_by_array(marginModePositions.clone(), Value::Str("symbol".into()), &[symbols, Value::Bool(false)]);
if !(self.is_empty(positions.clone()).as_bool() == Some(true)) {
client.resolve(&[positions, messageHash]);
}
}
}
client.resolve(&[marginModePositions, Value::Str(format!("{}{}", marginMode, Value::Str(":positions".into())).into())]);
}
}
}
/*
* @method
* @name htx#watchBalance
* @description watch balance and get the amount of funds available for trading or funds locked in orders
* @see https://www.htx.com/en-us/opend/newApiPages/?id=7ec52e28-7773-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=28c34995-77ae-11ed-9966-0242ac110003
* @see https://www.htx.com/en-us/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-195a6c94551
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn watch_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 type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchBalance".into()), &[Value::Null, params.clone()]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.handle_sub_type_and_params(Value::Str("watchBalance".into()), &[Value::Null, params.clone(), Value::Str("linear".into())]); subType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut isUnifiedAccount: Value = self.safe_bool2(params.clone(), Value::Str("isUnifiedAccount".into()), Value::Str("unified".into()), &[Value::Bool(false)]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("isUnifiedAccount".into()), Value::Str("unified".into())]), &[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut messageHash: Value = Value::Null;
let mut channel: Value = Value::Null;
let mut marginMode: Value = Value::Null;
let mut linear: bool = subType.as_str() == Some("linear");
let mut swap: bool = type_var.as_str() == Some("swap");
let mut future: bool = type_var.as_str() == Some("future");
let mut isV5Linear: Value = Value::Bool(linear && (swap || future));
if (type_var.as_str() == Some("spot")) {
let mut mode: Value = self.safe_string2(self.options.clone(), Value::Str("watchBalance".into()), Value::Str("mode".into()), &[Value::Str("2".into())]);
mode = self.safe_string_k(params.clone(), "mode", &[mode.clone()]);
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("accounts.update".into()), Value::Str("#".into())).into()), mode).into());
channel = messageHash.clone();
} else if matches!(&isV5Linear, Value::Bool(true)) {
marginMode = self.safe_string_k(params.clone(), "margin", &[Value::Str("cross".into())]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("currency".into()), Value::Str("symbol".into()), Value::Str("margin".into())]), &[]);
channel = Value::Str("account".into());
messageHash = Value::Str("account".into());
} else {
let mut symbol: Value = self.safe_string_k(params.clone(), "symbol", &[]);
let mut currency: Value = self.safe_string_k(params.clone(), "currency", &[]);
let mut market: Value = (if (symbol != Value::Null) { self.market(symbol.clone()) } else { Value::Null });
let mut currencyCode: Value = (if (currency != Value::Null) { self.currency(currency.clone()) } else { Value::Null });
marginMode = self.safe_string_k(params.clone(), "margin", &[Value::Str("cross".into())]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("currency".into()), Value::Str("symbol".into()), Value::Str("margin".into())]), &[]);
let mut prefix: Value = Value::Str("accounts".into());
messageHash = prefix.clone();
if (subType.as_str() == Some("linear")) {
if (isUnifiedAccount.as_bool() == Some(true)) {
// usdt contracts account
prefix = Value::Str("accounts_unify".into());
messageHash = prefix.clone();
channel = Value::Str(format!("{}{}", Value::Str(format!("{}{}", prefix, Value::Str(".".into())).into()), Value::Str("usdt".into())).into());
} else {
// usdt contracts account
prefix = (if (marginMode.as_str() == Some("cross")) { Value::Str(format!("{}{}", prefix, Value::Str("_cross".into())).into()) } else { prefix.clone() });
messageHash = prefix.clone();
if (marginMode.as_str() == Some("isolated")) {
// isolated margin only allows filtering by symbol3
if (symbol != Value::Null) && (market != Value::Null) {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(format!("{}{}", Value::Str(".".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into())).into());
channel = messageHash.clone();
} else {
// subscribe to all
channel = Value::Str(format!("{}{}", Value::Str(format!("{}{}", prefix, Value::Str(".".into())).into()), Value::Str("*".into())).into());
}
} else {
// cross margin
if (currencyCode != Value::Null) {
channel = Value::Str(format!("{}{}", Value::Str(format!("{}{}", prefix, Value::Str(".".into())).into()), currencyCode.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
messageHash = channel.clone();
} else {
// subscribe to all
channel = Value::Str(format!("{}{}", Value::Str(format!("{}{}", prefix, Value::Str(".".into())).into()), Value::Str("*".into())).into());
}
}
}
} else if (type_var.as_str() == Some("future")) {
// inverse futures account
if (currencyCode != Value::Null) {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(format!("{}{}", Value::Str(".".into()), currencyCode.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into())).into());
channel = messageHash.clone();
} else {
// subscribe to all
channel = Value::Str(format!("{}{}", Value::Str(format!("{}{}", prefix, Value::Str(".".into())).into()), Value::Str("*".into())).into());
}
} else {
// inverse swaps account
if (market != Value::Null) {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(format!("{}{}", Value::Str(".".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into())).into());
channel = messageHash.clone();
} else {
// subscribe to all
channel = Value::Str(format!("{}{}", Value::Str(format!("{}{}", prefix, Value::Str(".".into())).into()), Value::Str("*".into())).into());
}
}
}
let mut subscriptionParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var.clone());
m.insert("subType".to_string(), subType.clone());
m.insert("margin".to_string(), marginMode);
m.insert("isV5".to_string(), isV5Linear);
m
});
return self.subscribe_private(channel, messageHash, type_var, subType, &[params, subscriptionParams]).await;
Value::Null
}
pub fn handle_balance(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
// spot
//
// {
// "action": "push",
// "ch": "accounts.update#0",
// "data": {
// "currency": "btc",
// "accountId": 123456,
// "balance": "23.111",
// "available": "2028.699426619837209087",
// "changeType": "transfer",
// "accountType":"trade",
// "seqNum": "86872993928",
// "changeTime": 1568601800000
// }
// }
//
// inverse future
//
// {
// "op":"notify",
// "topic":"accounts.ada",
// "ts":1604388667226,
// "event":"order.match",
// "data":[
// {
// "symbol":"ADA",
// "margin_balance":446.417641681222726716,
// "margin_static":445.554085945257745136,
// "margin_position":11.049723756906077348,
// "margin_frozen":0,
// "margin_available":435.367917924316649368,
// "profit_real":21.627049781983019459,
// "profit_unreal":0.86355573596498158,
// "risk_rate":40.000796572150656768,
// "liquidation_price":0.018674308027108984,
// "withdraw_available":423.927036163274725677,
// "lever_rate":20,
// "adjust_factor":0.4
// }
// ],
// "uid":"123456789"
// }
//
// watchBalance linear v5
//
// {
// "op": "notify",
// "topic": "account",
// "contract_code": "",
// "ts": 1782459963509,
// "uid": "359305390",
// "event": "snapshot",
// "data": {
// "equity": "0",
// "state": "normal",
// "details": [
// {
// "currency": "USDT",
// "equity": "162.331953938562004875",
// "available": "162.331953938562004875",
// "profit_unreal": "0",
// "initial_margin": "0",
// "maintenance_margin": "0",
// "maintenance_margin_rate": "0",
// "initial_margin_rate": "0",
// "voucher": "0",
// "voucher_value": "0",
// "created_time": "1770293270932",
// "updated_time": "1780329743956",
// "isolated_equity": "0",
// "isolated_profit_unreal": "0",
// "withdraw_available": "162.331953938562004875"
// }
// ],
// "initial_margin": "0",
// "maintenance_margin": "0",
// "maintenance_margin_rate": "0",
// "profit_unreal": "0",
// "available_margin": "0",
// "created_time": "1770293268881",
// "updated_time": "1780329743956",
// "version": 5659,
// "voucher_value": "0"
// }
// }
//
// inverse future
//
// {
// "op":"notify",
// "topic":"accounts.ada",
// "ts":1604388667226,
// "event":"order.match",
// "data":[
// {
// "symbol":"ADA",
// "margin_balance":446.417641681222726716,
// "margin_static":445.554085945257745136,
// "margin_position":11.049723756906077348,
// "margin_frozen":0,
// "margin_available":435.367917924316649368,
// "profit_real":21.627049781983019459,
// "profit_unreal":0.86355573596498158,
// "risk_rate":40.000796572150656768,
// "liquidation_price":0.018674308027108984,
// "withdraw_available":423.927036163274725677,
// "lever_rate":20,
// "adjust_factor":0.4
// }
// ],
// "uid":"123456789"
// }
//
let mut channel: Value = (match message.get("ch") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut timestamp: Value = self.safe_integer_k(data.clone(), "changeTime", &[(match message.get("ts") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null })]);
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert("timestamp".into(), timestamp.clone()); }
{ let __be_tmp = self.iso8601(timestamp); if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert("datetime".into(), __be_tmp); } }
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert("info".into(), data.clone()); }
if (channel != Value::Null) {
// spot balance
let mut currencyId: Value = self.safe_string_k(data.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut account: Value = self.account();
add_element_to_object(&mut account, &Value::Str("free".into()), self.safe_string_k(data.clone(), "available", &[]));
add_element_to_object(&mut account, &Value::Str("total".into()), self.safe_string_k(data.clone(), "balance", &[]));
if (code != Value::Null) {
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account.clone()); }
}
{ let __t = self.safe_balance(self.balance.clone()); self.balance = __t; }
client.resolve(&[self.balance.clone(), channel]);
} else {
// contract balance
let mut topic: Value = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (topic == Value::Null) {
return;
}
if (topic.as_str() == Some("account")) {
let mut accountData: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut details: Value = self.safe_list_k(accountData, "details", &[Value::from(vec![])]);
let mut detailsLength: f64 = ((details.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_386: bool = true;
while { if !__for_first_386 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_386 = false; i.as_f64().unwrap_or(f64::NAN) < detailsLength } {
let mut detail: Value = details.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut currencyId: Value = self.safe_string_k(detail.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
if (code == Value::Null) {
continue;
}
let mut account: Value = self.account();
add_element_to_object(&mut account, &Value::Str("free".into()), self.safe_string_k(detail.clone(), "withdraw_available", &[]));
add_element_to_object(&mut account, &Value::Str("total".into()), self.safe_string_k(detail, "equity", &[]));
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account.clone()); }
}
}
{ let __t = self.safe_balance(self.balance.clone()); self.balance = __t; }
client.resolve(&[self.balance.clone(), Value::Str("account".into())]);
return;
}
let mut dataLength: f64 = ((data.len() as i64) as f64);
if (dataLength == 0.0) {
return;
}
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut splitTopic: Value = split(&topic, &Value::Str(".".into()));
let mut messageHash: Value = self.safe_string(splitTopic, Value::Int(0), &[]);
let mut subscription: Value = self.safe_dict2(get_value(&client, &Value::Str("subscriptions".into())), messageHash.clone(), Value::Str(format!("{}{}", messageHash, Value::Str(".*".into())).into()), &[]);
if (subscription == Value::Null) {
// if subscription not found means that we subscribed to a specific currency/symbol
// and we use the first data entry to find it
// Example: topic = 'accounts'
// client.subscription hash = 'accounts.usdt'
// we do 'accounts' + '.' + data[0]]['margin_asset'] to get it
let mut currencyId: Value = self.safe_string2(first.clone(), Value::Str("margin_asset".into()), Value::Str("symbol".into()), &[]);
if (currencyId == Value::Null) {
return;
}
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(format!("{}{}", Value::Str(".".into()), to_lower(¤cyId)).into())).into());
subscription = self.safe_dict(get_value(&client, &Value::Str("subscriptions".into())), messageHash.clone(), &[]);
}
let mut subType: Option<String> = self.safe_string_k(subscription.clone(), "subType", &[]).as_str().map(str::to_owned);
if (topic.as_str() == Some("accounts_unify")) {
// {
// "margin_asset": "USDT",
// "margin_static": 10,
// "cross_margin_static": 10,
// "margin_balance": 10,
// "cross_profit_unreal": 0,
// "margin_frozen": 0,
// "withdraw_available": 10,
// "cross_risk_rate": null,
// "cross_swap": [],
// "cross_future": [],
// "isolated_swap": []
// }
let mut marginAsset: Value = self.safe_string_k(first.clone(), "margin_asset", &[]);
let mut code: Value = self.safe_currency_code(marginAsset, &[]);
let mut marginFrozen: Value = self.safe_string_k(first.clone(), "margin_frozen", &[]);
let mut unifiedAccount: Value = self.account();
add_element_to_object(&mut unifiedAccount, &Value::Str("free".into()), self.safe_string_k(first.clone(), "withdraw_available", &[]));
add_element_to_object(&mut unifiedAccount, &Value::Str("used".into()), marginFrozen);
if (code != Value::Null) {
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), unifiedAccount); }
}
{ let __t = self.safe_balance(self.balance.clone()); self.balance = __t; }
client.resolve(&[self.balance.clone(), Value::Str("accounts_unify".into())]);
} else if (subType.as_deref() == Some("linear")) {
let mut margin: Option<String> = self.safe_string_k(subscription, "margin", &[]).as_str().map(str::to_owned);
if (margin.as_deref() == Some("cross")) {
// the cross account is one shared margin balance, keyed by the settle currency
let mut currencyId: Value = self.safe_string2(first.clone(), Value::Str("margin_asset".into()), Value::Str("margin_account".into()), &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
if (code != Value::Null) {
let mut account: Value = self.account();
add_element_to_object(&mut account, &Value::Str("free".into()), self.safe_string2(first.clone(), Value::Str("withdraw_available".into()), Value::Str("margin_available".into()), &[]));
add_element_to_object(&mut account, &Value::Str("used".into()), self.safe_string_k(first.clone(), "margin_frozen", &[]));
add_element_to_object(&mut account, &Value::Str("total".into()), self.safe_string_k(first, "margin_balance", &[]));
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account.clone()); }
{ let __t = self.safe_balance(self.balance.clone()); self.balance = __t; }
}
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_387: bool = true;
while { if !__for_first_387 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_387 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut isolatedBalance: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut account: Value = self.account();
add_element_to_object(&mut account, &Value::Str("free".into()), self.safe_string_k(isolatedBalance.clone(), "margin_balance", &[Value::Str("margin_available".into())]));
add_element_to_object(&mut account, &Value::Str("used".into()), self.safe_string_k(isolatedBalance.clone(), "margin_frozen", &[]));
let mut currencyId: Value = self.safe_string2(isolatedBalance, Value::Str("margin_asset".into()), Value::Str("symbol".into()), &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
if (code != Value::Null) {
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account.clone()); }
}
{ let __t = self.safe_balance(self.balance.clone()); self.balance = __t; }
}
}
}
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_388: bool = true;
while { if !__for_first_388 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_388 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut balance: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "symbol", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut account: Value = self.account();
add_element_to_object(&mut account, &Value::Str("free".into()), self.safe_string_k(balance.clone(), "margin_available", &[]));
add_element_to_object(&mut account, &Value::Str("used".into()), self.safe_string_k(balance.clone(), "margin_frozen", &[]));
if (code != Value::Null) {
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
{ let __t = self.safe_balance(self.balance.clone()); self.balance = __t; }
}
}
}
client.resolve(&[self.balance.clone(), messageHash]);
}
}
pub fn handle_subscription_status(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "id": 1583414227,
// "status": "ok",
// "subbed": "market.btcusdt.mbp.150",
// "ts": 1583414229143
// }
//
// unsubscribe
// {
// "id": "2",
// "status": "ok",
// "unsubbed": "market.BTC-USDT-251003.detail",
// "ts": 1759329276980
// }
//
let mut id: Value = (match __pro_message.get("id").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (id == Value::Null) {
return;
}
let mut subscriptionsById: Value = self.index_by(get_value(&client, &Value::Str("subscriptions".into())), Value::Str("id".into()));
let mut subscription: Value = self.safe_dict(subscriptionsById, id.clone(), &[]);
if (subscription != Value::Null) {
let mut method: Value = self.safe_value_k(subscription.clone(), "method", &[]);
if (method != Value::Null) {
self.dispatch_ws_handler(&method, &[client.clone(), message.clone(), subscription.clone()]);
}
// clean up
if (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &id)) {
if (id != Value::Null) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &id);
}
}
}
if (matches!(&message, Value::Dict(__d) if __d.contains_key("unsubbed"))) {
self.handle_un_subscription(client, subscription);
}
}
pub fn handle_un_subscription(&mut self, mut client: Value, mut subscription: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &subscription { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
let mut messageHashes: Value = (match __pro_message.get("messageHashes").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
let mut subMessageHashes: Value = (match __pro_message.get("subMessageHashes").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
{
let mut i: Value = Value::Int(0);
let mut __for_first_389: bool = true;
while { if !__for_first_389 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_389 = false; i.as_f64().unwrap_or(f64::NAN) < ((messageHashes.len() as i64) as f64) } {
let mut unsubHash: Value = messageHashes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut subHash: Value = subMessageHashes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
self.clean_unsubscription(client.clone(), subHash, unsubHash, &[]);
}
}
self.clean_cache(subscription);
}
pub fn handle_system_status(&self, mut client: Value, mut message: Value) -> Value {
return message;
Value::Null
}
pub fn handle_subject(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
// spot
// {
// "ch": "market.btcusdt.mbp.150",
// "ts": 1583472025885,
// "tick": {
// "seqNum": 104998984994,
// "prevSeqNum": 104998984977,
// "bids": [
// [9058.27, 0],
// [9058.43, 0],
// [9058.99, 0],
// ],
// "asks": [
// [9084.27, 0.2],
// [9085.69, 0],
// [9085.81, 0],
// ]
// }
// }
// non spot
//
// {
// "ch":"market.BTC220218.depth.size_150.high_freq",
// "tick":{
// "asks":[],
// "bids":[
// [43445.74,1],
// [43444.48,0 ],
// [40593.92,9]
// ],
// "ch":"market.BTC220218.depth.size_150.high_freq",
// "event":"update",
// "id":152727500274,
// "mrid":152727500274,
// "ts":1645023376098,
// "version":37536690
// },
// "ts":1645023376098
// }
//
// spot private trade
//
// {
// "action":"push",
// "ch":"trade.clearing#ltcusdt#1",
// "data":{
// "eventType":"trade",
// "symbol":"ltcusdt",
// // ...
// },
// }
//
// spot order
//
// {
// "action":"push",
// "ch":"orders#btcusdt",
// "data": {
// "orderSide":"buy",
// "lastActTime":1583853365586,
// "clientOrderId":"abc123",
// "orderStatus":"rejected",
// "symbol":"btcusdt",
// "eventType":"trigger",
// "errCode": 2002,
// "errMessage":"invalid.client.order.id (NT)"
// }
// }
//
// contract order
//
// {
// "op":"notify",
// "topic":"orders.ada",
// "ts":1604388667226,
// // ?
// }
//
let mut ch: Value = (match __pro_message.get("ch").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
let mut parts: Value = split(&ch, &Value::Str(".".into()));
let mut type_var: Option<String> = self.safe_string(parts.clone(), Value::Int(0), &[]).as_str().map(str::to_owned);
if (type_var.as_deref() == Some("market")) {
let mut methodName: Value = self.safe_string(parts, Value::Int(2), &[]);
let mut methods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("depth".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("mbp".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("detail".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("bbo".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("ticker".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("trade".to_string(), Value::Str("handle_trades".into()).clone());
m.insert("kline".to_string(), Value::Str("handle_ohlcv".into()).clone());
m
});
let mut method: Value = self.safe_value(methods, methodName, &[]);
if (method != Value::Null) {
self.dispatch_ws_handler(&method, &[client.clone(), message.clone()]);
return;
}
}
// private spot subjects
let mut privateParts: Value = split(&ch, &Value::Str("#".into()));
let mut privateType: Value = self.safe_string(privateParts, Value::Int(0), &[Value::Str("".into())]);
if (privateType.as_str() == Some("trade.clearing")) {
self.handle_my_trade(client.clone(), message.clone(), &[]);
return;
}
if Value::Int(privateType.as_str().and_then(|__s| __s.find("accounts.update")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_balance(client.clone(), message.clone());
return;
}
if (privateType.as_str() == Some("orders")) {
self.handle_order(client.clone(), message.clone());
return;
}
// private contract subjects
let mut op: Option<String> = (match __pro_message.get("op").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (op.as_deref() == Some("notify")) {
let mut topic: Value = (match __pro_message.get("topic").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
if Value::Int(topic.as_str().and_then(|__s| __s.find("orders")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_order(client.clone(), message.clone());
}
if Value::Int(topic.as_str().and_then(|__s| __s.find("trade")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_my_trade(client.clone(), message.clone(), &[]);
}
if Value::Int(topic.as_str().and_then(|__s| __s.find("account")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_balance(client.clone(), message.clone());
}
if Value::Int(topic.as_str().and_then(|__s| __s.find("positions")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_positions(client, message);
}
}
}
pub async fn pong(&mut self, mut client: Value, mut message: Value) -> Value {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut ping: Value = (match message.get("ping") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
if (ping != Value::Null) {
client.send(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pong".to_string(), ping);
m
})]);
return Value::Null;
}
let mut action: Option<String> = (match message.get("action") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (action.as_deref() == Some("ping")) {
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Null });
let mut pingTs: Value = self.safe_integer_k(data, "ts", &[]);
client.send(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Str("pong".into()));
m.insert("data".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ts".to_string(), pingTs.clone());
m
}));
m
})]);
return Value::Null;
}
let mut op: Option<String> = (match message.get("op") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (op.as_deref() == Some("ping")) {
let mut pingTs: Value = (match message.get("ts") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
client.send(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("op".to_string(), Value::Str("pong".into()));
m.insert("ts".to_string(), pingTs);
m
})]);
}
#[allow(unreachable_code)] { Value::Null }})).await;
match _try_result { Ok(__try_ok) => { if !matches!(__try_ok, Value::Null) { return __try_ok; } return Value::Null; } Err(_try_err) => { let e: Value = panic_to_value(_try_err);
let mut error = Value::from(crate::exchange_errors::network_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" pong failed ".into())).into()), self.exception_message(e, &[]))));
client.reset(error);
} }
Value::Null
}
pub fn handle_ping(&mut self, mut client: Value, mut message: Value) {
self.spawn(&[Value::Str("pong".into()).clone(), client, message]);
}
pub fn handle_authenticate(&self, mut client: Value, mut message: Value) {
//
// spot
//
// {
// "action": "req",
// "code": 200,
// "ch": "auth",
// "data": {}
// }
//
// non spot
//
// {
// "op": "auth",
// "type": "api",
// "err-code": 0,
// "ts": 1645200307319,
// "data": { "user-id": "35930539" }
// }
//
let mut promise: Value = get_value(&client, &Value::Str("futures".into())).as_map().and_then(|__m| __m.get("auth")).cloned().unwrap_or(Value::Null);
promise.resolve(&[message]);
}
pub fn handle_error_message(&self, mut client: Value, mut message: Value) -> Value {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "action": "sub",
// "code": 2002,
// "ch": "accounts.update#2",
// "message": "invalid.auth.state"
// }
//
// {
// "ts": 1586323747018,
// "status": "error",
// 'err-code': "bad-request",
// 'err-msg': "invalid mbp.150.symbol linkusdt",
// "id": "2"
// }
//
// {
// "op": "sub",
// "cid": "1",
// "topic": "accounts_unify.USDT",
// "err-code": 4007,
// 'err-msg': "Non - single account user is not available, please check through the cross and isolated account asset interface",
// "ts": 1698419490189
// }
// {
// "action":"req",
// "code":2002,
// "ch":"auth",
// "message":"auth.fail"
// }
//
let mut status: Option<String> = (match __pro_message.get("status").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (status.as_deref() == Some("error")) {
let mut id: Value = (match __pro_message.get("id").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (id == Value::Null) {
return Value::Bool(false);
}
let mut subscriptionsById: Value = self.index_by(get_value(&client, &Value::Str("subscriptions".into())), Value::Str("id".into()));
let mut subscription: Value = self.safe_dict(subscriptionsById, id.clone(), &[]);
if (subscription != Value::Null) {
let mut errorCode: Value = (match __pro_message.get("err-code").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let _try_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
self.throw_exactly_matched_exception(crate::value::get_value_k(&self.exceptions.as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "exact"), errorCode.clone(), json_stringify(&message));
panic!("{}", crate::exchange_errors::exchange_error(json_stringify(&message)));
#[allow(unreachable_code)] { Value::Null }}));
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
let mut messageHash: Value = self.safe_string_k(subscription, "messageHash", &[]);
client.reject(&[e.clone(), messageHash.clone()]);
client.reject(&[e.clone(), id.clone()]);
if (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &id)) {
if (id != Value::Null) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &id);
}
}
// the subscription is keyed by the messageHash, not by the id -
// without removing it a repeated watch call attaches to a future
// that nothing will resolve instead of resubscribing, see
// https://github.com/ccxt/ccxt/issues/10280
if (messageHash != Value::Null) && (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash)) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
}
}
}
return Value::Bool(false);
}
let mut code: Value = self.safe_string2(message.clone(), Value::Str("code".into()), Value::Str("err-code".into()), &[]);
if (code != Value::Null) && ((code.as_str() != Some("200")) && (code.as_str() != Some("0"))) {
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), json_stringify(&message)).into());
let _try_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
self.throw_exactly_matched_exception(crate::value::get_value_k(&self.exceptions.as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "exact"), code.clone(), feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
#[allow(unreachable_code)] { Value::Null }}));
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
if is_instance(&e, &Value::Str("AuthenticationError".into())) {
client.reject(&[e.clone(), Value::Str("auth".into())]);
let mut method: Value = Value::Str("auth".into());
if (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &method)) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &method);
}
return Value::Bool(false);
} else {
client.reject(&[e]);
}
}
}
return Value::Bool(true);
Value::Null
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
if (self.handle_error_message(client.clone(), message.clone()).as_bool() == Some(true)) {
//
// {"id":1583414227,"status":"ok","subbed":"market.btcusdt.mbp.150","ts":1583414229143}
//
// first ping format
//
// {"ping": 1645106821667 }
//
// second ping format
//
// {"action":"ping","data":{"ts":1645106821667}}
//
// third pong format
//
//
// auth spot
//
// {
// "action": "req",
// "code": 200,
// "ch": "auth",
// "data": {}
// }
//
// auth non spot
//
// {
// "op": "auth",
// "type": "api",
// "err-code": 0,
// "ts": 1645200307319,
// "data": { "user-id": "35930539" }
// }
//
// trade
//
// {
// "action":"push",
// "ch":"trade.clearing#ltcusdt#1",
// "data":{
// "eventType":"trade",
// // ?
// }
// }
//
if (matches!(&message, Value::Dict(__d) if __d.contains_key("id"))) {
self.handle_subscription_status(client.clone(), message.clone());
return;
}
if (matches!(&message, Value::Dict(__d) if __d.contains_key("action"))) {
let mut action: Option<String> = (match __pro_message.get("action").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (action.as_deref() == Some("ping")) {
self.handle_ping(client.clone(), message.clone());
return;
}
if (action.as_deref() == Some("sub")) {
self.handle_subscription_status(client.clone(), message.clone());
return;
}
}
if (matches!(&message, Value::Dict(__d) if __d.contains_key("ch"))) {
if (message.as_map().and_then(|__m| __m.get("ch")).cloned().unwrap_or(Value::Null).as_str() == Some("auth")) {
self.handle_authenticate(client.clone(), message.clone());
return;
} else {
// route by channel aka topic aka subject
self.handle_subject(client.clone(), message.clone());
return;
}
}
if (matches!(&message, Value::Dict(__d) if __d.contains_key("op"))) {
let mut op: Option<String> = (match __pro_message.get("op").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (op.as_deref() == Some("ping")) {
self.handle_ping(client.clone(), message.clone());
return;
}
if (op.as_deref() == Some("auth")) {
self.handle_authenticate(client.clone(), message.clone());
return;
}
if (op.as_deref() == Some("sub")) {
self.handle_subscription_status(client.clone(), message.clone());
return;
}
if (op.as_deref() == Some("notify")) {
self.handle_subject(client.clone(), message.clone());
return;
}
}
if (matches!(&message, Value::Dict(__d) if __d.contains_key("ping"))) {
self.handle_ping(client, message.clone());
}
}
}
pub fn handle_my_trade(&mut self, mut client: Value, mut message: Value, optional_args: &[Value]) {
let mut extendParams = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// spot
//
// {
// "action":"push",
// "ch":"trade.clearing#ltcusdt#1",
// "data":{
// "eventType":"trade",
// "symbol":"ltcusdt",
// "orderId":"478862728954426",
// "orderSide":"buy",
// "orderType":"buy-market",
// "accountId":44234548,
// "source":"spot-web",
// "orderValue":"5.01724137",
// "orderCreateTime":1645124660365,
// "orderStatus":"filled",
// "feeCurrency":"ltc",
// "tradePrice":"118.89",
// "tradeVolume":"0.042200701236437042",
// "aggressor":true,
// "tradeId":101539740584,
// "tradeTime":1645124660368,
// "transactFee":"0.000041778694224073",
// "feeDeduct":"0",
// "feeDeductType":""
// }
// }
//
// contract
//
// {
// "symbol": "ADA/USDT:USDT"
// "ch": "orders_cross.ada-usdt"
// "trades": [
// {
// "trade_fee":-0.022099447513812154,
// "fee_asset":"ADA",
// "trade_id":113913755890,
// "id":"113913755890-773207641127878656-1",
// "trade_volume":1,
// "trade_price":0.0905,
// "trade_turnover":10,
// "created_at":1604388667194,
// "profit":0,
// "real_profit": 0,
// "role":"maker"
// }
// ],
// }
//
// linear v5 watchMyTrades
//
// {
// "op": "notify",
// "topic": "trade",
// "contract_code": "BTC-USDT",
// "ts": 1782367694387,
// "uid": "359305390",
// "data": [
// {
// "direction": "buy",
// "id": "100121555172810-1519705786942156810-1",
// "contract_code": "BTC-USDT",
// "contract_type": "swap",
// "order_id": "1519705786942156810",
// "trade_id": "155233460",
// "position_side": "both",
// "trade_volume": "1",
// "trade_price": "61629",
// "trade_turnover": "61.629",
// "role": "taker",
// "client_order_id": "1519705786942156810",
// "created_time": "1782367694375",
// "updated_time": "1782367694385"
// }
// ]
// }
//
if (self.myTrades.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCacheBySymbolById::new(limit);
}
let mut cachedTrades: Value = self.myTrades.clone();
let mut messageHash: Value = self.safe_string2(message.clone(), Value::Str("ch".into()), Value::Str("topic".into()), &[]);
if (messageHash != Value::Null) {
let mut data: Value = (match __pro_message.get("data").cloned() { Some(Value::Str(__s)) if __s.is_empty() => Value::Null, Some(__v) => __v, None => Value::Null });
if (data != Value::Null) {
let mut contractCode: Value = (match __pro_message.get("contract_code").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut market: Value = (if (contractCode != Value::Null) { self.safe_market(&[contractCode.clone()]) } else { Value::Null });
if (matches!(&data, Value::Arr(_))) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_390: bool = true;
while { if !__for_first_390 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_390 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut parsed: Value = self.parse_ws_trade(data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[market.clone()]);
let mut symbol: Value = self.safe_string_k(parsed.clone(), "symbol", &[]);
if (symbol != Value::Null) {
cachedTrades.append(parsed.clone());
}
}
}
} else {
let mut parsed: Value = self.parse_ws_trade(data, &[market.clone()]);
let mut symbol: Value = self.safe_string_k(parsed.clone(), "symbol", &[]);
if (symbol != Value::Null) {
cachedTrades.append(parsed);
}
}
client.resolve(&[self.myTrades.clone(), messageHash.clone()]);
if (messageHash.as_str() == Some("trade")) && (contractCode != Value::Null) {
let mut specificMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str(".".into())).into()), to_lower(&contractCode)).into());
client.resolve(&[self.myTrades.clone(), specificMessageHash]);
}
} else {
// this trades object is artificially created
// in handleOrder
let mut rawTrades: Value = (match __pro_message.get("trades").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
let mut marketId: Value = self.safe_string_k(message.clone(), "symbol", &[]);
let mut market: Value = self.market(marketId);
{
let mut i: Value = Value::Int(0);
let mut __for_first_391: bool = true;
while { if !__for_first_391 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_391 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawTrades.len() as i64) as f64) } {
let mut trade: Value = rawTrades.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut parsedTrade: Value = self.parse_trade(trade, &[market.clone()]);
// add extra params (side, type, ...) coming from the order
parsedTrade = self.extend(parsedTrade.clone(), &[extendParams.clone()]);
cachedTrades.append(parsedTrade);
}
}
// messageHash here is the orders one, so
// we have to recreate the trades messageHash = orderMessageHash + ':' + 'trade'
let mut tradesHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str(":".into())).into()), Value::Str("trade".into())).into());
client.resolve(&[self.myTrades.clone(), tradesHash]);
// when we make an global order sub we have to send the channel like this
// ch = orders_cross.* and we store messageHash = 'orders_cross'
// however it is returned with the specific order update symbol: ch = orders_cross.btc-usd
// since this is a global sub, our messageHash does not specify any symbol (ex: orders_cross:trade)
// so we must remove it
let mut genericOrderHash: Value = replace_str(&messageHash, &Value::Str(format!("{}{}", Value::Str(".".into()), market.as_map().and_then(|__m| __m.get("lowercaseId")).cloned().unwrap_or(Value::Null)).into()), &Value::Str("".into()));
let mut lowerCaseBaseId: Value = self.safe_string_lower_k(market, "baseId", &[]);
genericOrderHash = replace_str(&genericOrderHash, &Value::Str(format!("{}{}", Value::Str(".".into()), lowerCaseBaseId).into()), &Value::Str("".into()));
let mut genericTradesHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", genericOrderHash, Value::Str(":".into())).into()), Value::Str("trade".into())).into());
client.resolve(&[self.myTrades.clone(), genericTradesHash]);
}
}
}
pub fn parse_ws_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
// spot private
//
// {
// "eventType":"trade",
// "symbol":"ltcusdt",
// "orderId":"478862728954426",
// "orderSide":"buy",
// "orderType":"buy-market",
// "accountId":44234548,
// "source":"spot-web",
// "orderValue":"5.01724137",
// "orderCreateTime":1645124660365,
// "orderStatus":"filled",
// "feeCurrency":"ltc",
// "tradePrice":"118.89",
// "tradeVolume":"0.042200701236437042",
// "aggressor":true,
// "tradeId":101539740584,
// "tradeTime":1645124660368,
// "transactFee":"0.000041778694224073",
// "feeDeduct":"0",
// "feeDeductType":""
// }
//
// linear v5 watchMyTrades
//
// {
// "direction": "buy",
// "id": "100121555172810-1519705786942156810-1",
// "contract_code": "BTC-USDT",
// "contract_type": "swap",
// "order_id": "1519705786942156810",
// "trade_id": "155233460",
// "position_side": "both",
// "trade_volume": "1",
// "trade_price": "61629",
// "trade_turnover": "61.629",
// "role": "taker",
// "client_order_id": "1519705786942156810",
// "created_time": "1782367694375",
// "updated_time": "1782367694385"
// }
//
let mut marketId: Value = self.safe_string2(trade.clone(), Value::Str("symbol".into()), Value::Str("contract_code".into()), &[]);
market = self.safe_market(&[marketId, market.clone()]);
let mut symbol: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut side: Value = self.safe_string_n(trade.clone(), Value::from(vec![Value::Str("side".into()), Value::Str("orderSide".into()), Value::Str("direction".into())]), &[]);
let mut tradeId: Value = self.safe_string_n(trade.clone(), Value::from(vec![Value::Str("tradeId".into()), Value::Str("trade_id".into()), Value::Str("id".into())]), &[]);
let mut price: Value = self.safe_string2(trade.clone(), Value::Str("tradePrice".into()), Value::Str("trade_price".into()), &[]);
let mut amount: Value = self.safe_string2(trade.clone(), Value::Str("tradeVolume".into()), Value::Str("trade_volume".into()), &[]);
let mut order: Value = self.safe_string2(trade.clone(), Value::Str("orderId".into()), Value::Str("order_id".into()), &[]);
let mut timestamp: Value = self.safe_integer_n(trade.clone(), Value::from(vec![Value::Str("tradeTime".into()), Value::Str("updated_time".into()), Value::Str("created_time".into())]), &[]);
let mut orderType: Value = self.safe_string2(trade.clone(), Value::Str("orderType".into()), Value::Str("type".into()), &[]);
let mut aggressor: Value = self.safe_bool_k(trade.clone(), "aggressor", &[]);
let mut takerOrMaker: Value = Value::Null;
if (aggressor != Value::Null) {
takerOrMaker = (if (aggressor.as_bool() == Some(true)) { Value::Str("taker".into()) } else { Value::Str("maker".into()) });
} else {
takerOrMaker = self.safe_string_lower_k(trade.clone(), "role", &[]);
}
let mut type_var: Value = Value::Null;
let mut orderTypeParts: Value = Value::from(vec![]);
if (orderType != Value::Null) {
orderTypeParts = split(&orderType, &Value::Str("-".into()));
type_var = self.safe_string(orderTypeParts, Value::Int(1), &[orderType]);
}
let mut fee: Value = Value::Null;
let mut feeCurrency: Value = self.safe_currency_code(self.safe_string_n(trade.clone(), Value::from(vec![Value::Str("feeCurrency".into()), Value::Str("fee_currency".into()), Value::Str("fee_asset".into())]), &[]), &[]);
if (feeCurrency != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.safe_string_n(trade.clone(), Value::from(vec![Value::Str("transactFee".into()), Value::Str("fee".into()), Value::Str("trade_fee".into())]), &[]));
m.insert("currency".to_string(), feeCurrency);
m
});
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), symbol);
m.insert("id".to_string(), tradeId);
m.insert("order".to_string(), order);
m.insert("type".to_string(), type_var);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
}), &[market]);
Value::Null
}
pub fn get_url_by_market_type(&self, mut type_var: Value, optional_args: &[Value]) -> Option<String> {
let mut isLinear = get_arg(optional_args, 0, Value::Bool(true));
let mut isPrivate = get_arg(optional_args, 1, Value::Bool(false));
let mut isFeed = get_arg(optional_args, 2, Value::Bool(false));
let mut isV5 = get_arg(optional_args, 3, Value::Bool(false));
let mut api: Value = self.safe_string_k(self.options.clone(), "api", &[Value::Str("api".into())]);
let mut hostname: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hostname".to_string(), self.hostname.clone());
m
});
let mut hostnameURL: Value = Value::Null;
let mut url: Value = Value::Null;
if (type_var.as_str() == Some("spot")) {
if is_true(&isPrivate) {
hostnameURL = crate::value::get_value_k(&crate::value::get_value_k(&get_value(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), &api), "spot"), "private");
} else {
if is_true(&isFeed) {
hostnameURL = crate::value::get_value_k(&crate::value::get_value_k(&get_value(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), &api), "spot"), "feed");
} else {
hostnameURL = crate::value::get_value_k(&crate::value::get_value_k(&get_value(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), &api), "spot"), "public");
}
}
url = self.implode_params(hostnameURL, hostname);
} else {
let mut baseUrl: Value = get_value(&get_value(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), &api), &type_var);
let mut subTypeUrl: Value = (if is_true(&isLinear) { crate::value::get_value_k(&baseUrl, "linear") } else { crate::value::get_value_k(&baseUrl, "inverse") });
if is_true(&isPrivate) {
if is_true(&isV5) && is_true(&isLinear) {
url = self.safe_string_k(subTypeUrl.clone(), "privateV5", &[crate::value::get_value_k(&subTypeUrl, "private")]);
} else {
url = crate::value::get_value_k(&subTypeUrl, "private");
}
} else {
url = crate::value::get_value_k(&subTypeUrl, "public");
}
}
return url.as_str().map(str::to_owned);
}
pub async fn subscribe_public(&mut self, mut url: Value, mut symbol: Value, mut messageHash: Value, optional_args: &[Value]) -> Value {
let mut method = 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 requestId: Value = self.request_id();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sub".to_string(), messageHash.clone());
m.insert("id".to_string(), requestId.clone());
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId);
m.insert("messageHash".to_string(), messageHash.clone());
m.insert("symbol".to_string(), symbol);
m.insert("params".to_string(), params.clone());
m
});
if (method != Value::Null) {
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("method".into(), method); }
}
let __ws_arg_0 = self.extend(request, &[params]);
return self.watch(url, messageHash.clone(), &[__ws_arg_0, messageHash.clone(), subscription]).await;
Value::Null
}
pub async fn unsubscribe_public(&mut self, mut market: Value, mut subMessageHash: Value, mut topic: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut requestId: Value = self.request_id();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("unsub".to_string(), subMessageHash.clone());
m.insert("id".to_string(), requestId.clone());
m
});
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe::".into()), subMessageHash).into());
let mut isFeed: Value = (Value::Bool(topic.as_str() == Some("orderbook")));
if (market == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" unsubscribePublic() market is required".into()))));
}
let mut url: Value = self.get_url_by_market_type(market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null), &[market.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null), Value::Bool(false), isFeed]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("id".to_string(), requestId);
m.insert("subMessageHashes".to_string(), Value::from(vec![subMessageHash]));
m.insert("messageHashes".to_string(), Value::from(vec![messageHash.clone()]));
m.insert("symbols".to_string(), Value::from(vec![market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)]));
m.insert("topic".to_string(), topic);
m
});
let mut symbolsAndTimeframes: Value = self.safe_list_k(params.clone(), "symbolsAndTimeframes", &[]);
if (symbolsAndTimeframes != Value::Null) {
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("symbolsAndTimeframes".into(), symbolsAndTimeframes); }
params = self.omit(params.clone(), Value::Str("symbolsAndTimeframes".into()), &[]);
}
let __ws_arg_1 = self.extend(request, &[params]);
return self.watch(url, messageHash.clone(), &[__ws_arg_1, messageHash.clone(), subscription]).await;
Value::Null
}
pub async fn subscribe_private(&mut self, mut channel: Value, mut messageHash: Value, mut type_var: Value, mut subtype: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut subscriptionParams = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut requestId: Value = self.request_id();
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("messageHash".to_string(), messageHash.clone());
m.insert("params".to_string(), params.clone());
m
});
let mut extendedSubsription: Value = self.extend(subscription, &[subscriptionParams.clone()]);
let mut request: Value = Value::Null;
if (type_var.as_str() == Some("spot")) {
request = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Str("sub".into()));
m.insert("ch".to_string(), channel.clone());
m
});
} else {
request = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("op".to_string(), Value::Str("sub".into()));
m.insert("topic".to_string(), channel.clone());
m.insert("cid".to_string(), requestId);
m
});
}
let mut isLinear: Value = Value::Bool(subtype.as_str() == Some("linear"));
let mut isV5: Value = self.safe_bool_k(subscriptionParams, "isV5", &[Value::Bool(false)]);
let mut url: Value = self.get_url_by_market_type(type_var.clone(), &[isLinear, Value::Bool(true), Value::Bool(false), isV5]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut hostname: Value = (if (type_var.as_str() == Some("spot")) { crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("hostnames")).cloned().unwrap_or(Value::Null), "spot") } else { crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("hostnames")).cloned().unwrap_or(Value::Null), "contract") });
let mut authParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var);
m.insert("url".to_string(), url.clone());
m.insert("hostname".to_string(), hostname);
m
});
self.authenticate(&[authParams]).await;
let __ws_arg_2 = self.extend(request, &[params]);
return self.watch(url, messageHash, &[__ws_arg_2, channel, extendedSubsription]).await;
Value::Null
}
pub async fn authenticate(&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 url: Value = self.safe_string_k(params.clone(), "url", &[]);
let mut hostname: Value = self.safe_string_k(params.clone(), "hostname", &[]);
let mut type_var: Option<String> = self.safe_string_k(params.clone(), "type", &[]).as_str().map(str::to_owned);
if (url == Value::Null) || (hostname == Value::Null) || (type_var.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" authenticate requires a url, hostname and type argument".into()))));
}
self.check_required_credentials(&[]);
let mut messageHash: Value = Value::Str("auth".into());
let mut relativePath: Value = replace_str(&url, &Value::Str(format!("{}{}", Value::Str("wss://".into()), hostname).into()), &Value::Str("".into()));
let mut client: Value = self.client(&[url.clone()]);
let mut future: Value = client.reusable_future(messageHash.clone());
let mut authenticated: Value = self.safe_value(get_value(&client, &Value::Str("subscriptions".into())), messageHash.clone(), &[]);
if (authenticated == Value::Null) {
let mut timestamp: Value = self.ymdhms(self.milliseconds(), &[Value::Str("T".into())]);
let mut signatureParams: Value = Value::Null;
if (type_var.as_deref() == Some("spot")) {
signatureParams = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accessKey".to_string(), self.apiKey.clone());
m.insert("signatureMethod".to_string(), Value::Str("HmacSHA256".into()));
m.insert("signatureVersion".to_string(), Value::Str("2.1".into()));
m.insert("timestamp".to_string(), timestamp.clone());
m
});
} else {
signatureParams = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("AccessKeyId".to_string(), self.apiKey.clone());
m.insert("SignatureMethod".to_string(), Value::Str("HmacSHA256".into()));
m.insert("SignatureVersion".to_string(), Value::Str("2".into()));
m.insert("Timestamp".to_string(), timestamp.clone());
m
});
}
signatureParams = self.keysort(signatureParams.clone(), &[]);
let mut auth: Value = self.urlencode(signatureParams, &[Value::Bool(true)]); // true required in go
let mut payload: Value = join(&Value::from(vec![Value::Str("GET".into()), hostname, relativePath, auth]), &Value::Str("\n".into())); // eslint-disable-line quotes
let mut signature: Value = self.hmac(self.encode(payload), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[Value::Str("base64".into())]);
let mut request: Value = Value::Null;
if (type_var.as_deref() == Some("spot")) {
let mut newParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("authType".to_string(), Value::Str("api".into()));
m.insert("accessKey".to_string(), self.apiKey.clone());
m.insert("signatureMethod".to_string(), Value::Str("HmacSHA256".into()));
m.insert("signatureVersion".to_string(), Value::Str("2.1".into()));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("signature".to_string(), signature.clone());
m
});
request = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("params".to_string(), newParams);
m.insert("action".to_string(), Value::Str("req".into()));
m.insert("ch".to_string(), Value::Str("auth".into()));
m
});
} else {
request = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("op".to_string(), Value::Str("auth".into()));
m.insert("type".to_string(), Value::Str("api".into()));
m.insert("AccessKeyId".to_string(), self.apiKey.clone());
m.insert("SignatureMethod".to_string(), Value::Str("HmacSHA256".into()));
m.insert("SignatureVersion".to_string(), Value::Str("2".into()));
m.insert("Timestamp".to_string(), timestamp);
m.insert("Signature".to_string(), signature);
m
});
}
let mut requestId: Value = self.request_id();
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId);
m.insert("messageHash".to_string(), messageHash.clone());
m.insert("params".to_string(), params);
m
});
self.watch(url, messageHash.clone(), &[request, messageHash.clone(), subscription]).await;
}
return crate::exchange_stubs::ws_await_flight(&future).await;
Value::Null
}
}