// 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 XtCore {
pub parent: crate::exchanges::xt::XtCore,
}
impl XtCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::xt::XtCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = XtCore::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 XtCore {
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 XtCore {
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 {
"get_cache_index" => self.get_cache_index(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"get_listen_key" => self.get_listen_key(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"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)).await; crate::Value::Null },
"handle_funding_rate" => self.handle_funding_rate(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_ohlcv" => self.handle_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(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)),
"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)),
"handle_ticker" => self.handle_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_tickers" => self.handle_tickers(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_trade" => self.handle_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"load_positions_snapshot" => self.load_positions_snapshot(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"parse_ws_order" => self.parse_ws_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_order_trade" => self.parse_ws_order_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"ping" => self.ping(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"subscribe" => self.subscribe(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_subscribe" => self.un_subscribe(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), &args[5.min(args.len())..]).await,
"un_watch_funding_rate" => self.un_watch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.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_tickers" => self.un_watch_tickers(&args[..]).await,
"un_watch_trades" => self.un_watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_balance" => self.watch_balance(&args[..]).await,
"watch_funding_rate" => self.watch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_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_tickers" => self.watch_tickers(&args[..]).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 XtCore {
/// 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 {
"get_cache_index" => self.get_cache_index(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"get_listen_key" => { crate::exchange_stubs::enqueue_spawn("get_listen_key", args.to_vec()); 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_error_message" => { crate::exchange_stubs::enqueue_spawn("handle_error_message", args.to_vec()); crate::Value::Null },
"handle_funding_rate" => self.handle_funding_rate(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_trades" => { self.handle_my_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); 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)),
"handle_order" => self.handle_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(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_position" => { self.handle_position(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)),
"handle_ticker" => self.handle_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_tickers" => self.handle_tickers(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_trade" => self.handle_trade(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 },
"load_positions_snapshot" => { crate::exchange_stubs::enqueue_spawn("load_positions_snapshot", args.to_vec()); crate::Value::Null },
"parse_ws_order" => self.parse_ws_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_order_trade" => self.parse_ws_order_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"ping" => self.ping(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"set_positions_cache" => { self.set_positions_cache(args.get(0).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"subscribe" => { crate::exchange_stubs::enqueue_spawn("subscribe", args.to_vec()); crate::Value::Null },
"un_subscribe" => { crate::exchange_stubs::enqueue_spawn("un_subscribe", args.to_vec()); crate::Value::Null },
"un_watch_funding_rate" => { crate::exchange_stubs::enqueue_spawn("un_watch_funding_rate", 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_tickers" => { crate::exchange_stubs::enqueue_spawn("un_watch_tickers", args.to_vec()); crate::Value::Null },
"un_watch_trades" => { crate::exchange_stubs::enqueue_spawn("un_watch_trades", args.to_vec()); crate::Value::Null },
"watch_balance" => { crate::exchange_stubs::enqueue_spawn("watch_balance", args.to_vec()); crate::Value::Null },
"watch_funding_rate" => { crate::exchange_stubs::enqueue_spawn("watch_funding_rate", 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_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_tickers" => { crate::exchange_stubs::enqueue_spawn("watch_tickers", 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 XtCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for XtCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl XtCore {
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("watchOHLCV".to_string(), Value::Bool(true));
m.insert("unWatchOHLCV".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("unWatchOrderBook".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("unWatchTicker".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(true));
m.insert("unWatchTickers".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m.insert("unWatchTrades".to_string(), Value::Bool(true));
m.insert("watchTradesForSymbols".to_string(), Value::Bool(false));
m.insert("watchBalance".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchPositions".to_string(), Value::Bool(true));
m.insert("watchFundingRate".to_string(), Value::Bool(true));
m.insert("unWatchFundingRate".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("spot".to_string(), Value::Str("wss://stream.xt.com".into()));
m.insert("contract".to_string(), Value::Str("wss://fstream.xt.com/ws".into()));
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("ordersLimit".to_string(), Value::Int(1000));
m.insert("OHLCVLimit".to_string(), Value::Int(1000));
m.insert("watchTicker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("ticker".into()));
m
}));
m.insert("watchTickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("tickers".into()));
m
}));
m.insert("watchPositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("swap".into()));
m.insert("fetchPositionsSnapshot".to_string(), Value::Bool(true));
m.insert("awaitPositionsSnapshot".to_string(), Value::Bool(true));
m
}));
m
}));
m.insert("streaming".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("keepAlive".to_string(), Value::Int(20000));
m.insert("ping".to_string(), Value::Str("ping".into()).clone());
m
}));
m.insert("token".to_string(), Value::Null);
m
})]);
Value::Null
}
/*
* @ignore
* @method
* @description required for private endpoints
* @param {string} isContract true for contract trades
* @see https://doc.xt.com/docs/spot/WebSocket%20Private/GetWsToken
* @see https://doc.xt.com/docs/futures/UserWebsocket/General_WSS_information
* @returns {string} listen key / access token
*/
pub async fn get_listen_key(&mut self, mut isContract: Value) -> Value {
self.check_required_credentials(&[]);
let mut tradeType: Value = (if is_true(&isContract) { Value::Str("contract".into()) } else { Value::Str("spot".into()) });
let mut url: 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), &tradeType);
if !is_true(&isContract) {
url = add(&url, &Value::Str("/private".into()));
}
let mut client: Value = self.client(&[url]);
let mut token: Option<String> = self.safe_string(get_value(&client, &Value::Str("subscriptions".into())), Value::Str("token".into()), &[]).as_str().map(str::to_owned);
if (token.is_none()) {
// single-flight leader election, see https://github.com/ccxt/ccxt/issues/29393:
// concurrent callers each minted their own token, last write won, and the losers
// carried an orphaned token into name + '@' + listenKey so their streams went dead
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("authenticate:".into()), tradeType).into());
if (in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
// a flight is already in progress - wake when the leader
// settles it: the token is then in the bucket
crate::exchange_stubs::ws_await_flight(&client.future(&[messageHash.clone()])).await;
return get_value(&client, &Value::Str("subscriptions".into())).as_map().and_then(|__m| __m.get("token")).cloned().unwrap_or(Value::Null);
}
// client.futures is the same registry Exchange.watch () dedupes on, so registering
// the flight here, before any suspension point, makes concurrent callers wait
let mut future: Value = client.reusable_future(messageHash.clone());
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut listenKey: Value = Value::Null;
if is_true(&isContract) {
let mut response: Value = self.parent.private_linear_get_future_user_v1_user_listen_key(&[]).await;
//
// {
// returnCode: '0',
// msgInfo: 'success',
// error: null,
// result: '3BC1D71D6CF96DA3458FC35B05B633351684511731128'
// }
//
listenKey = self.safe_string_k(response.clone(), "result", &[]);
} else {
let mut response: Value = self.parent.private_spot_post_ws_token(&[]).await;
//
// {
// "rc": 0,
// "mc": "SUCCESS",
// "ma": [],
// "result": {
// "token": "eyJhbqGciOiJSUzI1NiJ9.eyJhY2NvdW50SWQiOiIyMTQ2Mjg1MzIyNTU5Iiwic3ViIjoibGh4dDRfMDAwMUBzbmFwbWFpbC5jYyIsInNjb3BlIjoiYXV0aCIsImlzcyI6Inh0LmNvbSIsImxhc3RBdXRoVGltZSI6MTY2MzgxMzY5MDk1NSwic2lnblR5cGUiOiJBSyIsInVzZXJOYW1lIjoibGh4dDRfMDAwMUBzbmFwbWFpbC5jYyIsImV4cCI6MTY2NjQwNTY5MCwiZGV2aWNlIjoidW5rbm93biIsInVzZXJJZCI6MjE0NjI4NTMyMjU1OX0.h3zJlJBQrK2x1HvUxsKivnn6PlSrSDXXXJ7WqHAYSrN2CG5XPTKc4zKnTVoYFbg6fTS0u1fT8wH7wXqcLWXX71vm0YuP8PCvdPAkUIq4-HyzltbPr5uDYd0UByx0FPQtq1exvsQGe7evXQuDXx3SEJXxEqUbq_DNlXPTq_JyScI",
// "refreshToken": "eyJhbGciOiqJSUzI1NiJ9.eyJhY2NvdW50SWQiOiIyMTQ2Mjg1MzIyNTU5Iiwic3ViIjoibGh4dDRfMDAwMUBzbmFwbWFpbC5jYyIsInNjb3BlIjoicmVmcmVzaCIsImlzcyI6Inh0LmNvbSIsImxhc3RBdXRoVGltZSI6MTY2MzgxMzY5MDk1NSwic2lnblR5cGUiOiJBSyIsInVzZXJOYW1lIjoibGh4dDRfMDAwMUBzbmFwbWFpbC5jYyIsImV4cCI6MTY2NjQwNTY5MCwiZGV2aWNlIjoidW5rbm93biIsInVzZXJJZCI6MjE0NjI4NTMyMjU1OX0.Fs3YVm5YrEOzzYOSQYETSmt9iwxUHBovh2u73liv1hLUec683WGfktA_s28gMk4NCpZKFeQWFii623FvdfNoteXR0v1yZ2519uNvNndtuZICDdv3BQ4wzW1wIHZa1skxFfqvsDnGdXpjqu9UFSbtHwxprxeYfnxChNk4ssei430"
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[]);
listenKey = self.safe_string_k(result, "accessToken", &[]);
}
if (listenKey == Value::Null) {
panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", self.id.clone(), Value::Str(" getListenKey() received an empty listen key".into()))));
}
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &Value::Str("token".into()), listenKey.clone());
client.resolve(&[listenKey, messageHash.clone()]);
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
// hand the failure to every waiter so the next caller re-leads instead of
// deadlocking on a dead flight. no throw here: the trailing future rethrows
// to this caller and keeps a waiterless rejection from crashing the process
client.reject(&[e, messageHash]);
}
crate::exchange_stubs::ws_await_flight(&future).await;
}
return get_value(&client, &Value::Str("subscriptions".into())).as_map().and_then(|__m| __m.get("token")).cloned().unwrap_or(Value::Null);
Value::Null
}
pub fn get_cache_index(&self, mut orderbook: Value, mut cache: Value) -> Value {
// return the first index of the cache that can be applied to the orderbook or -1 if not possible
let mut nonce: Value = self.safe_integer_k(orderbook, "nonce", &[]);
let mut firstDelta: Value = self.safe_dict(cache.clone(), Value::Int(0), &[]);
let mut firstDeltaNonce: Value = self.safe_integer2(firstDelta, Value::Str("i".into()), Value::Str("u".into()), &[]);
if (nonce != Value::Null) && (firstDeltaNonce != Value::Null) && (nonce.as_f64().unwrap_or(f64::NAN) < (match (&(firstDeltaNonce), &(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().unwrap_or(f64::NAN)) {
return Value::Int(-1);
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_661: bool = true;
while { if !__for_first_661 { 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_661 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&cache).as_f64().unwrap_or(f64::NAN) } {
let mut delta: Value = get_value(&cache, &i);
let mut delta: Value = get_value(&cache, &i);
let mut deltaNonce: Value = self.safe_integer2(delta, Value::Str("i".into()), Value::Str("u".into()), &[]);
if (deltaNonce != Value::Null) && (nonce != Value::Null) && (deltaNonce.as_f64().unwrap_or(f64::NAN) >= nonce.as_f64().unwrap_or(f64::NAN)) {
return i;
}
}
}
return get_array_length(&cache);
Value::Null
}
pub fn handle_delta(&self, mut orderbook: Value, mut delta: Value) {
add_element_to_object(&mut orderbook, &Value::Str("nonce".into()), self.safe_integer2(delta.clone(), Value::Str("i".into()), Value::Str("u".into()), &[]));
let mut obAsks: Value = self.safe_list_k(delta.clone(), "a", &[Value::from(vec![])]);
let mut obBids: Value = self.safe_list_k(delta, "b", &[Value::from(vec![])]);
let mut bids: Value = crate::value::get_value_k(&orderbook, "bids");
let mut asks: Value = crate::value::get_value_k(&orderbook, "asks");
{
let mut i: Value = Value::Int(0);
let mut __for_first_662: bool = true;
while { if !__for_first_662 { 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_662 = false; i.as_f64().unwrap_or(f64::NAN) < ((obBids.len() as i64) as f64) } {
let mut bid: Value = obBids.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 price: Value = self.safe_number(bid.clone(), Value::Int(0), &[]);
let mut quantity: Value = self.safe_number(bid, Value::Int(1), &[]);
bids.store(price.clone(), quantity.clone());
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_663: bool = true;
while { if !__for_first_663 { 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_663 = false; i.as_f64().unwrap_or(f64::NAN) < ((obAsks.len() as i64) as f64) } {
let mut ask: Value = obAsks.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 price: Value = self.safe_number(ask.clone(), Value::Int(0), &[]);
let mut quantity: Value = self.safe_number(ask, Value::Int(1), &[]);
asks.store(price, quantity);
}
}
}
/*
* @ignore
* @method
* @description Connects to a websocket channel
* @see https://doc.xt.com/docs/spot/WebSocket%20Private/RequestMessageFormat
* @see https://doc.xt.com/docs/futures/WebsocKetV2/General_WSS_information
* @param {string} name name of the channel
* @param {string} access public or private
* @param {string} methodName the name of the CCXT class method
* @param {object} [market] CCXT market
* @param {string[]} [symbols] unified market symbols
* @param {object} params extra parameters specific to the xt api
* @returns {object} data from the websocket stream
*/
pub async fn subscribe(&mut self, mut name: Value, mut access: Value, mut methodName: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut symbols = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut privateAccess: bool = access.as_str() == Some("private");
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(methodName, &[market, 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 isContract: Value = (Value::Bool(type_var.as_str() != Some("spot")));
let mut id: Value = Value::Str(format!("{}{}", self.number_to_string(self.milliseconds()), name).into()); // call back ID
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), (if matches!(&isContract, Value::Bool(true)) { Value::Str("SUBSCRIBE".into()) } else { Value::Str("subscribe".into()) }));
m.insert("id".to_string(), id.clone());
m
});
if privateAccess {
if !(matches!(&isContract, Value::Bool(true))) {
if let Value::Dict(__d) = &mut subscribe { std::sync::Arc::make_mut(__d).insert("params".into(), Value::from(vec![name.clone()])); }
if let Value::Dict(__d) = &mut subscribe { std::sync::Arc::make_mut(__d).insert("listenKey".into(), self.get_listen_key(isContract.clone()).await); }
} else {
let mut listenKey: Value = self.get_listen_key(isContract.clone()).await;
let mut param: Value = add(&Value::Str(format!("{}{}", name, Value::Str("@".into())).into()), &listenKey);
if let Value::Dict(__d) = &mut subscribe { std::sync::Arc::make_mut(__d).insert("params".into(), Value::from(vec![param])); }
}
} else {
if let Value::Dict(__d) = &mut subscribe { std::sync::Arc::make_mut(__d).insert("params".into(), Value::from(vec![name.clone()])); }
}
let mut tradeType: Value = (if matches!(&isContract, Value::Bool(true)) { Value::Str("contract".into()) } else { Value::Str("spot".into()) });
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", name, Value::Str("::".into())).into()), tradeType).into());
if (symbols != Value::Null) {
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str("::".into())).into()), join(&symbols, &Value::Str(",".into()))).into());
}
let mut request: Value = self.extend(subscribe, &[params]);
let mut tail: Value = access;
if matches!(&isContract, Value::Bool(true)) {
tail = (if privateAccess { Value::Str("user".into()) } else { Value::Str("market".into()) });
}
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m
});
let mut url: Value = Value::Str(format!("{}{}", add(&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), &tradeType), &Value::Str("/".into())), tail).into());
return self.watch(url, messageHash.clone(), &[request, messageHash.clone(), subscription]).await;
Value::Null
}
/*
* @ignore
* @method
* @description Connects to a websocket channel
* @see https://doc.xt.com/docs/spot/WebSocket%20Private/RequestMessageFormat
* @see https://doc.xt.com/docs/futures/WebsocKetV2/General_WSS_information
* @param {string} messageHash the message hash of the subscription
* @param {string} name name of the channel
* @param {string} access public or private
* @param {string} methodName the name of the CCXT class method
* @param {string} topic topic of the subscription
* @param {object} [market] CCXT market
* @param {string[]} [symbols] unified market symbols
* @param {object} params extra parameters specific to the xt api
* @param {object} subscriptionParams extra parameters specific to the subscription
* @returns {object} data from the websocket stream
*/
pub async fn un_subscribe(&mut self, mut messageHash: Value, mut name: Value, mut access: Value, mut methodName: Value, mut topic: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut symbols = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut subscriptionParams = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut privateAccess: bool = access.as_str() == Some("private");
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(methodName, &[market, 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 isContract: Value = (Value::Bool(type_var.as_str() != Some("spot")));
let mut id: Value = Value::Str(format!("{}{}", self.number_to_string(self.milliseconds()), name).into()); // call back ID
let mut unsubscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), (if matches!(&isContract, Value::Bool(true)) { Value::Str("UNSUBSCRIBE".into()) } else { Value::Str("unsubscribe".into()) }));
m.insert("id".to_string(), id.clone());
m
});
if privateAccess {
if !(matches!(&isContract, Value::Bool(true))) {
if let Value::Dict(__d) = &mut unsubscribe { std::sync::Arc::make_mut(__d).insert("params".into(), Value::from(vec![name.clone()])); }
if let Value::Dict(__d) = &mut unsubscribe { std::sync::Arc::make_mut(__d).insert("listenKey".into(), self.get_listen_key(isContract.clone()).await); }
} else {
let mut listenKey: Value = self.get_listen_key(isContract.clone()).await;
let mut param: Value = add(&Value::Str(format!("{}{}", name, Value::Str("@".into())).into()), &listenKey);
if let Value::Dict(__d) = &mut unsubscribe { std::sync::Arc::make_mut(__d).insert("params".into(), Value::from(vec![param])); }
}
} else {
if let Value::Dict(__d) = &mut unsubscribe { std::sync::Arc::make_mut(__d).insert("params".into(), Value::from(vec![name.clone()])); }
}
let mut tradeType: Value = (if matches!(&isContract, Value::Bool(true)) { Value::Str("contract".into()) } else { Value::Str("spot".into()) });
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", name, Value::Str("::".into())).into()), tradeType).into());
let mut request: Value = self.extend(unsubscribe, &[params.clone()]);
let mut tail: Value = access;
if matches!(&isContract, Value::Bool(true)) {
tail = (if privateAccess { Value::Str("user".into()) } else { Value::Str("market".into()) });
}
let mut url: Value = Value::Str(format!("{}{}", add(&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), &tradeType), &Value::Str("/".into())), tail).into());
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(), id);
m.insert("subMessageHashes".to_string(), Value::from(vec![subMessageHash]));
m.insert("messageHashes".to_string(), Value::from(vec![messageHash.clone()]));
m.insert("symbols".to_string(), symbols);
m.insert("topic".to_string(), topic);
m
});
let mut symbolsAndTimeframes: Value = self.safe_list_k(subscriptionParams.clone(), "symbolsAndTimeframes", &[]);
if (symbolsAndTimeframes != Value::Null) {
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("symbolsAndTimeframes".into(), symbolsAndTimeframes); }
subscriptionParams = self.omit(subscriptionParams.clone(), Value::Str("symbolsAndTimeframes".into()), &[]);
}
let __ws_arg_0 = self.extend(request, &[params]);
let __ws_arg_1 = self.extend(subscription, &[subscriptionParams]);
return self.watch(url, messageHash.clone(), &[__ws_arg_0, messageHash.clone(), __ws_arg_1]).await;
Value::Null
}
/*
* @method
* @name xt#watchTicker
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://doc.xt.com/docs/spot/WebSocket%20Public/Ticker
* @see https://doc.xt.com/docs/futures/WebsocKetV2/AggTicker
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} params extra parameters specific to the exchange API endpoint
* @param {string} [params.method] 'agg_ticker' (contract only) or 'ticker', default = 'ticker' - the endpoint that will be streamed
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/en/latest/manual.html#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);
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchTicker", &[]);
let mut defaultMethod: Value = self.safe_string_k(options, "method", &[Value::Str("ticker".into())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod]);
let mut name: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", method, Value::Str("@".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
return self.subscribe(name, Value::Str("public".into()), Value::Str("watchTicker".into()), &[market, Value::Null, params]).await;
Value::Null
}
/*
* @method
* @name xt#unWatchTicker
* @description stops watching a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://doc.xt.com/docs/spot/WebSocket%20Public/Ticker
* @see https://doc.xt.com/docs/futures/WebsocKetV2/AggTicker
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} params extra parameters specific to the exchange API endpoint
* @param {string} [params.method] 'agg_ticker' (contract only) or 'ticker', default = 'ticker' - the endpoint that will be streamed
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/en/latest/manual.html#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 options: Value = self.safe_dict_k(self.options.clone(), "unWatchTicker", &[]);
let mut defaultMethod: Value = self.safe_string_k(options, "method", &[Value::Str("ticker".into())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod.clone()]);
let mut name: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", method, Value::Str("@".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe::".into()), name).into());
return self.un_subscribe(messageHash, name, Value::Str("public".into()), Value::Str("unWatchTicker".into()), defaultMethod, &[market, Value::Null, params]).await;
Value::Null
}
/*
* @method
* @name xt#watchTickers
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://doc.xt.com/docs/spot/WebSocket%20Public/Ticker
* @see https://doc.xt.com/docs/futures/WebsocKetV2/AggTicker
* @param {string} [symbols] unified market symbols
* @param {object} params extra parameters specific to the exchange API endpoint
* @param {string} [params.method] 'agg_tickers' (contract only) or 'tickers', default = 'tickers' - the endpoint that will be streamed
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/en/latest/manual.html#ticker-structure}
*/
pub async fn watch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchTickers", &[]);
let mut defaultMethod: Value = self.safe_string_k(options, "method", &[Value::Str("tickers".into())]);
let mut name: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod]);
let mut market: Value = Value::Null;
if (symbols != Value::Null) {
market = self.market(symbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
}
let mut tickers: Value = self.subscribe(name, Value::Str("public".into()), Value::Str("watchTickers".into()), &[market, symbols.clone(), params]).await;
if is_true(&self.newUpdates) {
return tickers;
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".into()), &[symbols]);
Value::Null
}
/*
* @method
* @name xt#unWatchTickers
* @description stops watching a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://doc.xt.com/docs/spot/WebSocket%20Public/Ticker
* @see https://doc.xt.com/docs/futures/WebsocKetV2/AggTicker
* @param {string} [symbols] unified market symbols
* @param {object} params extra parameters specific to the exchange API endpoint
* @param {string} [params.method] 'agg_tickers' (contract only) or 'tickers', default = 'tickers' - the endpoint that will be streamed
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/en/latest/manual.html#ticker-structure}
*/
pub async fn un_watch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut options: Value = self.safe_dict_k(self.options.clone(), "unWatchTickers", &[]);
let mut defaultMethod: Value = self.safe_string_k(options, "method", &[Value::Str("tickers".into())]);
let mut name: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod]);
if (symbols != Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" unWatchTickers() does not support symbols argument, unsubscribtion is for all tickers at once only".into()))));
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe::".into()), name).into());
let mut tickers: Value = self.un_subscribe(messageHash, name, Value::Str("public".into()), Value::Str("unWatchTickers".into()), Value::Str("ticker".into()), &[Value::Null, symbols.clone(), params]).await;
if is_true(&self.newUpdates) {
return tickers;
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".into()), &[symbols]);
Value::Null
}
/*
* @method
* @name xt#watchOHLCV
* @description watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://doc.xt.com/docs/spot/WebSocket%20Public/Kline
* @see https://doc.xt.com/docs/futures/WebsocKetV2/Kline
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, or 1M
* @param {int} [since] not used by xt watchOHLCV
* @param {int} [limit] not used by xt watchOHLCV
* @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());
let mut name: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("kline@".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(",".into())).into()), timeframe).into());
let mut ohlcv: Value = self.subscribe(name, Value::Str("public".into()), Value::Str("watchOHLCV".into()), &[market, 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 xt#unWatchOHLCV
* @description stops watching historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://doc.xt.com/docs/spot/WebSocket%20Public/Kline
* @see https://doc.xt.com/docs/futures/WebsocKetV2/Kline
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, or 1M
* @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 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.clone());
let mut name: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("kline@".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(",".into())).into()), timeframe).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe::".into()), name).into());
let mut symbolsAndTimeframes: Value = Value::from(vec![Value::from(vec![market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), timeframe])]);
return self.un_subscribe(messageHash, name, Value::Str("public".into()), Value::Str("unWatchOHLCV".into()), Value::Str("ohlcv".into()), &[market, Value::from(vec![symbol]), params, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbolsAndTimeframes".to_string(), symbolsAndTimeframes);
m
})]).await;
Value::Null
}
/*
* @method
* @name xt#watchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://doc.xt.com/docs/spot/WebSocket%20Public/TradeRecord
* @see https://doc.xt.com/docs/futures/WebsocKetV2/TradeRecord
* @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/en/latest/manual.html?#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());
let mut name: Value = Value::Str(format!("{}{}", Value::Str("trade@".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut trades: Value = self.subscribe(name, Value::Str("public".into()), Value::Str("watchTrades".into()), &[market, 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::Null
}
/*
* @method
* @name xt#unWatchTrades
* @description stops watching the list of most recent trades for a particular symbol
* @see https://doc.xt.com/docs/spot/WebSocket%20Public/TradeRecord
* @see https://doc.xt.com/docs/futures/WebsocKetV2/TradeRecord
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {object} params extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/en/latest/manual.html?#public-trades}
*/
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.clone());
let mut name: Value = Value::Str(format!("{}{}", Value::Str("trade@".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe::".into()), name).into());
return self.un_subscribe(messageHash, name, Value::Str("public".into()), Value::Str("unWatchTrades".into()), Value::Str("trades".into()), &[market, Value::from(vec![symbol]), params]).await;
Value::Null
}
/*
* @method
* @name xt#watchOrderBook
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://doc.xt.com/docs/spot/WebSocket%20Public/LimitedDepth
* @see https://doc.xt.com/docs/spot/WebSocket%20Public/IncrementalDepth
* @see https://doc.xt.com/docs/futures/WebsocKetV2/LimitedDepth
* @see https://doc.xt.com/docs/futures/WebsocKetV2/IncrementalDepth
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] not used by xt watchOrderBook
* @param {object} params extra parameters specific to the exchange API endpoint
* @param {int} [params.levels] 5, 10, 20, or 50
* @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);
let mut levels: Value = self.safe_string_k(params.clone(), "levels", &[]);
params = self.omit(params.clone(), Value::Str("levels".into()), &[]);
let mut name: Value = Value::Str(format!("{}{}", Value::Str("depth_update@".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
if (levels != Value::Null) {
name = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("depth@".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(",".into())).into()), levels).into());
}
let mut orderbook: Value = self.subscribe(name, Value::Str("public".into()), Value::Str("watchOrderBook".into()), &[market, Value::Null, params]).await;
return orderbook.limit();
Value::Null
}
/*
* @method
* @name xt#unWatchOrderBook
* @description stops watching information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://doc.xt.com/docs/spot/WebSocket%20Public/LimitedDepth
* @see https://doc.xt.com/docs/spot/WebSocket%20Public/IncrementalDepth
* @see https://doc.xt.com/docs/futures/WebsocKetV2/LimitedDepth
* @see https://doc.xt.com/docs/futures/WebsocKetV2/IncrementalDepth
* @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.levels] 5, 10, 20, or 50
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/en/latest/manual.html#order-book-structure} indexed by market symbols
*/
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.clone());
let mut levels: Value = self.safe_string_k(params.clone(), "levels", &[]);
params = self.omit(params.clone(), Value::Str("levels".into()), &[]);
let mut name: Value = Value::Str(format!("{}{}", Value::Str("depth_update@".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
if (levels != Value::Null) {
name = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("depth@".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(",".into())).into()), levels).into());
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe::".into()), name).into());
return self.un_subscribe(messageHash, name, Value::Str("public".into()), Value::Str("unWatchOrderBook".into()), Value::Str("orderbook".into()), &[market, Value::from(vec![symbol]), params]).await;
Value::Null
}
/*
* @method
* @name xt#watchOrders
* @description watches information on multiple orders made by the user
* @see https://doc.xt.com/docs/spot/WebSocket%20Private/OrderChange
* @see https://doc.xt.com/docs/futures/UserWebsocket/UserOrder
* @param {string} [symbol] unified market symbol
* @param {int} [since] not used by xt watchOrders
* @param {int} [limit] the maximum number of orders to return
* @param {object} params extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/en/latest/manual.html#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 name: Value = Value::Str("order".into());
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut orders: Value = self.subscribe(name, Value::Str("private".into()), Value::Str("watchOrders".into()), &[market, Value::Null, params]).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::Null
}
/*
* @method
* @name xt#watchMyTrades
* @description watches information on multiple trades made by the user
* @see https://doc.xt.com/docs/spot/WebSocket%20Private/OrderFilled
* @see https://doc.xt.com/docs/futures/UserWebsocket/Transactions
* @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 orde 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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("trade".into());
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut trades: Value = self.subscribe(name, Value::Str("private".into()), Value::Str("watchMyTrades".into()), &[market, 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::Null
}
/*
* @method
* @name xt#watchOrders
* @description watches information on multiple orders made by the user
* @see https://doc.xt.com/docs/spot/WebSocket%20Private/BalanceChange
* @see https://doc.xt.com/docs/futures/UserWebsocket/BalanceChange
* @param {object} params extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [balance structures]{@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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("balance".into());
return self.subscribe(name, Value::Str("private".into()), Value::Str("watchBalance".into()), &[Value::Null, Value::Null, params]).await;
Value::Null
}
/*
* @method
* @name xt#watchPositions
* @see https://doc.xt.com/docs/futures/UserWebsocket/ChangePosition
* @description watch all open positions
* @param {string[]|undefined} symbols list of unified market symbols
* @param {number} [since] since timestamp
* @param {number} [limit] limit
* @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 url: Value = Value::Str(format!("{}{}", add(&crate::value::get_value_k(&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), "contract"), &Value::Str("/".into())), Value::Str("user".into())).into());
let mut client: Value = self.client(&[url]);
self.set_positions_cache(client.clone());
let mut fetchPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".into()), Value::Str("fetchPositionsSnapshot".into()), &[Value::Bool(true)]);
let mut awaitPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".into()), Value::Str("awaitPositionsSnapshot".into()), &[Value::Bool(true)]);
let mut cache: Value = self.positions.clone();
if (is_equal(&fetchPositionsSnapshot, &Value::Bool(true))) && (is_equal(&awaitPositionsSnapshot, &Value::Bool(true))) && self.is_empty(cache.clone()).as_bool() == Some(true) {
let mut snapshot: Value = crate::exchange_stubs::ws_await_flight(&client.future(&[Value::Str("fetchPositionsSnapshot".into())])).await;
return self.filter_by_symbols_since_limit(snapshot, &[symbols.clone(), since.clone(), limit.clone(), Value::Bool(true)]);
}
let mut name: Value = Value::Str("position".into());
let mut newPositions: Value = self.subscribe(name, Value::Str("private".into()), Value::Str("watchPositions".into()), &[Value::Null, Value::Null, params]).await;
if is_true(&self.newUpdates) {
return newPositions;
}
return self.filter_by_symbols_since_limit(cache, &[symbols, since, limit, Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name xt#watchFundingRate
* @description watch the current funding rate
* @see https://doc.xt.com/docs/futures/WebsocKetV2/FundRate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/en/latest/manual.html#funding-rate-structure}
*/
pub async fn watch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" watchFundingRate() supports swap contracts only".into()))));
}
let mut name: Value = Value::Str(format!("{}{}", Value::Str("fund_rate@".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
return self.subscribe(name, Value::Str("public".into()), Value::Str("watchFundingRate".into()), &[market, Value::Null, params]).await;
Value::Null
}
/*
* @method
* @name xt#unWatchFundingRate
* @description stops watching the funding rate
* @see https://doc.xt.com/docs/futures/WebsocKetV2/FundRate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/en/latest/manual.html#funding-rate-structure}
*/
pub async fn un_watch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" unWatchFundingRate() supports swap contracts only".into()))));
}
let mut name: Value = Value::Str(format!("{}{}", Value::Str("fund_rate@".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe::".into()), name).into());
return self.un_subscribe(messageHash, name, Value::Str("public".into()), Value::Str("unWatchFundingRate".into()), Value::Str("fund_rate".into()), &[market, Value::Null, params]).await;
Value::Null
}
pub fn handle_funding_rate(&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;
//
// {
// "topic": "fund_rate",
// "event": "fund_rate@btc_usdt",
// "data": {
// "s": "btc_usdt", // symbol
// "r": "0.01", // funding rate
// "t": 123124124 // timestamp
// }
// }
//
let mut data: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
if (marketId != Value::Null) {
let mut raw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), marketId);
m.insert("fundingRate".to_string(), self.safe_string_k(data.clone(), "r", &[]));
m
});
let mut fundingRate: Value = self.parse_funding_rate(raw, &[]);
let mut timestamp: Value = self.safe_integer_k(data, "t", &[]);
add_element_to_object(&mut fundingRate, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut fundingRate, &Value::Str("datetime".into()), self.iso8601(timestamp));
let mut symbol: Value = fundingRate.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut self.fundingRates { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), fundingRate.clone()); }
let mut event: Value = (match __pro_message.get("event").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 messageHash: Value = Value::Str(format!("{}{}", event, Value::Str("::contract".into())).into());
client.resolve(&[fundingRate, messageHash]);
}
return message;
Value::Null
}
pub fn set_positions_cache(&mut self, mut client: Value) {
if (self.positions.clone() == Value::Null) {
self.positions = ArrayCacheBySymbolBySide::new(Value::Null);
}
let mut fetchPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".into()), Value::Str("fetchPositionsSnapshot".into()), &[]);
if is_equal(&fetchPositionsSnapshot, &Value::Bool(true)) {
let mut messageHash: Value = Value::Str("fetchPositionsSnapshot".into());
if !(in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
client.future(&[messageHash.clone()]);
self.spawn(&[Value::Str("load_positions_snapshot".into()).clone(), client.clone(), messageHash.clone()]);
}
}
}
pub async fn load_positions_snapshot(&mut self, mut client: Value, mut messageHash: Value) -> Value {
let mut positions: Value = self.fetch_positions(&[]).await;
self.positions = ArrayCacheBySymbolBySide::new(Value::Null);
let mut cache: Value = self.positions.clone();
{
let mut i: Value = Value::Int(0);
let mut __for_first_664: bool = true;
while { if !__for_first_664 { 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_664 = false; i.as_f64().unwrap_or(f64::NAN) < ((positions.len() as i64) as f64) } {
let mut position: Value = positions.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 contracts: Value = self.safe_number_k(position.clone(), "contracts", &[Value::Int(0)]);
if (contracts != Value::Null) && (contracts.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
cache.append(position);
}
}
}
// don't remove the future from the .futures cache
if (in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
let mut future: Value = get_value(&get_value(&client, &Value::Str("futures".into())), &messageHash);
future.resolve(&[cache.clone()]);
client.resolve(&[cache, Value::Str("position::contract".into())]);
}
Value::Null
}
pub fn handle_position(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// topic: 'position',
// event: 'position',
// data: {
// accountId: 245296,
// accountType: 0,
// symbol: 'eth_usdt',
// contractType: 'PERPETUAL',
// positionType: 'CROSSED',
// positionSide: 'LONG',
// positionSize: '1',
// closeOrderSize: '0',
// availableCloseSize: '1',
// realizedProfit: '-0.0121',
// entryPrice: '2637.87',
// openOrderSize: '1',
// isolatedMargin: '2.63787',
// openOrderMarginFrozen: '2.78832014',
// underlyingType: 'U_BASED',
// leverage: 10,
// welfareAccount: false,
// profitFixedLatest: {},
// closeProfit: '0.0000',
// totalFee: '-0.0158',
// totalFundFee: '0.0037',
// markPrice: '2690.96'
// }
// }
//
if (self.positions.clone() == Value::Null) {
self.positions = ArrayCacheBySymbolBySide::new(Value::Null);
}
let mut cache: Value = self.positions.clone();
let mut data: 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 position: Value = self.parse_position(data, &[]);
cache.append(position.clone());
let mut messageHashes: Value = self.find_message_hashes(client.clone(), Value::Str("position::contract".into()));
{
let mut i: Value = Value::Int(0);
let mut __for_first_665: bool = true;
while { if !__for_first_665 { 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_665 = false; i.as_f64().unwrap_or(f64::NAN) < ((messageHashes.len() as i64) as f64) } {
let mut messageHash: 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 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(Value::from(vec![position.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(&[Value::from(vec![position]), Value::Str("position::contract".into())]);
}
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;
//
// spot
//
// {
// topic: 'ticker',
// event: 'ticker@btc_usdt',
// data: {
// s: 'btc_usdt', // symbol
// t: 1683501935877, // time(Last transaction time)
// cv: '-82.67', // priceChangeValue(24 hour price change)
// cr: '-0.0028', // priceChangeRate 24-hour price change (percentage)
// o: '28823.87', // open price
// c: '28741.20', // close price
// h: '29137.64', // highest price
// l: '28660.93', // lowest price
// q: '6372.601573', // quantity
// v: '184086075.2772391' // volume
// }
// }
//
// contract
//
// {
// "topic": "ticker",
// "event": "ticker@btc_usdt",
// "data": {
// "s": "btc_index", // trading pair
// "o": "49000", // opening price
// "c": "50000", // closing price
// "h": "0.1", // highest price
// "l": "0.1", // lowest price
// "a": "0.1", // volume
// "v": "0.1", // turnover
// "ch": "0.21", // quote change
// "t": 123124124 // timestamp
// }
// }
//
// agg_ticker (contract)
//
// {
// "topic": "agg_ticker",
// "event": "agg_ticker@btc_usdt",
// "data": {
// "s": "btc_index", // trading pair
// "o": "49000", // opening price
// "c": "50000", // closing price
// "h": "0.1", // highest price
// "l": "0.1", // lowest price
// "a": "0.1", // volume
// "v": "0.1", // turnover
// "ch": "0.21", // quote change
// "i": "0.21" , // index price
// "m": "0.21", // mark price
// "bp": "0.21", // bid price
// "ap": "0.21" , // ask price
// "t": 123124124 // timestamp
// }
// }
//
let mut data: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Option<String> = self.safe_string_k(data.clone(), "s", &[]).as_str().map(str::to_owned);
if (marketId.is_some()) {
let mut cv: Option<String> = self.safe_string_k(data.clone(), "cv", &[]).as_str().map(str::to_owned);
let mut isSpot: bool = cv.is_some();
let mut ticker: Value = self.parse_ticker(data, &[]);
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()); }
}
let mut event: Value = (match __pro_message.get("event").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 messageHashTail: Value = (if isSpot { Value::Str("spot".into()) } else { Value::Str("contract".into()) });
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", event, Value::Str("::".into())).into()), messageHashTail).into());
client.resolve(&[ticker, messageHash]);
}
return message;
Value::Null
}
pub fn handle_tickers(&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;
//
// spot
//
// {
// topic: 'tickers',
// event: 'tickers',
// data: [
// {
// s: 'elon_usdt',
// t: 1683502958381,
// cv: '-0.0000000125',
// cr: '-0.0495',
// o: '0.0000002522',
// c: '0.0000002397',
// h: '0.0000002690',
// l: '0.0000002371',
// q: '3803783034.0000000000',
// v: '955.3260820022'
// },
// ...
// ]
// }
//
// contract
//
// {
// "topic": "tickers",
// "event": "tickers",
// "data": [
// {
// "s": "btc_index", // trading pair
// "o": "49000", // opening price
// "c": "50000", // closing price
// "h": "0.1", // highest price
// "l": "0.1", // lowest price
// "a": "0.1", // volume
// "v": "0.1", // turnover
// "ch": "0.21", // quote change
// "t": 123124124 // timestamp
// }
// ]
// }
//
// agg_ticker (contract)
//
// {
// "topic": "agg_tickers",
// "event": "agg_tickers",
// "data": [
// {
// "s": "btc_index", // trading pair
// "o": "49000", // opening price
// "c": "50000", // closing price
// "h": "0.1", // highest price
// "l": "0.1", // lowest price
// "a": "0.1", // volume
// "v": "0.1", // turnover
// "ch": "0.21", // quote change
// "i": "0.21" , // index price
// "m": "0.21", // mark price
// "bp": "0.21", // bid price
// "ap": "0.21" , // ask price
// "t": 123124124 // timestamp
// }
// ]
// }
//
let mut data: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
let mut firstTicker: Value = self.safe_dict(data.clone(), Value::Int(0), &[]);
let mut spotTest: Option<String> = self.safe_string2(firstTicker, Value::Str("cv".into()), Value::Str("aq".into()), &[]).as_str().map(str::to_owned);
let mut tradeType: Value = (if (spotTest.is_some()) { Value::Str("spot".into()) } else { Value::Str("contract".into()) });
let mut newTickers: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_666: bool = true;
while { if !__for_first_666 { 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_666 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut tickerData: 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 ticker: Value = self.parse_ticker(tickerData, &[]);
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()); }
}
append_to_array(&mut newTickers, ticker);
}
}
let mut messageHashStart: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", (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::Null }), Value::Str("::".into())).into()), tradeType).into());
let mut messageHashes: Value = self.find_message_hashes(client.clone(), Value::Str(format!("{}{}", messageHashStart, Value::Str("::".into())).into()));
{
let mut i: Value = Value::Int(0);
let mut __for_first_667: bool = true;
while { if !__for_first_667 { 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_667 = false; i.as_f64().unwrap_or(f64::NAN) < ((messageHashes.len() as i64) as f64) } {
let mut messageHash: 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 parts: Value = split(&messageHash, &Value::Str("::".into()));
let mut symbolsString: Value = parts.as_array().and_then(|__arr| __arr.get(2)).cloned().unwrap_or(Value::Null);
let mut symbols: Value = split(&symbolsString, &Value::Str(",".into()));
let mut tickers: Value = self.filter_by_array(newTickers.clone(), Value::Str("symbol".into()), &[symbols]);
let mut tickersSymbols: Value = object_keys(&tickers);
let mut numTickers: f64 = ((tickersSymbols.len() as i64) as f64);
if numTickers > ((0i64) as f64) {
client.resolve(&[tickers.clone(), messageHash]);
}
}
}
client.resolve(&[self.tickers.clone(), messageHashStart]);
return message;
Value::Null
}
pub fn handle_ohlcv(&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;
//
// spot
//
// {
// "topic": "kline",
// "event": "kline@btc_usdt,5m",
// "data": {
// "s": "btc_usdt", // symbol
// "t": 1656043200000, // time
// "i": "5m", // interval
// "o": "44000", // open price
// "c": "50000", // close price
// "h": "52000", // highest price
// "l": "36000", // lowest price
// "q": "34.2", // qty(quantity)
// "v": "230000" // volume
// }
// }
//
// contract
//
// {
// "topic": "kline",
// "event": "kline@btc_usdt,5m",
// "data": {
// "s": "btc_index", // trading pair
// "o": "49000", // opening price
// "c": "50000", // closing price
// "h": "0.1", // highest price
// "l": "0.1", // lowest price
// "a": "0.1", // volume
// "v": "0.1", // turnover
// "ch": "0.21", // quote change
// "t": 123124124 // timestamp
// }
// }
//
let mut data: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
if (marketId != Value::Null) {
let mut timeframe: Value = self.safe_string_k(data.clone(), "i", &[Value::Str("".into())]);
let mut tradeType: Value = (if (matches!(&data, Value::Dict(__d) if __d.contains_key("q"))) { Value::Str("spot".into()) } else { Value::Str("contract".into()) });
let mut market: Value = self.safe_market(&[marketId, Value::Null, Value::Null, tradeType.clone()]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut parsed: Value = self.parse_ohlcv(data, &[market]);
{ 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(get_value(&self.ohlcvs, &symbol), 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);
add_element_to_object(get_value_mut(&mut self.ohlcvs, &symbol), &timeframe, stored.clone());
}
stored.append(parsed);
let mut event: Value = (match __pro_message.get("event").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 messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", event, Value::Str("::".into())).into()), tradeType).into());
client.resolve(&[stored, messageHash]);
}
return message;
Value::Null
}
pub fn handle_trade(&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;
//
// spot
//
// {
// topic: 'trade',
// event: 'trade@btc_usdt',
// data: {
// s: 'btc_usdt',
// i: '228825383103928709',
// t: 1684258222702,
// p: '27003.65',
// q: '0.000796',
// b: true
// }
// }
//
// contract
//
// {
// "topic": "trade",
// "event": "trade@btc_usdt",
// "data": {
// "s": "btc_index", // trading pair
// "p": "50000", // price
// "a": "0.1" // Quantity
// "m": "BID" // Deal side BID:Buy ASK:Sell
// "t": 123124124 // timestamp
// }
// }
//
let mut data: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_lower_k(data.clone(), "s", &[]);
if (marketId != Value::Null) {
let mut trade: Value = self.parse_trade(data.clone(), &[]);
let mut i: Option<String> = self.safe_string_k(data, "i", &[]).as_str().map(str::to_owned);
let mut tradeType: Value = (if (i.is_some()) { Value::Str("spot".into()) } else { Value::Str("contract".into()) });
let mut market: Value = self.safe_market(&[marketId, Value::Null, Value::Null, tradeType.clone()]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut event: Value = (match __pro_message.get("event").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 tradesArray: Value = self.safe_value(self.trades.clone(), symbol.clone(), &[]);
if (tradesArray == Value::Null) {
let mut tradesLimit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
tradesArray = ArrayCache::new(tradesLimit);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), tradesArray.clone()); }
}
tradesArray.append(trade);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", event, Value::Str("::".into())).into()), tradeType).into());
client.resolve(&[tradesArray, messageHash]);
}
return message;
Value::Null
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// spot
//
// {
// "topic": "depth",
// "event": "depth@btc_usdt,20",
// "data": {
// "s": "btc_usdt", // symbol
// "fi": 1681433733351, // firstUpdateId = previous lastUpdateId + 1
// "i": 1681433733371, // updateId
// "a": [ // asks(sell order)
// [ // [0]price, [1]quantity
// "34000", // price
// "1.2" // quantity
// ],
// [
// "34001",
// "2.3"
// ]
// ],
// "b": [ // bids(buy order)
// [
// "32000",
// "0.2"
// ],
// [
// "31000",
// "0.5"
// ]
// ]
// }
// }
//
// contract
//
// {
// "topic": "depth",
// "event": "depth@btc_usdt,20",
// "data": {
// s: "btc_usdt",
// pu: "548111455664",
// fu: "548111455665",
// u: "548111455667",
// a: [
// [
// "26841.5",
// "50210",
// ],
// ],
// b: [
// [
// "26841",
// "67075",
// ],
// ],
// t: 1684530667083,
// }
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Null });
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
if (marketId != Value::Null) {
let mut event: Value = (match message.get("event") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
let mut splitEvent: Value = split(&event, &Value::Str(",".into()));
event = self.safe_string(splitEvent, Value::Int(0), &[Value::Str("".into())]);
let mut tradeType: Value = Value::Str("spot".into());
if (data != Value::Null) && (matches!(&data, Value::Dict(__d) if __d.contains_key("fu"))) {
tradeType = Value::Str("contract".into());
}
let mut market: Value = self.safe_market(&[marketId, Value::Null, Value::Null, tradeType.clone()]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut obAsks: Value = self.safe_list_k(data.clone(), "a", &[]);
let mut obBids: Value = self.safe_list_k(data.clone(), "b", &[]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", event, Value::Str("::".into())).into()), tradeType).into());
if !(in_op(&self.orderbooks, &symbol)) {
let mut subscription: Value = self.safe_dict(get_value(&client, &Value::Str("subscriptions".into())), messageHash.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut limit: Value = self.safe_integer_k(subscription, "limit", &[]);
{ 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);
let mut nonce: Option<i64> = self.safe_integer_k(orderbook.clone(), "nonce", &[]).as_i64();
if (nonce.is_none()) {
let mut cacheLength: Value = Value::Int(get_value(&orderbook, &Value::Str("cache".into())).len() as i64);
let mut snapshotDelay: Value = self.handle_option(Value::Str("watchOrderBook".into()), Value::Str("snapshotDelay".into()), &[Value::Int(25)]);
if is_equal(&cacheLength, &snapshotDelay) {
self.spawn(&[Value::Str("load_order_book".into()).clone(), client.clone(), messageHash.clone(), symbol.clone()]);
}
crate::runtime::append_to_object_array(&mut orderbook, &Value::Str("cache".into()), data.clone());
return;
}
if (obAsks != Value::Null) {
let mut asks: Value = get_value(&orderbook, &Value::Str("asks".into()));
{
let mut i: Value = Value::Int(0);
let mut __for_first_668: bool = true;
while { if !__for_first_668 { 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_668 = false; i.as_f64().unwrap_or(f64::NAN) < ((obAsks.len() as i64) as f64) } {
let mut ask: Value = obAsks.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 price: Value = self.safe_number(ask.clone(), Value::Int(0), &[]);
let mut quantity: Value = self.safe_number(ask, Value::Int(1), &[]);
asks.store(price.clone(), quantity.clone());
}
}
}
if (obBids != Value::Null) {
let mut bids: Value = get_value(&orderbook, &Value::Str("bids".into()));
{
let mut i: Value = Value::Int(0);
let mut __for_first_669: bool = true;
while { if !__for_first_669 { 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_669 = false; i.as_f64().unwrap_or(f64::NAN) < ((obBids.len() as i64) as f64) } {
let mut bid: Value = obBids.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 price: Value = self.safe_number(bid.clone(), Value::Int(0), &[]);
let mut quantity: Value = self.safe_number(bid, Value::Int(1), &[]);
bids.store(price, quantity);
}
}
}
let mut timestamp: Value = self.safe_integer_k(data.clone(), "t", &[]);
add_element_to_object(&mut orderbook, &Value::Str("nonce".into()), self.safe_integer2(data, Value::Str("i".into()), Value::Str("u".into()), &[]));
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));
add_element_to_object(&mut orderbook, &Value::Str("symbol".into()), symbol);
client.resolve(&[orderbook, messageHash]);
}
}
pub fn parse_ws_order_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "s": "btc_usdt", // symbol
// "t": 1656043204763, // time happened time
// "i": "6216559590087220004", // orderId,
// "ci": "test123", // clientOrderId
// "st": "PARTIALLY_FILLED", // state
// "sd": "BUY", // side BUY/SELL
// "eq": "2", // executedQty executed quantity
// "ap": "30000", // avg price
// "f": "0.002" // fee
// }
//
// contract
//
// {
// "symbol": "btc_usdt", // Trading pair
// "orderId": "1234", // Order Id
// "origQty": "34244", // Original Quantity
// "avgPrice": "123", // Quantity
// "price": "1111", // Average price
// "executedQty": "34244", // Volume (Cont)
// "orderSide": "BUY", // BUY, SELL
// "positionSide": "LONG", // LONG, SHORT
// "marginFrozen": "123", // Occupied margin
// "sourceType": "default", // DEFAULT:normal order,ENTRUST:plan commission,PROFIR:Take Profit and Stop Loss
// "sourceId" : "1231231", // Triggering conditions ID
// "state": "", // state:NEW:New order (unfilled);PARTIALLY_FILLED:Partial deal;PARTIALLY_CANCELED:Partial revocation;FILLED:Filled;CANCELED:Cancled;REJECTED:Order failed;EXPIRED:Expired
// "createTime": 1731231231, // CreateTime
// "clientOrderId": "204788317630342726"
// }
//
let mut marketId: Value = self.safe_string_k(trade.clone(), "s", &[]);
let mut tradeType: Value = (if (matches!(&trade, Value::Dict(__d) if __d.contains_key("symbol"))) { Value::Str("contract".into()) } else { Value::Str("spot".into()) });
market = self.safe_market(&[marketId, market.clone(), Value::Null, tradeType]);
let mut timestamp: Value = self.safe_string_k(trade.clone(), "t", &[]);
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("id".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("order".to_string(), self.safe_string_k(trade.clone(), "i", &[Value::Str("orderId".into())]));
m.insert("type".to_string(), self.parent.parse_order_status(self.safe_string_k(trade.clone(), "st", &[Value::Str("state".into())])));
m.insert("side".to_string(), self.safe_string_lower_k(trade.clone(), "sd", &[Value::Str("orderSide".into())]));
m.insert("takerOrMaker".to_string(), Value::Null);
m.insert("price".to_string(), self.safe_number_k(trade.clone(), "price", &[]));
m.insert("amount".to_string(), self.safe_string_k(trade.clone(), "origQty", &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Null);
m.insert("cost".to_string(), self.safe_number_k(trade, "f", &[]));
m.insert("rate".to_string(), Value::Null);
m
}));
m
}), &[market]);
Value::Null
}
pub fn parse_ws_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// spot
//
// {
// "s": "btc_usdt", // symbol
// "bc": "btc", // base currency
// "qc": "usdt", // quotation currency
// "t": 1656043204763, // happened time
// "ct": 1656043204663, // create time
// "i": "6216559590087220004", // order id,
// "ci": "test123", // client order id
// "st": "PARTIALLY_FILLED", // state NEW/PARTIALLY_FILLED/FILLED/CANCELED/REJECTED/EXPIRED
// "sd": "BUY", // side BUY/SELL
// "tp": "LIMIT", // type LIMIT/MARKET
// "oq": "4" // original quantity
// "oqq": 48000, // original quotation quantity
// "eq": "2", // executed quantity
// "lq": "2", // remaining quantity
// "p": "4000", // price
// "ap": "30000", // avg price
// "f":"0.002" // fee
// }
//
// contract
//
// {
// "symbol": "btc_usdt", // Trading pair
// "orderId": "1234", // Order Id
// "origQty": "34244", // Original Quantity
// "avgPrice": "123", // Quantity
// "price": "1111", // Average price
// "executedQty": "34244", // Volume (Cont)
// "orderSide": "BUY", // BUY, SELL
// "positionSide": "LONG", // LONG, SHORT
// "marginFrozen": "123", // Occupied margin
// "sourceType": "default", // DEFAULT:normal order,ENTRUST:plan commission,PROFIR:Take Profit and Stop Loss
// "sourceId" : "1231231", // Triggering conditions ID
// "state": "", // state:NEW:New order (unfilled);PARTIALLY_FILLED:Partial deal;PARTIALLY_CANCELED:Partial revocation;FILLED:Filled;CANCELED:Cancled;REJECTED:Order failed;EXPIRED:Expired
// "createTime": 1731231231, // CreateTime
// "clientOrderId": "204788317630342726"
// }
//
let mut marketId: Value = self.safe_string2(order.clone(), Value::Str("s".into()), Value::Str("symbol".into()), &[]);
let mut tradeType: Value = (if (matches!(&order, Value::Dict(__d) if __d.contains_key("symbol"))) { Value::Str("contract".into()) } else { Value::Str("spot".into()) });
market = self.safe_market(&[marketId, market.clone(), Value::Null, tradeType]);
let mut timestamp: Value = self.safe_integer2(order.clone(), Value::Str("ct".into()), Value::Str("createTime".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(), self.safe_string2(order.clone(), Value::Str("i".into()), Value::Str("orderId".into()), &[]));
m.insert("clientOrderId".to_string(), self.safe_string2(order.clone(), Value::Str("ci".into()), Value::Str("clientOrderId".into()), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null));
m.insert("timeInForce".to_string(), Value::Null);
m.insert("postOnly".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_lower2(order.clone(), Value::Str("sd".into()), Value::Str("orderSide".into()), &[]));
m.insert("price".to_string(), self.safe_number2(order.clone(), Value::Str("p".into()), Value::Str("price".into()), &[]));
m.insert("stopPrice".to_string(), Value::Null);
m.insert("stopLoss".to_string(), Value::Null);
m.insert("takeProfit".to_string(), Value::Null);
m.insert("amount".to_string(), self.safe_string2(order.clone(), Value::Str("oq".into()), Value::Str("origQty".into()), &[]));
m.insert("filled".to_string(), self.safe_string2(order.clone(), Value::Str("eq".into()), Value::Str("executedQty".into()), &[]));
m.insert("remaining".to_string(), self.safe_string_k(order.clone(), "lq", &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), self.safe_string2(order.clone(), Value::Str("ap".into()), Value::Str("avgPrice".into()), &[]));
m.insert("status".to_string(), self.parent.parse_order_status(self.safe_string_k(order.clone(), "st", &[Value::Str("state".into())])));
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Null);
m.insert("cost".to_string(), self.safe_number_k(order, "f", &[]));
m
}));
m.insert("trades".to_string(), Value::Null);
m
}), &[market]);
Value::Null
}
pub fn handle_order(&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;
//
// spot
//
// {
// "topic": "order",
// "event": "order",
// "data": {
// "s": "btc_usdt", // symbol
// "t": 1656043204763, // time happened time
// "i": "6216559590087220004", // orderId,
// "ci": "test123", // clientOrderId
// "st": "PARTIALLY_FILLED", // state
// "sd": "BUY", // side BUY/SELL
// "eq": "2", // executedQty executed quantity
// "ap": "30000", // avg price
// "f": "0.002" // fee
// }
// }
//
// contract
//
// {
// "topic": "order",
// "event": "order@123456",
// "data": {
// "symbol": "btc_usdt", // Trading pair
// "orderId": "1234", // Order Id
// "origQty": "34244", // Original Quantity
// "avgPrice": "123", // Quantity
// "price": "1111", // Average price
// "executedQty": "34244", // Volume (Cont)
// "orderSide": "BUY", // BUY, SELL
// "positionSide": "LONG", // LONG, SHORT
// "marginFrozen": "123", // Occupied margin
// "sourceType": "default", // DEFAULT:normal order,ENTRUST:plan commission,PROFIR:Take Profit and Stop Loss
// "sourceId" : "1231231", // Triggering conditions ID
// "state": "", // state:NEW:New order (unfilled);PARTIALLY_FILLED:Partial deal;PARTIALLY_CANCELED:Partial revocation;FILLED:Filled;CANCELED:Cancled;REJECTED:Order failed;EXPIRED:Expired
// "createTime": 1731231231, // CreateTime
// "clientOrderId": "204788317630342726"
// }
// }
//
let mut orders: Value = self.orders.clone();
if (orders == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[]);
orders = ArrayCacheBySymbolById::new(limit);
self.orders = orders.clone();
}
let mut order: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string2(order.clone(), Value::Str("s".into()), Value::Str("symbol".into()), &[]);
if (marketId != Value::Null) {
let mut tradeType: Value = (if (matches!(&order, Value::Dict(__d) if __d.contains_key("symbol"))) { Value::Str("contract".into()) } else { Value::Str("spot".into()) });
let mut market: Value = self.safe_market(&[marketId, Value::Null, Value::Null, tradeType.clone()]);
let mut parsed: Value = self.parse_ws_order(order, &[market]);
orders.append(parsed);
client.resolve(&[orders, Value::Str(format!("{}{}", Value::Str("order::".into()), tradeType).into())]);
}
return message;
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
//
// {
// topic: 'balance',
// event: 'balance',
// data: {
// a: 3513677381884,
// t: 1684250056775,
// c: 'usdt',
// b: '7.71000000',
// f: '0.00000000',
// z: 'SPOT'
// }
// }
//
// contract
//
// {
// "topic": "balance",
// "event": "balance@123456",
// "data": {
// "coin": "usdt",
// "underlyingType": 1, // 1:Coin-M,2:USDT-M
// "walletBalance": "123", // Balance
// "openOrderMarginFrozen": "123", // Frozen order
// "isolatedMargin": "213", // Isolated Margin
// "crossedMargin": "0" // Crossed Margin
// "availableBalance": '2.256114450000000000',
// "coupon": '0',
// "bonus": '0'
// }
// }
//
let mut data: 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 currencyId: Value = self.safe_string2(data.clone(), Value::Str("c".into()), Value::Str("coin".into()), &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut account: Value = self.account();
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_k(data.clone(), "availableBalance", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_string_k(data.clone(), "f", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string2(data.clone(), Value::Str("b".into()), Value::Str("walletBalance".into()), &[])); }
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; }
let mut tradeType: Value = (if (matches!(&data, Value::Dict(__d) if __d.contains_key("coin"))) { Value::Str("contract".into()) } else { Value::Str("spot".into()) });
client.resolve(&[self.balance.clone(), Value::Str(format!("{}{}", Value::Str("balance::".into()), tradeType).into())]);
}
pub fn handle_my_trades(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// spot
//
// {
// "topic": "trade",
// "event": "trade",
// "data": {
// "s": "btc_usdt", // symbol
// "t": 1656043204763, // time
// "i": "6316559590087251233", // tradeId
// "oi": "6216559590087220004", // orderId
// "p": "30000", // trade price
// "q": "3", // qty quantity
// "v": "90000" // volume trade amount
// }
// }
//
// contract
//
// {
// "topic": "trade",
// "event": "trade@123456",
// "data": {
// "symbol": 'btc_usdt',
// "orderSide": 'SELL',
// "positionSide": 'LONG',
// "orderId": '231485367663419328',
// "price": '27152.7',
// "quantity": '33',
// "marginUnfrozen": '2.85318000',
// "timestamp": 1684892412565
// }
// }
//
let mut data: 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 stored: Value = self.myTrades.clone();
if (stored == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
stored = ArrayCacheBySymbolById::new(limit);
self.myTrades = stored.clone();
}
let mut parsedTrade: Value = self.parse_trade(data, &[]);
let mut tradeSymbol: Value = parsedTrade.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (tradeSymbol == Value::Null) {
return;
}
let mut market: Value = self.market(tradeSymbol);
stored.append(parsedTrade);
let mut tradeType: Value = (if (market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { Value::Str("contract".into()) } else { Value::Str("spot".into()) });
client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("trade::".into()), tradeType).into())]);
}
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;
let mut event: Option<String> = (match __pro_message.get("event").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 (event.as_deref() == Some("pong")) {
client.on_pong(&[]);
} else if (event.is_some()) {
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::Null });
let mut methods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("kline".to_string(), Value::Str("handle_ohlcv".into()).clone());
m.insert("depth".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("depth_update".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("ticker".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("agg_ticker".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("tickers".to_string(), Value::Str("handle_tickers".into()).clone());
m.insert("agg_tickers".to_string(), Value::Str("handle_tickers".into()).clone());
m.insert("balance".to_string(), Value::Str("handle_balance".into()).clone());
m.insert("order".to_string(), Value::Str("handle_order".into()).clone());
m.insert("position".to_string(), Value::Str("handle_position".into()).clone());
m.insert("fund_rate".to_string(), Value::Str("handle_funding_rate".into()).clone());
m
});
let mut method: Value = (if (topic == Value::Null) { Value::Null } else { self.safe_value(methods, topic.clone(), &[]) });
if (topic.as_str() == Some("trade")) {
let mut data: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
if (data != Value::Null) && ((matches!(&data, Value::Dict(__d) if __d.contains_key("oi"))) || (matches!(&data, Value::Dict(__d) if __d.contains_key("orderId")))) {
method = Value::Str("handle_my_trades".into()).clone();
} else {
method = Value::Str("handle_trade".into()).clone();
}
}
if (method != Value::Null) {
self.dispatch_ws_handler(&method, &[client.clone(), message.clone()]);
}
} else {
self.handle_subscription_status(client, message);
}
}
pub fn ping(&self, mut client: Value) -> Value {
crate::set_value(&mut client, &Value::Str("lastPong".into()), self.milliseconds());
return Value::Str("ping".into());
Value::Null
}
pub fn handle_subscription_status(&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;
//
// {
// id: '1763045665228ticker@eth_usdt',
// code: 0,
// msg: 'SUCCESS',
// method: 'unsubscribe'
// }
//
// {
// code: 0,
// msg: 'success',
// id: '1764032903806ticker@btc_usdt',
// sessionId: '5e1597fffeb08f50-00000001-06401597-943ec6d3c64310dd-9b247bee'
// }
//
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 subscriptionsById: Value = self.index_by(get_value(&client, &Value::Str("subscriptions".into())), Value::Str("id".into()));
let mut unsubscribe: Value = Value::Bool(false);
if (id != Value::Null) {
let mut subscription: Value = self.safe_dict(subscriptionsById, id, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
unsubscribe = self.safe_bool_k(subscription.clone(), "unsubscribe", &[Value::Bool(false)]);
if (unsubscribe.as_bool() == Some(true)) {
self.handle_un_subscription(client, subscription);
}
}
return message;
Value::Null
}
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 j: Value = Value::Int(0);
let mut __for_first_670: bool = true;
while { if !__for_first_670 { 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_670 = false; j.as_f64().unwrap_or(f64::NAN) < ((messageHashes.len() as i64) as f64) } {
let mut unsubHash: 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 subHash: Value = subMessageHashes.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);
self.clean_unsubscription(client.clone(), subHash, unsubHash, &[]);
}
}
self.clean_cache(subscription);
}
pub async fn handle_error_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;
//
// {
// "id": "123",
// "code": 401,
// "msg": "token expire"
// }
//
let mut msg: Option<String> = (match __pro_message.get("msg").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 (msg.as_deref() == Some("invalid_listen_key")) || (msg.as_deref() == Some("token expire")) {
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &Value::Str("token".into()), Value::Null);
self.get_listen_key(Value::Bool(true)).await;
return;
}
client.reject(&[message]);
}
}