// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
use crate::pro::*;
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.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ws_order_trade" => self.parse_ws_order_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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.get(3..).unwrap_or(&[]).to_vec()[..]).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.get(5..).unwrap_or(&[]).to_vec()[..]).await,
"un_watch_funding_rate" => self.un_watch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"un_watch_ohlcv" => self.un_watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"un_watch_order_book" => self.un_watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"un_watch_ticker" => self.un_watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"un_watch_tickers" => self.un_watch_tickers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"un_watch_trades" => self.un_watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"watch_balance" => self.watch_balance(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"watch_funding_rate" => self.watch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"watch_my_trades" => self.watch_my_trades(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"watch_ohlcv" => self.watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"watch_orders" => self.watch_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"watch_positions" => self.watch_positions(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"watch_tickers" => self.watch_tickers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).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_str(), _ => 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.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ws_order_trade" => self.parse_ws_order_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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".to_string()));
m.insert("contract".to_string(), Value::Str("wss://fstream.xt.com/ws".to_string()));
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".to_string()));
m
}));
m.insert("watchTickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("tickers".to_string()));
m
}));
m.insert("watchPositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("swap".to_string()));
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".to_string()).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 = ternary(is_true(&isContract), Value::Str("contract".to_string()), Value::Str("spot".to_string()));
let mut url: Value = get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &tradeType);
if !is_true(&isContract) {
url = add(&url, &Value::Str("/private".to_string()));
}
let mut client: Value = self.client(&[url.clone()]);
let mut token: Value = self.safe_string(get_value(&client, &Value::Str("subscriptions".to_string())), Value::Str("token".to_string()), &[]);
if is_equal(&token, &Value::Null) {
// 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 = add(&Value::Str("authenticate:".to_string()), &tradeType);
if is_true(&Value::Bool(in_op(&get_value(&client, &Value::Str("futures".to_string())), &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(&get_value(&client, &Value::Str("subscriptions".to_string())), &Value::Str("token".to_string()));
}
// 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.clone(), "result", &[]);
listenKey = self.safe_string_k(result.clone(), "accessToken", &[]);
}
if is_equal(&listenKey, &Value::Null) {
panic!("{}", crate::exchange_errors::authentication_error(add(&self.id, &Value::Str(" getListenKey() received an empty listen key".to_string()))));
}
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &Value::Str("token".to_string()), listenKey.clone());
client.resolve(&[listenKey.clone(), 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.clone(), messageHash.clone()]);
}
crate::exchange_stubs::ws_await_flight(&future).await;
}
return get_value(&get_value(&client, &Value::Str("subscriptions".to_string())), &Value::Str("token".to_string()));
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.clone(), "nonce", &[]);
let mut firstDelta: Value = self.safe_value(cache.clone(), Value::Int(0), &[]);
let mut firstDeltaNonce: Value = self.safe_integer2(firstDelta.clone(), Value::Str("i".to_string()), Value::Str("u".to_string()), &[]);
if is_true(&(!is_equal(&nonce, &Value::Null))) && is_true(&(!is_equal(&firstDeltaNonce, &Value::Null))) && is_true(&(is_less_than(&nonce, &subtract(&firstDeltaNonce, &Value::Int(1))))) {
return negate(&Value::Int(1));
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_674: bool = true;
while { if !__for_first_674 { i = add(&i, &Value::Int(1)); } __for_first_674 = false; is_less_than(&i, &get_array_length(&cache)) } {
let mut delta: Value = get_value(&cache, &i);
let mut delta: Value = get_value(&cache, &i);
let mut deltaNonce: Value = self.safe_integer2(delta.clone(), Value::Str("i".to_string()), Value::Str("u".to_string()), &[]);
if is_true(&(!is_equal(&deltaNonce, &Value::Null))) && is_true(&(!is_equal(&nonce, &Value::Null))) && is_true(&(is_greater_than_or_equal(&deltaNonce, &nonce))) {
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".to_string()), self.safe_integer2(delta.clone(), Value::Str("i".to_string()), Value::Str("u".to_string()), &[]));
let mut obAsks: Value = self.safe_list_k(delta.clone(), "a", &[Value::List(vec![])]);
let mut obBids: Value = self.safe_list_k(delta.clone(), "b", &[Value::List(vec![])]);
let mut bids: Value = get_value(&orderbook, &Value::Str("bids".to_string()));
let mut asks: Value = get_value(&orderbook, &Value::Str("asks".to_string()));
{
let mut i: Value = Value::Int(0);
let mut __for_first_675: bool = true;
while { if !__for_first_675 { i = add(&i, &Value::Int(1)); } __for_first_675 = false; is_less_than(&i, &get_array_length(&obBids)) } {
let mut bid: Value = get_value(&obBids, &i);
let mut bid: Value = get_value(&obBids, &i);
let mut price: Value = self.safe_number(bid.clone(), Value::Int(0), &[]);
let mut quantity: Value = self.safe_number(bid.clone(), Value::Int(1), &[]);
bids.store(price.clone(), quantity.clone());
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_676: bool = true;
while { if !__for_first_676 { i = add(&i, &Value::Int(1)); } __for_first_676 = false; is_less_than(&i, &get_array_length(&obAsks)) } {
let mut ask: Value = get_value(&obAsks, &i);
let mut ask: Value = get_value(&obAsks, &i);
let mut price: Value = self.safe_number(ask.clone(), Value::Int(0), &[]);
let mut quantity: Value = self.safe_number(ask.clone(), Value::Int(1), &[]);
asks.store(price.clone(), quantity.clone());
}
}
}
/*
* @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 = is_equal(&access, &Value::Str("private".to_string()));
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(methodName.clone(), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut isContract: Value = Value::Bool(!is_equal(&type_var, &Value::Str("spot".to_string())));
let mut id: Value = add(&self.number_to_string(self.milliseconds()), &name); // call back ID
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), ternary(is_true(&isContract), Value::Str("SUBSCRIBE".to_string()), Value::Str("subscribe".to_string())));
m.insert("id".to_string(), id.clone());
m
});
if is_true(&privateAccess) {
if !is_true(&isContract) {
add_element_to_object(&mut subscribe, &Value::Str("params".to_string()), Value::List(vec![name.clone()]));
add_element_to_object(&mut subscribe, &Value::Str("listenKey".to_string()), self.get_listen_key(isContract.clone()).await);
} else {
let mut listenKey: Value = self.get_listen_key(isContract.clone()).await;
let mut param: Value = add(&add(&name, &Value::Str("@".to_string())), &listenKey);
add_element_to_object(&mut subscribe, &Value::Str("params".to_string()), Value::List(vec![param.clone()]));
}
} else {
add_element_to_object(&mut subscribe, &Value::Str("params".to_string()), Value::List(vec![name.clone()]));
}
let mut tradeType: Value = ternary(is_true(&isContract), Value::Str("contract".to_string()), Value::Str("spot".to_string()));
let mut messageHash: Value = add(&add(&name, &Value::Str("::".to_string())), &tradeType);
if !is_equal(&symbols, &Value::Null) {
messageHash = add(&add(&messageHash, &Value::Str("::".to_string())), &join(&symbols, &Value::Str(",".to_string())));
}
let mut request: Value = self.extend(subscribe.clone(), &[params.clone()]);
let mut tail: Value = access.clone();
if is_true(&isContract) {
tail = ternary(is_true(&privateAccess), Value::Str("user".to_string()), Value::Str("market".to_string()));
}
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m
});
let mut url: Value = add(&add(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &tradeType), &Value::Str("/".to_string())), &tail);
return self.watch(url.clone(), messageHash.clone(), &[request.clone(), messageHash.clone(), subscription.clone()]).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 = is_equal(&access, &Value::Str("private".to_string()));
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(methodName.clone(), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut isContract: Value = Value::Bool(!is_equal(&type_var, &Value::Str("spot".to_string())));
let mut id: Value = add(&self.number_to_string(self.milliseconds()), &name); // call back ID
let mut unsubscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), ternary(is_true(&isContract), Value::Str("UNSUBSCRIBE".to_string()), Value::Str("unsubscribe".to_string())));
m.insert("id".to_string(), id.clone());
m
});
if is_true(&privateAccess) {
if !is_true(&isContract) {
add_element_to_object(&mut unsubscribe, &Value::Str("params".to_string()), Value::List(vec![name.clone()]));
add_element_to_object(&mut unsubscribe, &Value::Str("listenKey".to_string()), self.get_listen_key(isContract.clone()).await);
} else {
let mut listenKey: Value = self.get_listen_key(isContract.clone()).await;
let mut param: Value = add(&add(&name, &Value::Str("@".to_string())), &listenKey);
add_element_to_object(&mut unsubscribe, &Value::Str("params".to_string()), Value::List(vec![param.clone()]));
}
} else {
add_element_to_object(&mut unsubscribe, &Value::Str("params".to_string()), Value::List(vec![name.clone()]));
}
let mut tradeType: Value = ternary(is_true(&isContract), Value::Str("contract".to_string()), Value::Str("spot".to_string()));
let mut subMessageHash: Value = add(&add(&name, &Value::Str("::".to_string())), &tradeType);
let mut request: Value = self.extend(unsubscribe.clone(), &[params.clone()]);
let mut tail: Value = access.clone();
if is_true(&isContract) {
tail = ternary(is_true(&privateAccess), Value::Str("user".to_string()), Value::Str("market".to_string()));
}
let mut url: Value = add(&add(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &tradeType), &Value::Str("/".to_string())), &tail);
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.clone());
m.insert("subMessageHashes".to_string(), Value::List(vec![subMessageHash.clone()]));
m.insert("messageHashes".to_string(), Value::List(vec![messageHash.clone()]));
m.insert("symbols".to_string(), symbols.clone());
m.insert("topic".to_string(), topic.clone());
m
});
let mut symbolsAndTimeframes: Value = self.safe_list_k(subscriptionParams.clone(), "symbolsAndTimeframes", &[]);
if !is_equal(&symbolsAndTimeframes, &Value::Null) {
add_element_to_object(&mut subscription, &Value::Str("symbolsAndTimeframes".to_string()), symbolsAndTimeframes.clone());
subscriptionParams = self.omit(subscriptionParams.clone(), Value::Str("symbolsAndTimeframes".to_string()), &[]);
}
let __ws_arg_0 = self.extend(request.clone(), &[params.clone()]);
let __ws_arg_1 = self.extend(subscription.clone(), &[subscriptionParams.clone()]);
return self.watch(url.clone(), 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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchTicker", &[]);
let mut defaultMethod: Value = self.safe_string_k(options.clone(), "method", &[Value::Str("ticker".to_string())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod.clone()]);
let mut name: Value = add(&add(&method, &Value::Str("@".to_string())), &get_value(&market, &Value::Str("id".to_string())));
return self.subscribe(name.clone(), Value::Str("public".to_string()), Value::Str("watchTicker".to_string()), &[market.clone(), Value::Null, params.clone()]).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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut options: Value = self.safe_dict_k(self.options.clone(), "unWatchTicker", &[]);
let mut defaultMethod: Value = self.safe_string_k(options.clone(), "method", &[Value::Str("ticker".to_string())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod.clone()]);
let mut name: Value = add(&add(&method, &Value::Str("@".to_string())), &get_value(&market, &Value::Str("id".to_string())));
let mut messageHash: Value = add(&Value::Str("unsubscribe::".to_string()), &name);
return self.un_subscribe(messageHash.clone(), name.clone(), Value::Str("public".to_string()), Value::Str("unWatchTicker".to_string()), defaultMethod.clone(), &[market.clone(), Value::Null, params.clone()]).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 is_equal(&self.markets, &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.clone(), "method", &[Value::Str("tickers".to_string())]);
let mut name: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod.clone()]);
let mut market: Value = Value::Null;
if !is_equal(&symbols, &Value::Null) {
market = self.market(get_value(&symbols, &Value::Int(0)));
}
let mut tickers: Value = self.subscribe(name.clone(), Value::Str("public".to_string()), Value::Str("watchTickers".to_string()), &[market.clone(), symbols.clone(), params.clone()]).await;
if is_true(&self.newUpdates) {
return tickers;
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".to_string()), &[symbols.clone()]);
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 is_equal(&self.markets, &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.clone(), "method", &[Value::Str("tickers".to_string())]);
let mut name: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod.clone()]);
if !is_equal(&symbols, &Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" unWatchTickers() does not support symbols argument, unsubscribtion is for all tickers at once only".to_string()))));
}
let mut messageHash: Value = add(&Value::Str("unsubscribe::".to_string()), &name);
let mut tickers: Value = self.un_subscribe(messageHash.clone(), name.clone(), Value::Str("public".to_string()), Value::Str("unWatchTickers".to_string()), Value::Str("ticker".to_string()), &[Value::Null, symbols.clone(), params.clone()]).await;
if is_true(&self.newUpdates) {
return tickers;
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".to_string()), &[symbols.clone()]);
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".to_string()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut name: Value = add(&add(&add(&Value::Str("kline@".to_string()), &get_value(&market, &Value::Str("id".to_string()))), &Value::Str(",".to_string())), &timeframe);
let mut ohlcv: Value = self.subscribe(name.clone(), Value::Str("public".to_string()), Value::Str("watchOHLCV".to_string()), &[market.clone(), Value::Null, params.clone()]).await;
if is_true(&self.newUpdates) {
limit = ohlcv.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_since_limit(ohlcv.clone(), &[since.clone(), limit.clone(), 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".to_string()));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut name: Value = add(&add(&add(&Value::Str("kline@".to_string()), &get_value(&market, &Value::Str("id".to_string()))), &Value::Str(",".to_string())), &timeframe);
let mut messageHash: Value = add(&Value::Str("unsubscribe::".to_string()), &name);
let mut symbolsAndTimeframes: Value = Value::List(vec![Value::List(vec![get_value(&market, &Value::Str("symbol".to_string())), timeframe.clone()])]);
return self.un_subscribe(messageHash.clone(), name.clone(), Value::Str("public".to_string()), Value::Str("unWatchOHLCV".to_string()), Value::Str("ohlcv".to_string()), &[market.clone(), Value::List(vec![symbol.clone()]), params.clone(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbolsAndTimeframes".to_string(), symbolsAndTimeframes.clone());
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut name: Value = add(&Value::Str("trade@".to_string()), &get_value(&market, &Value::Str("id".to_string())));
let mut trades: Value = self.subscribe(name.clone(), Value::Str("public".to_string()), Value::Str("watchTrades".to_string()), &[market.clone(), Value::Null, params.clone()]).await;
if is_true(&self.newUpdates) {
limit = trades.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_since_limit(trades.clone(), &[since.clone(), limit.clone(), Value::Str("timestamp".to_string())]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut name: Value = add(&Value::Str("trade@".to_string()), &get_value(&market, &Value::Str("id".to_string())));
let mut messageHash: Value = add(&Value::Str("unsubscribe::".to_string()), &name);
return self.un_subscribe(messageHash.clone(), name.clone(), Value::Str("public".to_string()), Value::Str("unWatchTrades".to_string()), Value::Str("trades".to_string()), &[market.clone(), Value::List(vec![symbol.clone()]), params.clone()]).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 is_equal(&self.markets, &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".to_string()), &[]);
let mut name: Value = add(&Value::Str("depth_update@".to_string()), &get_value(&market, &Value::Str("id".to_string())));
if !is_equal(&levels, &Value::Null) {
name = add(&add(&add(&Value::Str("depth@".to_string()), &get_value(&market, &Value::Str("id".to_string()))), &Value::Str(",".to_string())), &levels);
}
let mut orderbook: Value = self.subscribe(name.clone(), Value::Str("public".to_string()), Value::Str("watchOrderBook".to_string()), &[market.clone(), Value::Null, params.clone()]).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 is_equal(&self.markets, &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".to_string()), &[]);
let mut name: Value = add(&Value::Str("depth_update@".to_string()), &get_value(&market, &Value::Str("id".to_string())));
if !is_equal(&levels, &Value::Null) {
name = add(&add(&add(&Value::Str("depth@".to_string()), &get_value(&market, &Value::Str("id".to_string()))), &Value::Str(",".to_string())), &levels);
}
let mut messageHash: Value = add(&Value::Str("unsubscribe::".to_string()), &name);
return self.un_subscribe(messageHash.clone(), name.clone(), Value::Str("public".to_string()), Value::Str("unWatchOrderBook".to_string()), Value::Str("orderbook".to_string()), &[market.clone(), Value::List(vec![symbol.clone()]), params.clone()]).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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("order".to_string());
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut orders: Value = self.subscribe(name.clone(), Value::Str("private".to_string()), Value::Str("watchOrders".to_string()), &[market.clone(), Value::Null, params.clone()]).await;
if is_true(&self.newUpdates) {
limit = orders.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_since_limit(orders.clone(), &[since.clone(), limit.clone(), Value::Str("timestamp".to_string())]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("trade".to_string());
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut trades: Value = self.subscribe(name.clone(), Value::Str("private".to_string()), Value::Str("watchMyTrades".to_string()), &[market.clone(), Value::Null, params.clone()]).await;
if is_true(&self.newUpdates) {
limit = trades.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_since_limit(trades.clone(), &[since.clone(), limit.clone(), Value::Str("timestamp".to_string())]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("balance".to_string());
return self.subscribe(name.clone(), Value::Str("private".to_string()), Value::Str("watchBalance".to_string()), &[Value::Null, Value::Null, params.clone()]).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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut url: Value = add(&add(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("contract".to_string())), &Value::Str("/".to_string())), &Value::Str("user".to_string()));
let mut client: Value = self.client(&[url.clone()]);
self.set_positions_cache(client.clone());
let mut fetchPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".to_string()), Value::Str("fetchPositionsSnapshot".to_string()), &[Value::Bool(true)]);
let mut awaitPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".to_string()), Value::Str("awaitPositionsSnapshot".to_string()), &[Value::Bool(true)]);
let mut cache: Value = self.positions.clone();
if is_true(&(is_equal(&fetchPositionsSnapshot, &Value::Bool(true)))) && is_true(&(is_equal(&awaitPositionsSnapshot, &Value::Bool(true)))) && is_true(&self.is_empty(cache.clone())) {
let mut snapshot: Value = crate::exchange_stubs::ws_await_flight(&client.future(&[Value::Str("fetchPositionsSnapshot".to_string())])).await;
return self.filter_by_symbols_since_limit(snapshot.clone(), &[symbols.clone(), since.clone(), limit.clone(), Value::Bool(true)]);
}
let mut name: Value = Value::Str("position".to_string());
let mut newPositions: Value = self.subscribe(name.clone(), Value::Str("private".to_string()), Value::Str("watchPositions".to_string()), &[Value::Null, Value::Null, params.clone()]).await;
if is_true(&self.newUpdates) {
return newPositions;
}
return self.filter_by_symbols_since_limit(cache.clone(), &[symbols.clone(), since.clone(), limit.clone(), 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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if !is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" watchFundingRate() supports swap contracts only".to_string()))));
}
let mut name: Value = add(&Value::Str("fund_rate@".to_string()), &get_value(&market, &Value::Str("id".to_string())));
return self.subscribe(name.clone(), Value::Str("public".to_string()), Value::Str("watchFundingRate".to_string()), &[market.clone(), Value::Null, params.clone()]).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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if !is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" unWatchFundingRate() supports swap contracts only".to_string()))));
}
let mut name: Value = add(&Value::Str("fund_rate@".to_string()), &get_value(&market, &Value::Str("id".to_string())));
let mut messageHash: Value = add(&Value::Str("unsubscribe::".to_string()), &name);
return self.un_subscribe(messageHash.clone(), name.clone(), Value::Str("public".to_string()), Value::Str("unWatchFundingRate".to_string()), Value::Str("fund_rate".to_string()), &[market.clone(), Value::Null, params.clone()]).await;
Value::Null
}
pub fn handle_funding_rate(&mut self, mut client: Value, mut message: Value) -> Value {
//
// {
// "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 = self.safe_dict_k(message.clone(), "data", &[]);
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
if !is_equal(&marketId, &Value::Null) {
let mut raw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), marketId.clone());
m.insert("fundingRate".to_string(), self.safe_string_k(data.clone(), "r", &[]));
m
});
let mut fundingRate: Value = self.parse_funding_rate(raw.clone(), &[]);
let mut timestamp: Value = self.safe_integer_k(data.clone(), "t", &[]);
add_element_to_object(&mut fundingRate, &Value::Str("timestamp".to_string()), timestamp.clone());
add_element_to_object(&mut fundingRate, &Value::Str("datetime".to_string()), self.iso8601(timestamp.clone()));
let mut symbol: Value = get_value(&fundingRate, &Value::Str("symbol".to_string()));
add_element_to_object(&mut self.fundingRates, &symbol, fundingRate.clone());
let mut event: Value = self.safe_string_k(message.clone(), "event", &[]);
let mut messageHash: Value = add(&event, &Value::Str("::contract".to_string()));
client.resolve(&[fundingRate.clone(), messageHash.clone()]);
}
return message;
Value::Null
}
pub fn set_positions_cache(&mut self, mut client: Value) {
if is_equal(&self.positions, &Value::Null) {
self.positions = ArrayCacheBySymbolBySide::new(Value::Null);
}
let mut fetchPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".to_string()), Value::Str("fetchPositionsSnapshot".to_string()), &[]);
if is_equal(&fetchPositionsSnapshot, &Value::Bool(true)) {
let mut messageHash: Value = Value::Str("fetchPositionsSnapshot".to_string());
if !is_true(&(Value::Bool(in_op(&get_value(&client, &Value::Str("futures".to_string())), &messageHash)))) {
client.future(&[messageHash.clone()]);
self.spawn(&[Value::Str("load_positions_snapshot".to_string()).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_677: bool = true;
while { if !__for_first_677 { i = add(&i, &Value::Int(1)); } __for_first_677 = false; is_less_than(&i, &get_array_length(&positions)) } {
let mut position: Value = get_value(&positions, &i);
let mut position: Value = get_value(&positions, &i);
let mut contracts: Value = self.safe_number_k(position.clone(), "contracts", &[Value::Int(0)]);
if is_true(&(!is_equal(&contracts, &Value::Null))) && is_true(&(is_greater_than(&contracts, &Value::Int(0)))) {
cache.append(position.clone());
}
}
}
// don't remove the future from the .futures cache
if is_true(&Value::Bool(in_op(&get_value(&client, &Value::Str("futures".to_string())), &messageHash))) {
let mut future: Value = get_value(&get_value(&client, &Value::Str("futures".to_string())), &messageHash);
future.resolve(&[cache.clone()]);
client.resolve(&[cache.clone(), Value::Str("position::contract".to_string())]);
}
Value::Null
}
pub fn handle_position(&mut self, mut client: Value, mut message: Value) {
//
// {
// 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 is_equal(&self.positions, &Value::Null) {
self.positions = ArrayCacheBySymbolBySide::new(Value::Null);
}
let mut cache: Value = self.positions.clone();
let mut data: Value = self.safe_dict_k(message.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut position: Value = self.parse_position(data.clone(), &[]);
cache.append(position.clone());
let mut messageHashes: Value = self.find_message_hashes(client.clone(), Value::Str("position::contract".to_string()));
{
let mut i: Value = Value::Int(0);
let mut __for_first_678: bool = true;
while { if !__for_first_678 { i = add(&i, &Value::Int(1)); } __for_first_678 = false; is_less_than(&i, &get_array_length(&messageHashes)) } {
let mut messageHash: Value = get_value(&messageHashes, &i);
let mut messageHash: Value = get_value(&messageHashes, &i);
let mut parts: Value = split(&messageHash, &Value::Str("::".to_string()));
let mut symbolsString: Value = get_value(&parts, &Value::Int(1));
let mut symbols: Value = split(&symbolsString, &Value::Str(",".to_string()));
let mut positions: Value = self.filter_by_array(Value::List(vec![position.clone()]), Value::Str("symbol".to_string()), &[symbols.clone(), Value::Bool(false)]);
if !is_true(&self.is_empty(positions.clone())) {
client.resolve(&[positions.clone(), messageHash.clone()]);
}
}
}
client.resolve(&[Value::List(vec![position.clone()]), Value::Str("position::contract".to_string())]);
}
pub fn handle_ticker(&mut self, mut client: Value, mut message: Value) -> Value {
//
// 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 = self.safe_dict_k(message.clone(), "data", &[]);
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
if !is_equal(&marketId, &Value::Null) {
let mut cv: Value = self.safe_string_k(data.clone(), "cv", &[]);
let mut isSpot: bool = !is_equal(&cv, &Value::Null);
let mut ticker: Value = self.parse_ticker(data.clone(), &[]);
let mut symbol: Value = get_value(&ticker, &Value::Str("symbol".to_string()));
if !is_equal(&symbol, &Value::Null) {
add_element_to_object(&mut self.tickers, &symbol, ticker.clone());
}
let mut event: Value = self.safe_string_k(message.clone(), "event", &[]);
let mut messageHashTail: Value = ternary(is_true(&isSpot), Value::Str("spot".to_string()), Value::Str("contract".to_string()));
let mut messageHash: Value = add(&add(&event, &Value::Str("::".to_string())), &messageHashTail);
client.resolve(&[ticker.clone(), messageHash.clone()]);
}
return message;
Value::Null
}
pub fn handle_tickers(&mut self, mut client: Value, mut message: Value) -> Value {
//
// 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 = self.safe_list_k(message.clone(), "data", &[Value::List(vec![])]);
let mut firstTicker: Value = self.safe_dict(data.clone(), Value::Int(0), &[]);
let mut spotTest: Value = self.safe_string2(firstTicker.clone(), Value::Str("cv".to_string()), Value::Str("aq".to_string()), &[]);
let mut tradeType: Value = ternary(is_true(&(!is_equal(&spotTest, &Value::Null))), Value::Str("spot".to_string()), Value::Str("contract".to_string()));
let mut newTickers: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_679: bool = true;
while { if !__for_first_679 { i = add(&i, &Value::Int(1)); } __for_first_679 = false; is_less_than(&i, &get_array_length(&data)) } {
let mut tickerData: Value = get_value(&data, &i);
let mut tickerData: Value = get_value(&data, &i);
let mut ticker: Value = self.parse_ticker(tickerData.clone(), &[]);
let mut symbol: Value = get_value(&ticker, &Value::Str("symbol".to_string()));
if !is_equal(&symbol, &Value::Null) {
add_element_to_object(&mut self.tickers, &symbol, ticker.clone());
}
append_to_array(&mut newTickers, ticker.clone());
}
}
let mut messageHashStart: Value = add(&add(&self.safe_string_k(message.clone(), "topic", &[]), &Value::Str("::".to_string())), &tradeType);
let mut messageHashes: Value = self.find_message_hashes(client.clone(), add(&messageHashStart, &Value::Str("::".to_string())));
{
let mut i: Value = Value::Int(0);
let mut __for_first_680: bool = true;
while { if !__for_first_680 { i = add(&i, &Value::Int(1)); } __for_first_680 = false; is_less_than(&i, &get_array_length(&messageHashes)) } {
let mut messageHash: Value = get_value(&messageHashes, &i);
let mut messageHash: Value = get_value(&messageHashes, &i);
let mut parts: Value = split(&messageHash, &Value::Str("::".to_string()));
let mut symbolsString: Value = get_value(&parts, &Value::Int(2));
let mut symbols: Value = split(&symbolsString, &Value::Str(",".to_string()));
let mut tickers: Value = self.filter_by_array(newTickers.clone(), Value::Str("symbol".to_string()), &[symbols.clone()]);
let mut tickersSymbols: Value = object_keys(&tickers);
let mut numTickers: Value = get_array_length(&tickersSymbols);
if is_greater_than(&numTickers, &Value::Int(0)) {
client.resolve(&[tickers.clone(), messageHash.clone()]);
}
}
}
client.resolve(&[self.tickers.clone(), messageHashStart.clone()]);
return message;
Value::Null
}
pub fn handle_ohlcv(&mut self, mut client: Value, mut message: Value) -> Value {
//
// 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 = self.safe_dict_k(message.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
if !is_equal(&marketId, &Value::Null) {
let mut timeframe: Value = self.safe_string_k(data.clone(), "i", &[Value::Str("".to_string())]);
let mut tradeType: Value = ternary(is_true(&(Value::Bool(in_op(&data, &Value::Str("q".to_string()))))), Value::Str("spot".to_string()), Value::Str("contract".to_string()));
let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, Value::Null, tradeType.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut parsed: Value = self.parse_ohlcv(data.clone(), &[market.clone()]);
{ let __be_tmp = self.safe_dict(self.ohlcvs.clone(), symbol.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); add_element_to_object(&mut self.ohlcvs, &symbol, __be_tmp); };
let mut stored: Value = self.safe_value(get_value(&self.ohlcvs, &symbol), timeframe.clone(), &[]);
if is_equal(&stored, &Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "OHLCVLimit", &[Value::Int(1000)]);
stored = ArrayCacheByTimestamp::new(limit.clone());
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.ohlcvs) }, &symbol), &timeframe, stored.clone());
}
stored.append(parsed.clone());
let mut event: Value = self.safe_string_k(message.clone(), "event", &[]);
let mut messageHash: Value = add(&add(&event, &Value::Str("::".to_string())), &tradeType);
client.resolve(&[stored.clone(), messageHash.clone()]);
}
return message;
Value::Null
}
pub fn handle_trade(&mut self, mut client: Value, mut message: Value) -> Value {
//
// 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 = self.safe_dict_k(message.clone(), "data", &[]);
let mut marketId: Value = self.safe_string_lower(data.clone(), Value::Str("s".to_string()), &[]);
if !is_equal(&marketId, &Value::Null) {
let mut trade: Value = self.parse_trade(data.clone(), &[]);
let mut i: Value = self.safe_string_k(data.clone(), "i", &[]);
let mut tradeType: Value = ternary(is_true(&(!is_equal(&i, &Value::Null))), Value::Str("spot".to_string()), Value::Str("contract".to_string()));
let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, Value::Null, tradeType.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut event: Value = self.safe_string_k(message.clone(), "event", &[]);
let mut tradesArray: Value = self.safe_value(self.trades.clone(), symbol.clone(), &[]);
if is_equal(&tradesArray, &Value::Null) {
let mut tradesLimit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
tradesArray = ArrayCache::new(tradesLimit.clone());
add_element_to_object(&mut self.trades, &symbol, tradesArray.clone());
}
tradesArray.append(trade.clone());
let mut messageHash: Value = add(&add(&event, &Value::Str("::".to_string())), &tradeType);
client.resolve(&[tradesArray.clone(), messageHash.clone()]);
}
return message;
Value::Null
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value) {
//
// 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 = self.safe_dict_k(message.clone(), "data", &[]);
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
if !is_equal(&marketId, &Value::Null) {
let mut event: Value = self.safe_string_k(message.clone(), "event", &[Value::Str("".to_string())]);
let mut splitEvent: Value = split(&event, &Value::Str(",".to_string()));
event = self.safe_string(splitEvent.clone(), Value::Int(0), &[Value::Str("".to_string())]);
let mut tradeType: Value = Value::Str("spot".to_string());
if is_true(&(!is_equal(&data, &Value::Null))) && is_true(&(Value::Bool(in_op(&data, &Value::Str("fu".to_string()))))) {
tradeType = Value::Str("contract".to_string());
}
let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, Value::Null, tradeType.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
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 = add(&add(&event, &Value::Str("::".to_string())), &tradeType);
if !is_true(&(Value::Bool(in_op(&self.orderbooks, &symbol)))) {
let mut subscription: Value = self.safe_dict(get_value(&client, &Value::Str("subscriptions".to_string())), messageHash.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut limit: Value = self.safe_integer_k(subscription.clone(), "limit", &[]);
{ let __be_tmp = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), limit.clone()]); add_element_to_object(&mut self.orderbooks, &symbol, __be_tmp); };
}
let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
let mut nonce: Value = self.safe_integer_k(orderbook.clone(), "nonce", &[]);
if is_equal(&nonce, &Value::Null) {
let mut cacheLength: Value = get_array_length(&get_value(&orderbook, &Value::Str("cache".to_string())));
let mut snapshotDelay: Value = self.handle_option(Value::Str("watchOrderBook".to_string()), Value::Str("snapshotDelay".to_string()), &[Value::Int(25)]);
if is_equal(&cacheLength, &snapshotDelay) {
self.spawn(&[Value::Str("load_order_book".to_string()).clone(), client.clone(), messageHash.clone(), symbol.clone()]);
}
crate::runtime::append_to_object_array(&mut orderbook, &Value::Str("cache".to_string()), data.clone());
return;
}
if !is_equal(&obAsks, &Value::Null) {
let mut asks: Value = get_value(&orderbook, &Value::Str("asks".to_string()));
{
let mut i: Value = Value::Int(0);
let mut __for_first_681: bool = true;
while { if !__for_first_681 { i = add(&i, &Value::Int(1)); } __for_first_681 = false; is_less_than(&i, &get_array_length(&obAsks)) } {
let mut ask: Value = get_value(&obAsks, &i);
let mut ask: Value = get_value(&obAsks, &i);
let mut price: Value = self.safe_number(ask.clone(), Value::Int(0), &[]);
let mut quantity: Value = self.safe_number(ask.clone(), Value::Int(1), &[]);
asks.store(price.clone(), quantity.clone());
}
}
}
if !is_equal(&obBids, &Value::Null) {
let mut bids: Value = get_value(&orderbook, &Value::Str("bids".to_string()));
{
let mut i: Value = Value::Int(0);
let mut __for_first_682: bool = true;
while { if !__for_first_682 { i = add(&i, &Value::Int(1)); } __for_first_682 = false; is_less_than(&i, &get_array_length(&obBids)) } {
let mut bid: Value = get_value(&obBids, &i);
let mut bid: Value = get_value(&obBids, &i);
let mut price: Value = self.safe_number(bid.clone(), Value::Int(0), &[]);
let mut quantity: Value = self.safe_number(bid.clone(), Value::Int(1), &[]);
bids.store(price.clone(), quantity.clone());
}
}
}
let mut timestamp: Value = self.safe_integer_k(data.clone(), "t", &[]);
add_element_to_object(&mut orderbook, &Value::Str("nonce".to_string()), self.safe_integer2(data.clone(), Value::Str("i".to_string()), Value::Str("u".to_string()), &[]));
add_element_to_object(&mut orderbook, &Value::Str("timestamp".to_string()), timestamp.clone());
add_element_to_object(&mut orderbook, &Value::Str("datetime".to_string()), self.iso8601(timestamp.clone()));
add_element_to_object(&mut orderbook, &Value::Str("symbol".to_string()), symbol.clone());
client.resolve(&[orderbook.clone(), messageHash.clone()]);
}
}
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 = ternary(is_true(&(Value::Bool(in_op(&trade, &Value::Str("symbol".to_string()))))), Value::Str("contract".to_string()), Value::Str("spot".to_string()));
market = self.safe_market(&[marketId.clone(), market.clone(), Value::Null, tradeType.clone()]);
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.clone()));
m.insert("symbol".to_string(), get_value(&market, &Value::Str("symbol".to_string())));
m.insert("order".to_string(), self.safe_string_k(trade.clone(), "i", &[Value::Str("orderId".to_string())]));
m.insert("type".to_string(), self.parent.parse_order_status(self.safe_string_k(trade.clone(), "st", &[Value::Str("state".to_string())])));
m.insert("side".to_string(), self.safe_string_lower(trade.clone(), Value::Str("sd".to_string()), &[Value::Str("orderSide".to_string())]));
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.clone(), "f", &[]));
m.insert("rate".to_string(), Value::Null);
m
}));
m
}), &[market.clone()]);
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".to_string()), Value::Str("symbol".to_string()), &[]);
let mut tradeType: Value = ternary(is_true(&(Value::Bool(in_op(&order, &Value::Str("symbol".to_string()))))), Value::Str("contract".to_string()), Value::Str("spot".to_string()));
market = self.safe_market(&[marketId.clone(), market.clone(), Value::Null, tradeType.clone()]);
let mut timestamp: Value = self.safe_integer2(order.clone(), Value::Str("ct".to_string()), Value::Str("createTime".to_string()), &[]);
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".to_string()), Value::Str("orderId".to_string()), &[]));
m.insert("clientOrderId".to_string(), self.safe_string2(order.clone(), Value::Str("ci".to_string()), Value::Str("clientOrderId".to_string()), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("symbol".to_string(), get_value(&market, &Value::Str("symbol".to_string())));
m.insert("type".to_string(), get_value(&market, &Value::Str("type".to_string())));
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".to_string()), Value::Str("orderSide".to_string()), &[]));
m.insert("price".to_string(), self.safe_number2(order.clone(), Value::Str("p".to_string()), Value::Str("price".to_string()), &[]));
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".to_string()), Value::Str("origQty".to_string()), &[]));
m.insert("filled".to_string(), self.safe_string2(order.clone(), Value::Str("eq".to_string()), Value::Str("executedQty".to_string()), &[]));
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".to_string()), Value::Str("avgPrice".to_string()), &[]));
m.insert("status".to_string(), self.parent.parse_order_status(self.safe_string_k(order.clone(), "st", &[Value::Str("state".to_string())])));
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.clone(), "f", &[]));
m
}));
m.insert("trades".to_string(), Value::Null);
m
}), &[market.clone()]);
Value::Null
}
pub fn handle_order(&mut self, mut client: Value, mut message: Value) -> Value {
//
// 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 is_equal(&orders, &Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[]);
orders = ArrayCacheBySymbolById::new(limit.clone());
self.orders = orders.clone();
}
let mut order: Value = self.safe_dict_k(message.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketId: Value = self.safe_string2(order.clone(), Value::Str("s".to_string()), Value::Str("symbol".to_string()), &[]);
if !is_equal(&marketId, &Value::Null) {
let mut tradeType: Value = ternary(is_true(&(Value::Bool(in_op(&order, &Value::Str("symbol".to_string()))))), Value::Str("contract".to_string()), Value::Str("spot".to_string()));
let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, Value::Null, tradeType.clone()]);
let mut parsed: Value = self.parse_ws_order(order.clone(), &[market.clone()]);
orders.append(parsed.clone());
client.resolve(&[orders.clone(), add(&Value::Str("order::".to_string()), &tradeType)]);
}
return message;
Value::Null
}
pub fn handle_balance(&mut self, mut client: Value, mut message: Value) {
//
// 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 = self.safe_dict_k(message.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut currencyId: Value = self.safe_string2(data.clone(), Value::Str("c".to_string()), Value::Str("coin".to_string()), &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut account: Value = self.account();
add_element_to_object(&mut account, &Value::Str("free".to_string()), self.safe_string_k(data.clone(), "availableBalance", &[]));
add_element_to_object(&mut account, &Value::Str("used".to_string()), self.safe_string_k(data.clone(), "f", &[]));
add_element_to_object(&mut account, &Value::Str("total".to_string()), self.safe_string2(data.clone(), Value::Str("b".to_string()), Value::Str("walletBalance".to_string()), &[]));
if !is_equal(&code, &Value::Null) {
add_element_to_object(&mut self.balance, &code, account.clone());
}
{ let __t = self.safe_balance(self.balance.clone()); self.balance = __t; }
let mut tradeType: Value = ternary(is_true(&(Value::Bool(in_op(&data, &Value::Str("coin".to_string()))))), Value::Str("contract".to_string()), Value::Str("spot".to_string()));
client.resolve(&[self.balance.clone(), add(&Value::Str("balance::".to_string()), &tradeType)]);
}
pub fn handle_my_trades(&mut self, mut client: Value, mut message: Value) {
//
// 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 = self.safe_dict_k(message.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut stored: Value = self.myTrades.clone();
if is_equal(&stored, &Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
stored = ArrayCacheBySymbolById::new(limit.clone());
self.myTrades = stored.clone();
}
let mut parsedTrade: Value = self.parse_trade(data.clone(), &[]);
let mut tradeSymbol: Value = get_value(&parsedTrade, &Value::Str("symbol".to_string()));
if is_equal(&tradeSymbol, &Value::Null) {
return;
}
let mut market: Value = self.market(tradeSymbol.clone());
stored.append(parsedTrade.clone());
let mut tradeType: Value = ternary(is_true(&(is_equal(&get_value(&market, &Value::Str("contract".to_string())), &Value::Bool(true)))), Value::Str("contract".to_string()), Value::Str("spot".to_string()));
client.resolve(&[stored.clone(), add(&Value::Str("trade::".to_string()), &tradeType)]);
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
let mut event: Value = self.safe_string_k(message.clone(), "event", &[]);
if is_equal(&event, &Value::Str("pong".to_string())) {
client.on_pong(&[]);
} else if !is_equal(&event, &Value::Null) {
let mut topic: Value = self.safe_string_k(message.clone(), "topic", &[]);
let mut methods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("kline".to_string(), Value::Str("handle_ohlcv".to_string()).clone());
m.insert("depth".to_string(), Value::Str("handle_order_book".to_string()).clone());
m.insert("depth_update".to_string(), Value::Str("handle_order_book".to_string()).clone());
m.insert("ticker".to_string(), Value::Str("handle_ticker".to_string()).clone());
m.insert("agg_ticker".to_string(), Value::Str("handle_ticker".to_string()).clone());
m.insert("tickers".to_string(), Value::Str("handle_tickers".to_string()).clone());
m.insert("agg_tickers".to_string(), Value::Str("handle_tickers".to_string()).clone());
m.insert("balance".to_string(), Value::Str("handle_balance".to_string()).clone());
m.insert("order".to_string(), Value::Str("handle_order".to_string()).clone());
m.insert("position".to_string(), Value::Str("handle_position".to_string()).clone());
m.insert("fund_rate".to_string(), Value::Str("handle_funding_rate".to_string()).clone());
m
});
let mut method: Value = ternary(is_true(&(is_equal(&topic, &Value::Null))), Value::Null, self.safe_value(methods.clone(), topic.clone(), &[]));
if is_equal(&topic, &Value::Str("trade".to_string())) {
let mut data: Value = self.safe_dict_k(message.clone(), "data", &[]);
if is_true(&(!is_equal(&data, &Value::Null))) && is_true(&(is_true(&(Value::Bool(in_op(&data, &Value::Str("oi".to_string()))))) || is_true(&(Value::Bool(in_op(&data, &Value::Str("orderId".to_string()))))))) {
method = Value::Str("handle_my_trades".to_string()).clone();
} else {
method = Value::Str("handle_trade".to_string()).clone();
}
}
if !is_equal(&method, &Value::Null) {
self.dispatch_ws_handler(&method, &[client.clone(), message.clone()]);
}
} else {
self.handle_subscription_status(client.clone(), message.clone());
}
}
pub fn ping(&self, mut client: Value) -> Value {
crate::set_value(&mut client, &Value::Str("lastPong".to_string()), self.milliseconds());
return Value::Str("ping".to_string());
Value::Null
}
pub fn handle_subscription_status(&mut self, mut client: Value, mut message: Value) -> Value {
//
// {
// 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 = self.safe_string_k(message.clone(), "id", &[]);
let mut subscriptionsById: Value = self.index_by(get_value(&client, &Value::Str("subscriptions".to_string())), Value::Str("id".to_string()));
let mut unsubscribe: Value = Value::Bool(false);
if !is_equal(&id, &Value::Null) {
let mut subscription: Value = self.safe_dict(subscriptionsById.clone(), id.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
unsubscribe = self.safe_bool_k(subscription.clone(), "unsubscribe", &[Value::Bool(false)]);
if is_equal(&unsubscribe, &Value::Bool(true)) {
self.handle_un_subscription(client.clone(), subscription.clone());
}
}
return message;
Value::Null
}
pub fn handle_un_subscription(&mut self, mut client: Value, mut subscription: Value) {
let mut messageHashes: Value = self.safe_list_k(subscription.clone(), "messageHashes", &[Value::List(vec![])]);
let mut subMessageHashes: Value = self.safe_list_k(subscription.clone(), "subMessageHashes", &[Value::List(vec![])]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_683: bool = true;
while { if !__for_first_683 { j = add(&j, &Value::Int(1)); } __for_first_683 = false; is_less_than(&j, &get_array_length(&messageHashes)) } {
let mut unsubHash: Value = get_value(&messageHashes, &j);
let mut unsubHash: Value = get_value(&messageHashes, &j);
let mut subHash: Value = get_value(&subMessageHashes, &j);
let mut subHash: Value = get_value(&subMessageHashes, &j);
self.clean_unsubscription(client.clone(), subHash.clone(), unsubHash.clone(), &[]);
}
}
self.clean_cache(subscription.clone());
}
pub async fn handle_error_message(&mut self, mut client: Value, mut message: Value) {
//
// {
// "id": "123",
// "code": 401,
// "msg": "token expire"
// }
//
let mut msg: Value = self.safe_string_k(message.clone(), "msg", &[]);
if is_true(&(is_equal(&msg, &Value::Str("invalid_listen_key".to_string())))) || is_true(&(is_equal(&msg, &Value::Str("token expire".to_string())))) {
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &Value::Str("token".to_string()), Value::Null);
self.get_listen_key(Value::Bool(true)).await;
return;
}
client.reject(&[message.clone()]);
}
}