#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
use crate::pro::*;
pub struct BinanceCore {
pub parent: crate::exchanges::binance::BinanceCore,
}
impl BinanceCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::binance::BinanceCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = BinanceCore::describe(self);
self.initialize_properties(described);
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self);
}
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for BinanceCore {
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 BinanceCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"authenticate" => self.authenticate(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_all_orders_ws" => self.cancel_all_orders_ws(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_order_ws" => self.cancel_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"create_order_ws" => self.create_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"describe_data" => self.describe_data(),
"edit_order_ws" => self.edit_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"ensure_user_data_stream_ws_subscribe_listen_token" => self.ensure_user_data_stream_ws_subscribe_listen_token(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"ensure_user_data_stream_ws_subscribe_signature" => self.ensure_user_data_stream_ws_subscribe_signature(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_balance_ws" => self.fetch_balance_ws(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_closed_orders_ws" => self.fetch_closed_orders_ws(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_my_trades_ws" => self.fetch_my_trades_ws(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ohlcv_ws" => self.fetch_ohlcv_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_open_orders_ws" => self.fetch_open_orders_ws(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order_book_snapshot" => self.fetch_order_book_snapshot(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_order_book_ws" => self.fetch_order_book_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order_ws" => self.fetch_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_orders_ws" => self.fetch_orders_ws(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_position_ws" => self.fetch_position_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_positions_ws" => self.fetch_positions_ws(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ticker_ws" => self.fetch_ticker_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_trades_ws" => self.fetch_trades_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"get_account_type_from_subscriptions" => self.get_account_type_from_subscriptions(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_future_ws_category" => self.get_future_ws_category(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_market_type" => self.get_market_type(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]),
"get_private_ws_url" => self.get_private_ws_url(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"get_stock_ticker_from_symbol" => self.get_stock_ticker_from_symbol(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_stock_unified_symbol" => self.get_stock_unified_symbol(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"get_stock_ws_url" => self.get_stock_ws_url(&args.get(0..).unwrap_or(&[]).to_vec()[..]),
"get_ws_url" => self.get_ws_url(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book_message" => self.handle_order_book_message(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)),
"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)),
"is_spot_url" => self.is_spot_url(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"keep_alive_listen_key" => self.keep_alive_listen_key(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"load_balance_snapshot" => self.load_balance_snapshot(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null)).await,
"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), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null)).await,
"parse_ws_liquidation" => self.parse_ws_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ws_options_position" => self.parse_ws_options_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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_position" => self.parse_ws_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ws_ticker" => self.parse_ws_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_ws_trade" => self.parse_ws_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"renew_listen_token" => self.renew_listen_token(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"request_id" => self.request_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"resolve_auth_type" => self.resolve_auth_type(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"sign_params" => self.sign_params(&args.get(0..).unwrap_or(&[]).to_vec()[..]),
"stream" => self.stream(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]),
"un_watch_bids_asks" => self.un_watch_bids_asks(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"un_watch_mark_price" => self.un_watch_mark_price(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"un_watch_mark_prices" => self.un_watch_mark_prices(&args.get(0..).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_ohlcv_for_symbols" => self.un_watch_ohlcv_for_symbols(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_order_book_for_symbols" => self.un_watch_order_book_for_symbols(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,
"un_watch_trades_for_symbols" => self.un_watch_trades_for_symbols(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_bids_asks" => self.watch_bids_asks(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"watch_liquidations" => self.watch_liquidations(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"watch_liquidations_for_symbols" => self.watch_liquidations_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"watch_mark_price" => self.watch_mark_price(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"watch_mark_prices" => self.watch_mark_prices(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"watch_multi_ticker_helper" => self.watch_multi_ticker_helper(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"watch_my_liquidations" => self.watch_my_liquidations(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"watch_my_liquidations_for_symbols" => self.watch_my_liquidations_for_symbols(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_ohlcv_for_symbols" => self.watch_ohlcv_for_symbols(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_order_book_for_symbols" => self.watch_order_book_for_symbols(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_stock_market_stream" => self.watch_stock_market_stream(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"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,
"watch_trades_for_symbols" => self.watch_trades_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
_ => crate::exchange_generated::ExchangeBase::call_dynamic(&mut self.parent, method, args).await,
}
})
}
}
impl BinanceCore {
#[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 {
"authenticate" => { crate::exchange_stubs::enqueue_spawn("authenticate", args.to_vec()); crate::Value::Null },
"cancel_all_orders_ws" => { crate::exchange_stubs::enqueue_spawn("cancel_all_orders_ws", args.to_vec()); crate::Value::Null },
"cancel_order_ws" => { crate::exchange_stubs::enqueue_spawn("cancel_order_ws", args.to_vec()); crate::Value::Null },
"create_order_ws" => { crate::exchange_stubs::enqueue_spawn("create_order_ws", args.to_vec()); crate::Value::Null },
"describe_data" => self.describe_data(),
"edit_order_ws" => { crate::exchange_stubs::enqueue_spawn("edit_order_ws", args.to_vec()); crate::Value::Null },
"ensure_user_data_stream_ws_subscribe_listen_token" => { crate::exchange_stubs::enqueue_spawn("ensure_user_data_stream_ws_subscribe_listen_token", args.to_vec()); crate::Value::Null },
"ensure_user_data_stream_ws_subscribe_signature" => { crate::exchange_stubs::enqueue_spawn("ensure_user_data_stream_ws_subscribe_signature", args.to_vec()); crate::Value::Null },
"fetch_balance_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_balance_ws", args.to_vec()); crate::Value::Null },
"fetch_closed_orders_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_closed_orders_ws", args.to_vec()); crate::Value::Null },
"fetch_my_trades_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_my_trades_ws", args.to_vec()); crate::Value::Null },
"fetch_ohlcv_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_ohlcv_ws", args.to_vec()); crate::Value::Null },
"fetch_open_orders_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_open_orders_ws", args.to_vec()); crate::Value::Null },
"fetch_order_book_snapshot" => { crate::exchange_stubs::enqueue_spawn("fetch_order_book_snapshot", args.to_vec()); crate::Value::Null },
"fetch_order_book_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_order_book_ws", args.to_vec()); crate::Value::Null },
"fetch_order_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_order_ws", args.to_vec()); crate::Value::Null },
"fetch_orders_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_orders_ws", args.to_vec()); crate::Value::Null },
"fetch_position_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_position_ws", args.to_vec()); crate::Value::Null },
"fetch_positions_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_positions_ws", args.to_vec()); crate::Value::Null },
"fetch_ticker_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_ticker_ws", args.to_vec()); crate::Value::Null },
"fetch_trades_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_trades_ws", args.to_vec()); crate::Value::Null },
"get_account_type_from_subscriptions" => self.get_account_type_from_subscriptions(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_future_ws_category" => self.get_future_ws_category(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_market_type" => self.get_market_type(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]),
"get_private_ws_url" => self.get_private_ws_url(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"get_stock_ticker_from_symbol" => self.get_stock_ticker_from_symbol(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_stock_unified_symbol" => self.get_stock_unified_symbol(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"get_stock_ws_url" => self.get_stock_ws_url(&args.get(0..).unwrap_or(&[]).to_vec()[..]),
"get_ws_url" => self.get_ws_url(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_account_status_ws" => { self.handle_account_status_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_acount_update" => { self.handle_acount_update(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_balance" => { self.handle_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_balance_ws" => { self.handle_balance_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_bids_asks" => { self.handle_bids_asks(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_delta" => { self.handle_delta(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_deltas" => { self.handle_deltas(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_edit_order_ws" => { self.handle_edit_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_event_stream_terminated" => { self.handle_event_stream_terminated(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_fetch_ohlcv" => { self.handle_fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_fetch_order_book" => { self.handle_fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_liquidation" => { self.handle_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_mark_prices" => { self.handle_mark_prices(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); 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_liquidation" => { self.handle_my_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_my_trade" => { self.handle_my_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_ohlcv" => { self.handle_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_options_account_update" => { self.handle_options_account_update(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_options_order_update" => { self.handle_options_order_update(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order" => { self.handle_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book" => { self.handle_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book_message" => self.handle_order_book_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null)),
"handle_order_book_subscription" => { self.handle_order_book_subscription(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_update" => { self.handle_order_update(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_ws" => { self.handle_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_orders_ws" => { self.handle_orders_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_positions" => { self.handle_positions(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_positions_ws" => { self.handle_positions_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_stock_price" => { self.handle_stock_price(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_stock_quote" => { self.handle_stock_quote(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_ws" => { self.handle_ticker_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); 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)); crate::Value::Null },
"handle_tickers_and_bids_asks" => { self.handle_tickers_and_bids_asks(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_trade" => { self.handle_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_trades_ws" => { self.handle_trades_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); 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 },
"handle_user_data_stream_subscribe" => { self.handle_user_data_stream_subscribe(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_ws_error" => { self.handle_ws_error(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"is_spot_url" => self.is_spot_url(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"keep_alive_listen_key" => { crate::exchange_stubs::enqueue_spawn("keep_alive_listen_key", args.to_vec()); crate::Value::Null },
"load_balance_snapshot" => { crate::exchange_stubs::enqueue_spawn("load_balance_snapshot", args.to_vec()); crate::Value::Null },
"load_positions_snapshot" => { crate::exchange_stubs::enqueue_spawn("load_positions_snapshot", args.to_vec()); crate::Value::Null },
"parse_ws_liquidation" => self.parse_ws_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ws_options_position" => self.parse_ws_options_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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_position" => self.parse_ws_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ws_ticker" => self.parse_ws_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_ws_trade" => self.parse_ws_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"renew_listen_token" => { crate::exchange_stubs::enqueue_spawn("renew_listen_token", args.to_vec()); crate::Value::Null },
"request_id" => self.request_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"resolve_auth_type" => self.resolve_auth_type(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"set_balance_cache" => { self.set_balance_cache(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]); crate::Value::Null },
"set_positions_cache" => { self.set_positions_cache(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]); crate::Value::Null },
"sign_params" => self.sign_params(&args.get(0..).unwrap_or(&[]).to_vec()[..]),
"stream" => self.stream(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]),
"un_watch_bids_asks" => { crate::exchange_stubs::enqueue_spawn("un_watch_bids_asks", args.to_vec()); crate::Value::Null },
"un_watch_mark_price" => { crate::exchange_stubs::enqueue_spawn("un_watch_mark_price", args.to_vec()); crate::Value::Null },
"un_watch_mark_prices" => { crate::exchange_stubs::enqueue_spawn("un_watch_mark_prices", 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_ohlcv_for_symbols" => { crate::exchange_stubs::enqueue_spawn("un_watch_ohlcv_for_symbols", 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_order_book_for_symbols" => { crate::exchange_stubs::enqueue_spawn("un_watch_order_book_for_symbols", 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 },
"un_watch_trades_for_symbols" => { crate::exchange_stubs::enqueue_spawn("un_watch_trades_for_symbols", args.to_vec()); crate::Value::Null },
"watch_balance" => { crate::exchange_stubs::enqueue_spawn("watch_balance", args.to_vec()); crate::Value::Null },
"watch_bids_asks" => { crate::exchange_stubs::enqueue_spawn("watch_bids_asks", args.to_vec()); crate::Value::Null },
"watch_liquidations" => { crate::exchange_stubs::enqueue_spawn("watch_liquidations", args.to_vec()); crate::Value::Null },
"watch_liquidations_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_liquidations_for_symbols", args.to_vec()); crate::Value::Null },
"watch_mark_price" => { crate::exchange_stubs::enqueue_spawn("watch_mark_price", args.to_vec()); crate::Value::Null },
"watch_mark_prices" => { crate::exchange_stubs::enqueue_spawn("watch_mark_prices", args.to_vec()); crate::Value::Null },
"watch_multi_ticker_helper" => { crate::exchange_stubs::enqueue_spawn("watch_multi_ticker_helper", args.to_vec()); crate::Value::Null },
"watch_my_liquidations" => { crate::exchange_stubs::enqueue_spawn("watch_my_liquidations", args.to_vec()); crate::Value::Null },
"watch_my_liquidations_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_my_liquidations_for_symbols", 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_ohlcv_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_ohlcv_for_symbols", args.to_vec()); crate::Value::Null },
"watch_order_book" => { crate::exchange_stubs::enqueue_spawn("watch_order_book", args.to_vec()); crate::Value::Null },
"watch_order_book_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_order_book_for_symbols", 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_stock_market_stream" => { crate::exchange_stubs::enqueue_spawn("watch_stock_market_stream", 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 },
"watch_trades_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_trades_for_symbols", args.to_vec()); crate::Value::Null },
_ => crate::Value::Null,
}
}
}
impl std::ops::Deref for BinanceCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for BinanceCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl BinanceCore {
pub fn describe(&self) -> Value {
let mut superDescribe: Value = self.parent.describe();
return self.deep_extend(superDescribe.clone(), &[self.describe_data()]);
Value::Null
}
pub fn describe_data(&self) -> Value {
return 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("watchBalance".to_string(), Value::Bool(true));
m.insert("watchLiquidations".to_string(), Value::Bool(true));
m.insert("watchLiquidationsForSymbols".to_string(), Value::Bool(true));
m.insert("watchMyLiquidations".to_string(), Value::Bool(true));
m.insert("watchMyLiquidationsForSymbols".to_string(), Value::Bool(true));
m.insert("watchBidsAsks".to_string(), Value::Bool(true));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchOHLCV".to_string(), Value::Bool(true));
m.insert("watchOHLCVForSymbols".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOrderBookForSymbols".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchOrdersForSymbols".to_string(), Value::Bool(true));
m.insert("watchPositions".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(true));
m.insert("watchMarkPrices".to_string(), Value::Bool(true));
m.insert("watchMarkPrice".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m.insert("watchTradesForSymbols".to_string(), Value::Bool(true));
m.insert("createOrderWs".to_string(), Value::Bool(true));
m.insert("editOrderWs".to_string(), Value::Bool(true));
m.insert("cancelOrderWs".to_string(), Value::Bool(true));
m.insert("cancelOrdersWs".to_string(), Value::Bool(false));
m.insert("cancelAllOrdersWs".to_string(), Value::Bool(true));
m.insert("fetchBalanceWs".to_string(), Value::Bool(true));
m.insert("fetchDepositsWs".to_string(), Value::Bool(false));
m.insert("fetchMarketsWs".to_string(), Value::Bool(false));
m.insert("fetchMyTradesWs".to_string(), Value::Bool(true));
m.insert("fetchOHLCVWs".to_string(), Value::Bool(true));
m.insert("fetchOrderBookWs".to_string(), Value::Bool(true));
m.insert("fetchOpenOrdersWs".to_string(), Value::Bool(true));
m.insert("fetchOrderWs".to_string(), Value::Bool(true));
m.insert("fetchOrdersWs".to_string(), Value::Bool(true));
m.insert("fetchPositionWs".to_string(), Value::Bool(true));
m.insert("fetchPositionForSymbolWs".to_string(), Value::Bool(true));
m.insert("fetchPositionsWs".to_string(), Value::Bool(true));
m.insert("fetchTickerWs".to_string(), Value::Bool(true));
m.insert("fetchTradesWs".to_string(), Value::Bool(true));
m.insert("fetchTradingFeesWs".to_string(), Value::Bool(false));
m.insert("fetchWithdrawalsWs".to_string(), Value::Bool(false));
m.insert("unWatchTicker".to_string(), Value::Bool(true));
m.insert("unWatchTickers".to_string(), Value::Bool(true));
m.insert("unWatchOHLCV".to_string(), Value::Bool(true));
m.insert("unWatchOHLCVForSymbols".to_string(), Value::Bool(true));
m.insert("unWatchOrderBook".to_string(), Value::Bool(true));
m.insert("unWatchOrderBookForSymbols".to_string(), Value::Bool(true));
m.insert("unWatchTrades".to_string(), Value::Bool(true));
m.insert("unWatchTradesForSymbols".to_string(), Value::Bool(true));
m.insert("unWatchMyTrades".to_string(), Value::Bool(false));
m.insert("unWatchOrders".to_string(), Value::Bool(false));
m.insert("unWatchPositions".to_string(), Value::Bool(false));
m.insert("unWatchMarkPrices".to_string(), Value::Bool(true));
m.insert("unWatchMarkPrice".to_string(), Value::Bool(true));
m.insert("unWatchBidsAsks".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("test".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.testnet.binance.vision/ws".to_string()));
m.insert("margin".to_string(), Value::Str("wss://stream.testnet.binance.vision/ws".to_string()));
m.insert("future".to_string(), Value::Str("wss://fstream.binancefuture.com/ws".to_string()));
m.insert("delivery".to_string(), Value::Str("wss://dstream.binancefuture.com/ws".to_string()));
m.insert("ws-api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("wss://ws-api.testnet.binance.vision/ws-api/v3".to_string()));
m.insert("future".to_string(), Value::Str("wss://testnet.binancefuture.com/ws-fapi/v1".to_string()));
m.insert("delivery".to_string(), Value::Str("wss://testnet.binancefuture.com/ws-dapi/v1".to_string()));
m
}));
m
}));
m
}));
m.insert("demo".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://demo-stream.binance.com/ws".to_string()));
m.insert("margin".to_string(), Value::Str("wss://demo-stream.binance.com/ws".to_string()));
m.insert("future".to_string(), Value::Str("wss://fstream.binancefuture.com/ws".to_string()));
m.insert("delivery".to_string(), Value::Str("wss://dstream.binancefuture.com/ws".to_string()));
m.insert("ws-api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("wss://demo-ws-api.binance.com/ws-api/v3".to_string()));
m.insert("future".to_string(), Value::Str("wss://testnet.binancefuture.com/ws-fapi/v1".to_string()));
m.insert("delivery".to_string(), Value::Str("wss://testnet.binancefuture.com/ws-dapi/v1".to_string()));
m
}));
m
}));
m
}));
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.binance.com:9443/ws".to_string()));
m.insert("margin".to_string(), Value::Str("wss://stream.binance.com:9443/ws".to_string()));
m.insert("future".to_string(), Value::Str("wss://fstream.binance.com/ws".to_string()));
m.insert("delivery".to_string(), Value::Str("wss://dstream.binance.com/ws".to_string()));
m.insert("stock".to_string(), Value::Str("wss://nbstream.binance.com/equity/ws".to_string()));
m.insert("option".to_string(), Value::Str("wss://fstream.binance.com/public/ws".to_string()));
m.insert("optionMarket".to_string(), Value::Str("wss://fstream.binance.com/market/ws".to_string()));
m.insert("optionPrivate".to_string(), Value::Str("wss://fstream.binance.com/private/ws".to_string()));
m.insert("ws-api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("wss://ws-api.binance.com:443/ws-api/v3".to_string()));
m.insert("future".to_string(), Value::Str("wss://ws-fapi.binance.com/ws-fapi/v1".to_string()));
m.insert("delivery".to_string(), Value::Str("wss://ws-dapi.binance.com/ws-dapi/v1".to_string()));
m
}));
m.insert("papi".to_string(), Value::Str("wss://fstream.binance.com/pm/ws".to_string()));
m
}));
m
}));
m.insert("doc".to_string(), Value::Str("https://developers.binance.com/en".to_string()));
m
}));
m.insert("streaming".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("keepAlive".to_string(), Value::Int(180000));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("returnRateLimits".to_string(), Value::Bool(false));
m.insert("streamLimits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Int(50));
m.insert("margin".to_string(), Value::Int(50));
m.insert("future".to_string(), Value::Int(50));
m.insert("delivery".to_string(), Value::Int(50));
m.insert("stock".to_string(), Value::Int(50));
m.insert("option".to_string(), Value::Int(50));
m.insert("optionMarket".to_string(), Value::Int(50));
m
}));
m.insert("subscriptionLimitByStream".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Int(200));
m.insert("margin".to_string(), Value::Int(200));
m.insert("future".to_string(), Value::Int(200));
m.insert("delivery".to_string(), Value::Int(200));
m.insert("stock".to_string(), Value::Int(200));
m.insert("option".to_string(), Value::Int(200));
m.insert("optionMarket".to_string(), Value::Int(200));
m
}));
m.insert("streamBySubscriptionsHash".to_string(), self.create_safe_dictionary(&[]));
m.insert("streamIndex".to_string(), negate(&Value::Int(1)));
m.insert("watchOrderBookRate".to_string(), Value::Int(100));
m.insert("liquidationsLimit".to_string(), Value::Int(1000));
m.insert("myLiquidationsLimit".to_string(), Value::Int(1000));
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("requestId".to_string(), self.create_safe_dictionary(&[]));
m.insert("watchOrderBookLimit".to_string(), Value::Int(1000));
m.insert("watchTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("trade".to_string()));
m
}));
m.insert("watchTicker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("ticker".to_string()));
m
}));
m.insert("watchTickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("miniTicker".to_string()));
m
}));
m.insert("watchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("kline".to_string()));
m
}));
m.insert("watchOrderBook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("maxRetries".to_string(), Value::Int(3));
m.insert("checksum".to_string(), Value::Bool(true));
m
}));
m.insert("option".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("listenKey".to_string(), Value::Null);
m.insert("lastAuthenticatedTime".to_string(), Value::Int(0));
m
}));
m.insert("watchBalance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fetchBalanceSnapshot".to_string(), Value::Bool(false));
m.insert("awaitBalanceSnapshot".to_string(), Value::Bool(true));
m
}));
m.insert("watchLiquidationsForSymbols".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultType".to_string(), Value::Str("swap".to_string()));
m
}));
m.insert("watchPositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fetchPositionsSnapshot".to_string(), Value::Bool(true));
m.insert("awaitPositionsSnapshot".to_string(), Value::Bool(true));
m
}));
m.insert("wallet".to_string(), Value::Str("wb".to_string()));
m.insert("listenKeyRefreshRate".to_string(), Value::Int(1200000));
m.insert("stockListenKeyRefreshRate".to_string(), Value::Int(1200000));
m.insert("ws".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("tickerChannelsMap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("price".to_string(), Value::Str("price".to_string()));
m.insert("quote".to_string(), Value::Str("quote".to_string()));
m.insert("24hrTicker".to_string(), Value::Str("ticker".to_string()));
m.insert("24hrMiniTicker".to_string(), Value::Str("miniTicker".to_string()));
m.insert("markPriceUpdate".to_string(), Value::Str("markPrice".to_string()));
m.insert("markPrice".to_string(), Value::Str("markPrice".to_string()));
m.insert("1hTicker".to_string(), Value::Str("ticker_1h".to_string()));
m.insert("4hTicker".to_string(), Value::Str("ticker_4h".to_string()));
m.insert("1dTicker".to_string(), Value::Str("ticker_1d".to_string()));
m.insert("bookTicker".to_string(), Value::Str("bookTicker".to_string()));
m
}));
m
}));
m
});
Value::Null
}
pub fn request_id(&self, mut url: Value) -> Value {
let mut options: Value = self.safe_dict_k(self.options.clone(), "requestId", &[self.create_safe_dictionary(&[])]);
let mut previousValue: Value = self.safe_integer(options.clone(), url.clone(), &[Value::Int(0)]);
let mut newValue: Value = self.sum(&[previousValue.clone(), Value::Int(1)]);
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("requestId".to_string())), &url, newValue.clone());
return newValue;
Value::Null
}
pub fn is_spot_url(&self, mut client: Value) -> Value {
return Value::Bool(is_true(&(is_greater_than(&get_index_of(&get_value(&client, &Value::Str("url".to_string())), &Value::Str("/stream".to_string())), &negate(&Value::Int(1))))) || is_true(&(is_greater_than(&get_index_of(&get_value(&client, &Value::Str("url".to_string())), &Value::Str("demo-stream".to_string())), &negate(&Value::Int(1))))));
Value::Null
}
pub fn stream(&mut self, mut type_var: Value, mut subscriptionHash: Value, optional_args: &[Value]) -> Value {
let mut numSubscriptions = get_arg(optional_args, 0, Value::Int(1));
let mut streamBySubscriptionsHash: Value = self.safe_dict_k(self.options.clone(), "streamBySubscriptionsHash", &[self.create_safe_dictionary(&[])]);
let mut stream: Value = self.safe_string(streamBySubscriptionsHash.clone(), subscriptionHash.clone(), &[]);
if is_equal(&stream, &Value::Null) {
let mut streamIndex: Value = self.safe_integer_k(self.options.clone(), "streamIndex", &[negate(&Value::Int(1))]);
let mut streamLimits: Value = self.safe_value_k(self.options.clone(), "streamLimits", &[]);
let mut streamLimit: Value = self.safe_integer(streamLimits.clone(), type_var.clone(), &[]);
streamIndex = add(&streamIndex, &Value::Int(1));
let mut normalizedIndex: Value = mod_val(&streamIndex, &streamLimit);
add_element_to_object(&mut self.options, &Value::Str("streamIndex".to_string()), streamIndex.clone());
stream = self.number_to_string(normalizedIndex.clone());
if !is_equal(&subscriptionHash, &Value::Null) {
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("streamBySubscriptionsHash".to_string())), &subscriptionHash, stream.clone());
}
let mut subscriptionsByStreams: Value = self.safe_value_k(self.options.clone(), "numSubscriptionsByStream", &[]);
if is_equal(&subscriptionsByStreams, &Value::Null) {
{ let __be_tmp = self.create_safe_dictionary(&[]); add_element_to_object(&mut self.options, &Value::Str("numSubscriptionsByStream".to_string()), __be_tmp); };
}
let mut subscriptionsByStream: Value = self.safe_integer(get_value(&self.options, &Value::Str("numSubscriptionsByStream".to_string())), stream.clone(), &[Value::Int(0)]);
let mut newNumSubscriptions: Value = add(&subscriptionsByStream, &numSubscriptions);
let mut subscriptionLimitByStream: Value = self.safe_integer(get_value(&self.options, &Value::Str("subscriptionLimitByStream".to_string())), type_var.clone(), &[Value::Int(200)]);
if is_greater_than(&newNumSubscriptions, &subscriptionLimitByStream) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" reached the limit of subscriptions by stream. Increase the number of streams, or increase the stream limit or subscription limit by stream if the exchange allows.".to_string()))));
}
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("numSubscriptionsByStream".to_string())), &stream, add(&subscriptionsByStream, &numSubscriptions));
}
return stream;
Value::Null
}
pub fn get_ws_url(&self, mut type_var: Value, mut category: Value) -> Value {
if is_true(&(is_equal(&type_var, &Value::Str("option".to_string())))) || is_true(&(is_equal(&type_var, &Value::Str("optionMarket".to_string())))) || is_true(&(is_equal(&type_var, &Value::Str("optionPrivate".to_string())))) {
return get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &type_var);
}
let mut baseUrl: Value = get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &type_var);
if is_equal(&type_var, &Value::Str("future".to_string())) {
let mut baseUrlSplit: Value = split(&baseUrl, &Value::Str("://".to_string()));
let mut baseUrlSplitLength: Value = get_array_length(&baseUrlSplit);
if is_greater_than(&baseUrlSplitLength, &Value::Int(2)) {
return baseUrl;
}
if is_true(&Value::Bool(ends_with(&baseUrl, &Value::Str("/ws".to_string())))) {
let mut prefix: Value = slice(&baseUrl, &Value::Int(0), &subtract(&get_array_length(&baseUrl), &Value::Int(3)));
return add(&add(&add(&prefix, &Value::Str("/".to_string())), &category), &Value::Str("/ws".to_string()));
}
return baseUrl;
}
return baseUrl;
Value::Null
}
pub fn get_future_ws_category(&self, mut channel: Value) -> Value {
if is_equal(&channel, &Value::Str("depth".to_string())) || is_equal(&channel, &Value::Str("rpiDepth".to_string())) || is_equal(&channel, &Value::Str("bookTicker".to_string())) || is_equal(&channel, &Value::Str("trade".to_string())) {
return Value::Str("public".to_string());
}
return Value::Str("market".to_string());
Value::Null
}
pub fn get_private_ws_url(&self, mut type_var: Value, mut listenKey: Value) -> Value {
if is_equal(&type_var, &Value::Str("future".to_string())) {
return add(&add(&self.get_ws_url(type_var.clone(), Value::Str("private".to_string())), &Value::Str("?listenKey=".to_string())), &listenKey);
}
return add(&add(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &type_var), &Value::Str("/".to_string())), &listenKey);
Value::Null
}
pub fn get_stock_ws_url(&self, optional_args: &[Value]) -> Value {
let mut streamType = get_arg(optional_args, 0, Value::Str("market".to_string()));
let mut baseUrl: Value = get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("stock".to_string()));
if is_equal(&streamType, &Value::Str("combined".to_string())) {
return replace_str(&baseUrl, &Value::Str("/ws".to_string()), &Value::Str("/stream".to_string()));
}
return baseUrl;
Value::Null
}
pub fn get_stock_ticker_from_symbol(&self, mut symbol: Value) -> Value {
let mut market: Value = self.market(symbol.clone());
let mut base: Value = self.safe_string2(market.clone(), Value::Str("base".to_string()), Value::Str("id".to_string()), &[]);
return ternary(is_true(&(is_equal(&base, &Value::Null))), Value::Null, to_lower(&base));
Value::Null
}
pub fn get_stock_unified_symbol(&self, mut stockSymbol: Value, optional_args: &[Value]) -> Value {
let mut quote = get_arg(optional_args, 0, Value::Null);
if is_equal(&stockSymbol, &Value::Null) {
return Value::Null;
}
let mut safeQuote: Value = ternary(is_true(&(is_equal("e, &Value::Null))), Value::Str("USDC".to_string()), quote.clone());
let mut parsed: Value = self.safe_symbol(stockSymbol.clone(), &[Value::Null, Value::Str("/".to_string()), Value::Str("spot".to_string())]);
if is_true(&(!is_equal(&parsed, &Value::Null))) && is_true(&(is_greater_than_or_equal(&get_index_of(&parsed, &Value::Str("/".to_string())), &Value::Int(0)))) {
return parsed;
}
return add(&add(&stockSymbol, &Value::Str("/".to_string())), &safeQuote);
Value::Null
}
pub async fn watch_stock_market_stream(&mut self, mut streams: Value, mut messageHashes: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut url: Value = self.get_stock_ws_url(&[Value::Str("market".to_string())]);
let mut requestId: Value = self.request_id(url.clone());
let mut query: Value = self.omit(params.clone(), Value::List(vec![Value::Str("stock".to_string()), Value::Str("name".to_string()), Value::Str("callerMethodName".to_string()), Value::Str("type".to_string()), Value::Str("subType".to_string()), Value::Str("symbol".to_string()), Value::Str("timeframe".to_string())]), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("SUBSCRIBE".to_string()));
m.insert("params".to_string(), streams.clone());
m.insert("id".to_string(), requestId.clone());
m
});
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m
});
let __ws_arg_0 = self.extend(request.clone(), &[query.clone()]);
return self.watch_multiple(url.clone(), messageHashes.clone(), &[__ws_arg_0, messageHashes.clone(), subscribe.clone()]).await;
Value::Null
}
pub async fn watch_liquidations(&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
}));
return self.watch_liquidations_for_symbols(Value::List(vec![symbol.clone()]), &[since.clone(), limit.clone(), params.clone()]).await;
Value::Null
}
pub async fn watch_liquidations_for_symbols(&mut self, mut symbols: 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 subscriptionHashes: Value = Value::List(vec![]);
let mut messageHashes: Value = Value::List(vec![]);
let mut streamHash: Value = Value::Str("liquidations".to_string());
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(true), Value::Bool(true)]);
if is_true(&self.is_empty(symbols.clone())) {
append_to_array(&mut subscriptionHashes, add(&Value::Str("!".to_string()), &Value::Str("forceOrder@arr".to_string())));
append_to_array(&mut messageHashes, Value::Str("liquidations".to_string()));
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_55: bool = true;
while { if !__for_first_55 { i = add(&i, &Value::Int(1)); } __for_first_55 = false; is_less_than(&i, &get_array_length(&symbols)) } {
let mut market: Value = self.market(get_value(&symbols, &i));
append_to_array(&mut subscriptionHashes, add(&get_value(&market, &Value::Str("lowercaseId".to_string())), &Value::Str("@forceOrder".to_string())));
append_to_array(&mut messageHashes, add(&Value::Str("liquidations::".to_string()), &get_value(&symbols, &i)));
}
}
streamHash = add(&streamHash, &add(&Value::Str("::".to_string()), &join(&symbols, &Value::Str(",".to_string()))));
}
let mut firstMarket: Value = Value::Null;
if !is_true(&self.is_empty(symbols.clone())) {
firstMarket = self.get_market_from_symbols(&[symbols.clone()]);
}
let mut resolvedAuth: Value = self.resolve_auth_type(Value::Str("watchLiquidationsForSymbols".to_string()), &[firstMarket.clone(), params.clone()]);
let mut type_var: Value = get_value(&resolvedAuth, &Value::Int(0));
params = get_value(&resolvedAuth, &Value::Int(2));
if is_equal(&type_var, &Value::Str("spot".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" watchLiquidationsForSymbols is not supported for spot symbols".to_string()))));
}
if is_equal(&type_var, &Value::Str("option".to_string())) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" watchLiquidationsForSymbols() does not support options markets, there is no public liquidation stream for eOptions".to_string()))));
}
let mut numSubscriptions: Value = get_array_length(&subscriptionHashes);
let mut url: Value = add(&add(&self.get_ws_url(type_var.clone(), self.get_future_ws_category(Value::Str("forceOrder".to_string()))), &Value::Str("/".to_string())), &self.stream(type_var.clone(), streamHash.clone(), &[numSubscriptions.clone()]));
let mut requestId: Value = self.request_id(url.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("SUBSCRIBE".to_string()));
m.insert("params".to_string(), subscriptionHashes.clone());
m.insert("id".to_string(), requestId.clone());
m
});
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m
});
let __ws_arg_1 = self.extend(request.clone(), &[params.clone()]);
let mut newLiquidations: Value = self.watch_multiple(url.clone(), messageHashes.clone(), &[__ws_arg_1, subscriptionHashes.clone(), subscribe.clone()]).await;
if is_true(&self.newUpdates) {
return newLiquidations;
}
return self.filter_by_symbols_since_limit(self.liquidations.clone(), &[symbols.clone(), since.clone(), limit.clone(), Value::Bool(true)]);
Value::Null
}
pub fn handle_liquidation(&mut self, mut client: Value, mut message: Value) {
let mut rawLiquidation: Value = self.safe_value_k(message.clone(), "o", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketId: Value = self.safe_string_k(rawLiquidation.clone(), "s", &[]);
let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, Value::Str("".to_string()), Value::Str("contract".to_string())]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut liquidation: Value = self.parse_ws_liquidation(rawLiquidation.clone(), &[market.clone()]);
if is_equal(&self.liquidations, &Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "liquidationsLimit", &[Value::Int(1000)]);
self.liquidations = ArrayCache::new(limit.clone());
}
let mut cache: Value = self.liquidations.clone();
cache.append(liquidation.clone());
client.resolve(&[Value::List(vec![liquidation.clone()]), Value::Str("liquidations".to_string())]);
client.resolve(&[Value::List(vec![liquidation.clone()]), add(&Value::Str("liquidations::".to_string()), &symbol)]);
}
pub fn parse_ws_liquidation(&self, mut liquidation: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Value = self.safe_string_k(liquidation.clone(), "s", &[]);
market = self.safe_market(&[marketId.clone(), market.clone(), Value::Null, Value::Str("swap".to_string())]);
let mut timestamp: Value = self.safe_integer_k(liquidation.clone(), "T", &[]);
return self.safe_liquidation(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), liquidation.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[market.clone()]));
m.insert("contracts".to_string(), self.safe_number_k(liquidation.clone(), "l", &[]));
m.insert("contractSize".to_string(), self.safe_number_k(market.clone(), "contractSize", &[]));
m.insert("price".to_string(), self.safe_number_k(liquidation.clone(), "ap", &[]));
m.insert("side".to_string(), self.safe_string_lower(liquidation.clone(), Value::Str("S".to_string()), &[]));
m.insert("baseValue".to_string(), Value::Null);
m.insert("quoteValue".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m
}), &[]);
Value::Null
}
pub async fn watch_my_liquidations(&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
}));
return self.watch_my_liquidations_for_symbols(Value::List(vec![symbol.clone()]), &[since.clone(), limit.clone(), params.clone()]).await;
Value::Null
}
pub async fn watch_my_liquidations_for_symbols(&mut self, mut symbols: 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;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(true), Value::Bool(true), Value::Bool(true)]);
let mut market: Value = self.get_market_from_symbols(&[symbols.clone()]);
let mut messageHashes: Value = Value::List(vec![Value::Str("myLiquidations".to_string())]);
if !is_true(&self.is_empty(symbols.clone())) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_56: bool = true;
while { if !__for_first_56 { i = add(&i, &Value::Int(1)); } __for_first_56 = false; is_less_than(&i, &get_array_length(&symbols)) } {
let mut symbol: Value = get_value(&symbols, &i);
let mut symbol: Value = get_value(&symbols, &i);
append_to_array(&mut messageHashes, add(&Value::Str("myLiquidations::".to_string()), &symbol));
}
}
}
let mut type_var: Value = Value::Null;
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.resolve_auth_type(Value::Str("watchMyLiquidationsForSymbols".to_string()), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); subType = get_value(&__destr_tmp, &Value::Int(1)); params = get_value(&__destr_tmp, &Value::Int(2)); }
let __ws_arg_2 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var.clone());
m.insert("subType".to_string(), subType.clone());
m
}), &[params.clone()]);
self.authenticate(&[__ws_arg_2]).await;
let mut listenKey: Value = get_value(&get_value(&self.options, &type_var), &Value::Str("listenKey".to_string()));
let mut url: Value = self.get_private_ws_url(type_var.clone(), listenKey.clone());
let mut message: Value = Value::Null;
let mut newLiquidations: Value = self.watch_multiple(url.clone(), messageHashes.clone(), &[message.clone(), Value::List(vec![type_var.clone()])]).await;
if is_true(&self.newUpdates) {
return newLiquidations;
}
return self.filter_by_symbols_since_limit(self.liquidations.clone(), &[symbols.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn handle_my_liquidation(&mut self, mut client: Value, mut message: Value) {
let mut orderType: Value = self.safe_string_k(message.clone(), "o", &[]);
if !is_equal(&orderType, &Value::Str("LIQUIDATION".to_string())) {
return;
}
let mut marketId: Value = self.safe_string_k(message.clone(), "s", &[]);
let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, Value::Null, Value::Str("swap".to_string())]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[market.clone()]);
let mut liquidation: Value = self.parse_ws_liquidation(message.clone(), &[market.clone()]);
let mut cache: Value = self.myLiquidations.clone();
if is_equal(&cache, &Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "myLiquidationsLimit", &[Value::Int(1000)]);
cache = ArrayCache::new(limit.clone());
}
cache.append(liquidation.clone());
self.myLiquidations = cache.clone();
client.resolve(&[Value::List(vec![liquidation.clone()]), Value::Str("myLiquidations".to_string())]);
client.resolve(&[Value::List(vec![liquidation.clone()]), add(&Value::Str("myLiquidations::".to_string()), &symbol)]);
}
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
}));
return self.watch_order_book_for_symbols(Value::List(vec![symbol.clone()]), &[limit.clone(), params.clone()]).await;
Value::Null
}
pub async fn watch_order_book_for_symbols(&mut self, mut symbols: 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;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(true), Value::Bool(true)]);
let mut firstMarket: Value = self.market(get_value(&symbols, &Value::Int(0)));
let mut type_var: Value = get_value(&firstMarket, &Value::Str("type".to_string()));
if is_equal(&get_value(&firstMarket, &Value::Str("option".to_string())), &Value::Bool(true)) {
type_var = Value::Str("option".to_string());
} else if is_equal(&get_value(&firstMarket, &Value::Str("contract".to_string())), &Value::Bool(true)) {
type_var = ternary(is_true(&(is_equal(&get_value(&firstMarket, &Value::Str("linear".to_string())), &Value::Bool(true)))), Value::Str("future".to_string()), Value::Str("delivery".to_string()));
}
let mut name: Value = Value::Str("depth".to_string());
let mut streamHash: Value = Value::Str("multipleOrderbook".to_string());
if !is_equal(&symbols, &Value::Null) {
let mut symbolsLength: Value = get_array_length(&symbols);
if is_greater_than(&symbolsLength, &Value::Int(200)) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" watchOrderBookForSymbols() accepts 200 symbols at most. To watch more symbols call watchOrderBookForSymbols() multiple times".to_string()))));
}
streamHash = add(&streamHash, &add(&Value::Str("::".to_string()), &join(&symbols, &Value::Str(",".to_string()))));
}
let mut watchOrderBookRate: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrderBookForSymbols".to_string()), Value::Str("watchOrderBookRate".to_string()), &[Value::Str("100".to_string())]); watchOrderBookRate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut rpi: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrderBookForSymbols".to_string()), Value::Str("rpi".to_string()), &[Value::Bool(false)]); rpi = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&rpi) && is_equal(&type_var, &Value::Str("future".to_string())) {
name = Value::Str("rpiDepth".to_string());
watchOrderBookRate = Value::Str("500".to_string());
}
let mut subParams: Value = Value::List(vec![]);
let mut messageHashes: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_57: bool = true;
while { if !__for_first_57 { i = add(&i, &Value::Int(1)); } __for_first_57 = false; is_less_than(&i, &get_array_length(&symbols)) } {
let mut symbol: Value = get_value(&symbols, &i);
let mut symbol: Value = get_value(&symbols, &i);
let mut market: Value = self.market(symbol.clone());
append_to_array(&mut messageHashes, add(&Value::Str("orderbook::".to_string()), &symbol));
let mut subscriptionHash: Value = add(&add(&get_value(&market, &Value::Str("lowercaseId".to_string())), &Value::Str("@".to_string())), &name);
if is_equal(&watchOrderBookRate, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" watchOrderBookForSymbols() watchOrderBookRate is required".to_string()))));
}
let mut symbolHash: Value = add(&add(&add(&subscriptionHash, &Value::Str("@".to_string())), &to_string_val(&watchOrderBookRate)), &Value::Str("ms".to_string()));
append_to_array(&mut subParams, symbolHash.clone());
}
}
let mut messageHashesLength: Value = get_array_length(&messageHashes);
let mut url: Value = add(&add(&self.get_ws_url(type_var.clone(), self.get_future_ws_category(name.clone())), &Value::Str("/".to_string())), &self.stream(type_var.clone(), streamHash.clone(), &[messageHashesLength.clone()]));
let mut requestId: Value = self.request_id(url.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("SUBSCRIBE".to_string()));
m.insert("params".to_string(), subParams.clone());
m.insert("id".to_string(), requestId.clone());
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), to_string_val(&requestId));
m.insert("name".to_string(), name.clone());
m.insert("symbols".to_string(), symbols.clone());
m.insert("method".to_string(), Value::Str("handle_order_book_subscription".to_string()).clone());
m.insert("limit".to_string(), limit.clone());
m.insert("type".to_string(), type_var.clone());
m.insert("params".to_string(), params.clone());
m
});
let __ws_arg_3 = self.extend(request.clone(), &[params.clone()]);
let mut orderbook: Value = self.watch_multiple(url.clone(), messageHashes.clone(), &[__ws_arg_3, messageHashes.clone(), subscription.clone()]).await;
return orderbook.limit();
Value::Null
}
pub async fn un_watch_order_book_for_symbols(&mut self, mut symbols: 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;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(true), Value::Bool(true)]);
let mut firstMarket: Value = self.market(get_value(&symbols, &Value::Int(0)));
let mut type_var: Value = get_value(&firstMarket, &Value::Str("type".to_string()));
if is_equal(&get_value(&firstMarket, &Value::Str("option".to_string())), &Value::Bool(true)) {
type_var = Value::Str("option".to_string());
} else if is_equal(&get_value(&firstMarket, &Value::Str("contract".to_string())), &Value::Bool(true)) {
type_var = ternary(is_true(&(is_equal(&get_value(&firstMarket, &Value::Str("linear".to_string())), &Value::Bool(true)))), Value::Str("future".to_string()), Value::Str("delivery".to_string()));
}
let mut name: Value = Value::Str("depth".to_string());
let mut streamHash: Value = Value::Str("multipleOrderbook".to_string());
if !is_equal(&symbols, &Value::Null) {
streamHash = add(&streamHash, &add(&Value::Str("::".to_string()), &join(&symbols, &Value::Str(",".to_string()))));
}
let mut watchOrderBookRate: Value = self.safe_string_k(self.options.clone(), "watchOrderBookRate", &[Value::Str("100".to_string())]);
let mut subParams: Value = Value::List(vec![]);
let mut subMessageHashes: Value = Value::List(vec![]);
let mut messageHashes: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_58: bool = true;
while { if !__for_first_58 { i = add(&i, &Value::Int(1)); } __for_first_58 = false; is_less_than(&i, &get_array_length(&symbols)) } {
let mut symbol: Value = get_value(&symbols, &i);
let mut symbol: Value = get_value(&symbols, &i);
let mut market: Value = self.market(symbol.clone());
append_to_array(&mut subMessageHashes, add(&Value::Str("orderbook::".to_string()), &symbol));
append_to_array(&mut messageHashes, add(&Value::Str("unsubscribe:orderbook:".to_string()), &symbol));
let mut streamId: Value = get_value(&market, &Value::Str("lowercaseId".to_string()));
let mut subscriptionHash: Value = add(&add(&streamId, &Value::Str("@".to_string())), &name);
let mut symbolHash: Value = add(&add(&add(&subscriptionHash, &Value::Str("@".to_string())), &watchOrderBookRate), &Value::Str("ms".to_string()));
append_to_array(&mut subParams, symbolHash.clone());
}
}
let mut messageHashesLength: Value = get_array_length(&subMessageHashes);
let mut url: Value = add(&add(&self.get_ws_url(type_var.clone(), self.get_future_ws_category(Value::Str("depth".to_string()))), &Value::Str("/".to_string())), &self.stream(type_var.clone(), streamHash.clone(), &[messageHashesLength.clone()]));
let mut requestId: Value = self.request_id(url.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("UNSUBSCRIBE".to_string()));
m.insert("params".to_string(), subParams.clone());
m.insert("id".to_string(), requestId.clone());
m
});
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(), to_string_val(&requestId));
m.insert("symbols".to_string(), symbols.clone());
m.insert("subMessageHashes".to_string(), subMessageHashes.clone());
m.insert("messageHashes".to_string(), messageHashes.clone());
m.insert("topic".to_string(), Value::Str("orderbook".to_string()));
m
});
let __ws_arg_4 = self.extend(request.clone(), &[params.clone()]);
return self.watch_multiple(url.clone(), messageHashes.clone(), &[__ws_arg_4, messageHashes.clone(), subscription.clone()]).await;
Value::Null
}
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
}));
return self.un_watch_order_book_for_symbols(Value::List(vec![symbol.clone()]), &[params.clone()]).await;
Value::Null
}
pub async fn fetch_order_book_ws(&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 payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut payload, &Value::Str("limit".to_string()), limit.clone());
}
let mut marketType: Value = self.get_market_type(Value::Str("fetchOrderBookWs".to_string()), market.clone(), &[params.clone()]);
if !is_equal(&marketType, &Value::Str("future".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchOrderBookWs only supports swap markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &marketType);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOrderBookWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
add_element_to_object(&mut payload, &Value::Str("returnRateLimits".to_string()), returnRateLimits.clone());
params = self.omit(params.clone(), Value::Str("test".to_string()), &[]);
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), Value::Str("depth".to_string()));
let __ws_arg_5 = self.extend(payload.clone(), &[params.clone()]);
m.insert("params".to_string(), self.sign_params(&[__ws_arg_5]));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_fetch_order_book".to_string()).clone());
m
});
let mut orderbook: Value = self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
add_element_to_object(&mut orderbook, &Value::Str("symbol".to_string()), get_value(&market, &Value::Str("symbol".to_string())));
return orderbook;
Value::Null
}
pub fn handle_fetch_order_book(&self, mut client: Value, mut message: Value) {
let mut messageHash: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut result: Value = self.safe_dict_k(message.clone(), "result", &[]);
let mut timestamp: Value = self.safe_integer_k(result.clone(), "T", &[]);
let mut orderbook: Value = self.parse_order_book(result.clone(), Value::Null, &[timestamp.clone()]);
add_element_to_object(&mut orderbook, &Value::Str("nonce".to_string()), self.safe_integer2(result.clone(), Value::Str("lastUpdateId".to_string()), Value::Str("u".to_string()), &[]));
client.resolve(&[orderbook.clone(), messageHash.clone()]);
}
pub async fn fetch_order_book_snapshot(&mut self, mut client: Value, mut message: Value, mut subscription: Value) -> Value {
let mut symbol: Value = self.safe_string_k(subscription.clone(), "symbol", &[]);
let mut messageHash: Value = add(&Value::Str("orderbook::".to_string()), &symbol);
{
let mut defaultLimit: Value = self.safe_integer_k(self.options.clone(), "watchOrderBookLimit", &[Value::Int(1000)]);
let mut type_var: Value = self.safe_value_k(subscription.clone(), "type", &[]);
let mut limit: Value = self.safe_integer_k(subscription.clone(), "limit", &[defaultLimit.clone()]);
let mut params: Value = self.safe_value_k(subscription.clone(), "params", &[]);
let mut snapshot: Value = self.fetch_rest_order_book_safe(symbol.clone(), &[limit.clone(), params.clone()]).await;
if is_equal(&self.safe_value(self.orderbooks.clone(), symbol.clone(), &[]), &Value::Null) {
return Value::Null;
}
let mut orderbook: Value = self.safe_value(self.orderbooks.clone(), symbol.clone(), &[]);
orderbook.reset(snapshot.clone());
let mut messages: Value = get_value(&orderbook, &Value::Str("cache".to_string()));
crate::set_value(&mut orderbook, &Value::Str("cache".to_string()), Value::List(vec![]));
{
let mut i: Value = Value::Int(0);
let mut __for_first_59: bool = true;
while { if !__for_first_59 { i = add(&i, &Value::Int(1)); } __for_first_59 = false; is_less_than(&i, &get_array_length(&messages)) } {
let mut messageItem: Value = get_value(&messages, &i);
let mut messageItem: Value = get_value(&messages, &i);
let mut U: Value = self.safe_integer_k(messageItem.clone(), "U", &[]);
let mut u: Value = self.safe_integer_k(messageItem.clone(), "u", &[]);
if is_true(&(is_equal(&U, &Value::Null))) || is_true(&(is_equal(&u, &Value::Null))) {
continue;
}
let mut pu: Value = self.safe_integer_k(messageItem.clone(), "pu", &[]);
if is_equal(&type_var, &Value::Str("future".to_string())) {
if is_less_than(&u, &get_value(&orderbook, &Value::Str("nonce".to_string()))) {
continue;
}
if is_true(&(is_less_than_or_equal(&U, &get_value(&orderbook, &Value::Str("nonce".to_string()))))) && is_true(&(is_greater_than_or_equal(&u, &get_value(&orderbook, &Value::Str("nonce".to_string()))))) || is_true(&(is_equal(&pu, &get_value(&orderbook, &Value::Str("nonce".to_string()))))) {
self.handle_order_book_message(client.clone(), messageItem.clone(), orderbook.clone());
}
} else {
if is_less_than_or_equal(&u, &get_value(&orderbook, &Value::Str("nonce".to_string()))) {
continue;
}
if is_true(&(is_less_than_or_equal(&(subtract(&U, &Value::Int(1))), &get_value(&orderbook, &Value::Str("nonce".to_string()))))) && is_true(&(is_greater_than_or_equal(&(subtract(&u, &Value::Int(1))), &get_value(&orderbook, &Value::Str("nonce".to_string()))))) {
self.handle_order_book_message(client.clone(), messageItem.clone(), orderbook.clone());
}
}
}
}
if !is_equal(&symbol, &Value::Null) {
add_element_to_object(&mut self.orderbooks, &symbol, orderbook.clone());
}
client.resolve(&[orderbook.clone(), messageHash.clone()]);
}
Value::Null
}
pub fn handle_delta(&self, mut bookside: Value, mut delta: Value) {
let mut price: Value = self.safe_float(delta.clone(), Value::Int(0), &[]);
let mut amount: Value = self.safe_float(delta.clone(), Value::Int(1), &[]);
bookside.store(price.clone(), amount.clone());
}
pub fn handle_deltas(&self, mut bookside: Value, mut deltas: Value) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_60: bool = true;
while { if !__for_first_60 { i = add(&i, &Value::Int(1)); } __for_first_60 = false; is_less_than(&i, &get_array_length(&deltas)) } {
self.handle_delta(bookside.clone(), get_value(&deltas, &i));
}
}
}
pub fn handle_order_book_message(&self, mut client: Value, mut message: Value, mut orderbook: Value) -> Value {
let mut u: Value = self.safe_integer_k(message.clone(), "u", &[]);
self.handle_deltas(get_value(&orderbook, &Value::Str("asks".to_string())), self.safe_value_k(message.clone(), "a", &[Value::List(vec![])]));
self.handle_deltas(get_value(&orderbook, &Value::Str("bids".to_string())), self.safe_value_k(message.clone(), "b", &[Value::List(vec![])]));
add_element_to_object(&mut orderbook, &Value::Str("nonce".to_string()), u.clone());
let mut timestamp: Value = self.safe_integer_k(message.clone(), "E", &[]);
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()));
return orderbook;
Value::Null
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value) {
let mut marketId: Value = self.safe_string_k(message.clone(), "s", &[]);
let mut isSpot: Value = self.is_spot_url(client.clone());
let mut marketType: Value = ternary(is_true(&isSpot), Value::Str("spot".to_string()), Value::Str("swap".to_string()));
let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, Value::Null, marketType.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut messageHash: Value = add(&Value::Str("orderbook::".to_string()), &symbol);
if !is_true(&(Value::Bool(in_op(&self.orderbooks, &symbol)))) {
return;
}
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) {
crate::runtime::append_to_object_array(&mut orderbook, &Value::Str("cache".to_string()), message.clone());
} else {
let _try_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut U: Value = self.safe_integer_k(message.clone(), "U", &[]);
if is_equal(&U, &Value::Null) {
return true;
}
let mut u: Value = self.safe_integer_k(message.clone(), "u", &[]);
if is_equal(&u, &Value::Null) {
return true;
}
let mut pu: Value = self.safe_integer_k(message.clone(), "pu", &[]);
if is_equal(&pu, &Value::Null) {
if is_greater_than(&u, &nonce) {
let mut timestamp: Value = self.safe_integer_k(orderbook.clone(), "timestamp", &[]);
let mut conditional: Value = Value::Null;
if is_equal(×tamp, &Value::Null) {
conditional = Value::Bool(is_true(&(is_less_than_or_equal(&(subtract(&U, &Value::Int(1))), &nonce))) && is_true(&(is_greater_than_or_equal(&(subtract(&u, &Value::Int(1))), &nonce))));
} else {
conditional = Value::Bool(is_equal(&(subtract(&U, &Value::Int(1))), &nonce));
}
if is_true(&conditional) {
self.handle_order_book_message(client.clone(), message.clone(), orderbook.clone());
if is_less_than(&nonce, &self.safe_integer_k(orderbook.clone(), "nonce", &[Value::Int(0)])) {
client.resolve(&[orderbook.clone(), messageHash.clone()]);
}
} else {
let mut checksum: Value = self.handle_option(Value::Str("watchOrderBook".to_string()), Value::Str("checksum".to_string()), &[Value::Bool(true)]);
if is_equal(&checksum, &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::checksum_error(add(&add(&self.id, &Value::Str(" ".to_string())), &self.orderbook_checksum_message(symbol.clone()))));
}
}
}
} else {
if is_greater_than_or_equal(&u, &nonce) {
if is_true(&(is_less_than_or_equal(&U, &nonce))) || is_true(&(is_equal(&pu, &nonce))) {
self.handle_order_book_message(client.clone(), message.clone(), orderbook.clone());
if is_less_than_or_equal(&nonce, &self.safe_integer_k(orderbook.clone(), "nonce", &[Value::Int(0)])) {
client.resolve(&[orderbook.clone(), messageHash.clone()]);
}
} else {
let mut checksum: Value = self.handle_option(Value::Str("watchOrderBook".to_string()), Value::Str("checksum".to_string()), &[Value::Bool(true)]);
if is_equal(&checksum, &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::checksum_error(add(&add(&self.id, &Value::Str(" ".to_string())), &self.orderbook_checksum_message(symbol.clone()))));
}
}
}
}
#[allow(unreachable_code)] { false }}));
match _try_result { Ok(__try_ret) => { if __try_ret { return; } } Err(_try_err) => { let e: Value = panic_to_value(_try_err);
if is_true(&Value::Bool(in_op(&self.orderbooks, &symbol))) {
remove(&mut self.orderbooks, &symbol);
}
if is_true(&Value::Bool(in_op(&get_value(&client, &Value::Str("subscriptions".to_string())), &messageHash))) {
remove(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &messageHash);
}
client.reject(&[e.clone(), messageHash.clone()]);
} }
}
}
pub fn handle_order_book_subscription(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
let mut defaultLimit: Value = self.safe_integer_k(self.options.clone(), "watchOrderBookLimit", &[Value::Int(1000)]);
let mut symbolOfSubscription: Value = self.safe_string_k(subscription.clone(), "symbol", &[]); let mut symbols: Value = self.safe_value_k(subscription.clone(), "symbols", &[Value::List(vec![symbolOfSubscription.clone()])]); let mut limit: Value = self.safe_integer_k(subscription.clone(), "limit", &[defaultLimit.clone()]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_61: bool = true;
while { if !__for_first_61 { i = add(&i, &Value::Int(1)); } __for_first_61 = false; is_less_than(&i, &get_array_length(&symbols)) } {
let mut symbol: Value = get_value(&symbols, &i);
let mut symbol: Value = get_value(&symbols, &i);
if is_true(&Value::Bool(in_op(&self.orderbooks, &symbol))) {
remove(&mut self.orderbooks, &symbol);
}
{ 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); };
subscription = self.extend(subscription.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.clone());
m
})]);
self.spawn(&[Value::Str("fetch_order_book_snapshot".to_string()).clone(), client.clone(), message.clone(), subscription.clone()]);
}
}
}
pub fn handle_subscription_status(&mut self, mut client: Value, mut message: Value) -> Value {
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 subscription: Value = self.safe_value(subscriptionsById.clone(), id.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut method: Value = self.safe_value_k(subscription.clone(), "method", &[]);
if !is_equal(&method, &Value::Null) {
self.dispatch_ws_handler(&method, &[client.clone(), message.clone(), subscription.clone()]);
}
let mut isUnSubMessage: Value = self.safe_bool_k(subscription.clone(), "unsubscribe", &[Value::Bool(false)]);
if is_equal(&isUnSubMessage, &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_62: bool = true;
while { if !__for_first_62 { j = add(&j, &Value::Int(1)); } __for_first_62 = 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 watch_trades_for_symbols(&mut self, mut symbols: 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;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(true), Value::Bool(true)]);
let mut streamHash: Value = Value::Str("multipleTrades".to_string());
if !is_equal(&symbols, &Value::Null) {
let mut symbolsLength: Value = get_array_length(&symbols);
if is_greater_than(&symbolsLength, &Value::Int(200)) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" watchTradesForSymbols() accepts 200 symbols at most. To watch more symbols call watchTradesForSymbols() multiple times".to_string()))));
}
streamHash = add(&streamHash, &add(&Value::Str("::".to_string()), &join(&symbols, &Value::Str(",".to_string()))));
}
let mut name: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchTradesForSymbols".to_string()), Value::Str("name".to_string()), &[Value::Str("trade".to_string())]); name = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
params = self.omit(params.clone(), Value::Str("callerMethodName".to_string()), &[]);
let mut firstMarket: Value = self.market(get_value(&symbols, &Value::Int(0)));
let mut type_var: Value = get_value(&firstMarket, &Value::Str("type".to_string()));
let mut isOption: Value = get_value(&firstMarket, &Value::Str("option".to_string()));
if is_equal(&isOption, &Value::Bool(true)) {
type_var = Value::Str("option".to_string());
} else if is_equal(&get_value(&firstMarket, &Value::Str("contract".to_string())), &Value::Bool(true)) {
type_var = ternary(is_true(&(is_equal(&get_value(&firstMarket, &Value::Str("linear".to_string())), &Value::Bool(true)))), Value::Str("future".to_string()), Value::Str("delivery".to_string()));
}
let mut messageHashes: Value = Value::List(vec![]);
let mut subParams: Value = Value::List(vec![]);
if is_equal(&isOption, &Value::Bool(true)) {
let mut seenUnderlyings: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_63: bool = true;
while { if !__for_first_63 { i = add(&i, &Value::Int(1)); } __for_first_63 = false; is_less_than(&i, &get_array_length(&symbols)) } {
let mut symbol: Value = get_value(&symbols, &i);
let mut symbol: Value = get_value(&symbols, &i);
let mut market: Value = self.market(symbol.clone());
append_to_array(&mut messageHashes, add(&Value::Str("trade::".to_string()), &symbol));
let mut baseIdLower: Value = self.safe_string_lower(market.clone(), Value::Str("baseId".to_string()), &[Value::Str("".to_string())]);
let mut quoteIdLower: Value = self.safe_string_lower(market.clone(), Value::Str("quoteId".to_string()), &[Value::Str("".to_string())]);
let mut underlying: Value = add(&add(&baseIdLower, &Value::Str("".to_string())), "eIdLower);
if !is_true(&(Value::Bool(in_op(&seenUnderlyings, &underlying)))) {
add_element_to_object(&mut seenUnderlyings, &underlying, Value::Bool(true));
append_to_array(&mut subParams, add(&underlying, &Value::Str("@optionTrade".to_string())));
}
}
}
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_64: bool = true;
while { if !__for_first_64 { i = add(&i, &Value::Int(1)); } __for_first_64 = false; is_less_than(&i, &get_array_length(&symbols)) } {
let mut symbol: Value = get_value(&symbols, &i);
let mut symbol: Value = get_value(&symbols, &i);
let mut market: Value = self.market(symbol.clone());
append_to_array(&mut messageHashes, add(&Value::Str("trade::".to_string()), &symbol));
let mut rawHash: Value = add(&add(&get_value(&market, &Value::Str("lowercaseId".to_string())), &Value::Str("@".to_string())), &name);
append_to_array(&mut subParams, rawHash.clone());
}
}
}
let mut query: Value = self.omit(params.clone(), Value::Str("type".to_string()), &[]);
let mut subParamsLength: Value = get_array_length(&subParams);
let mut url: Value = add(&add(&self.get_ws_url(type_var.clone(), self.get_future_ws_category(name.clone())), &Value::Str("/".to_string())), &self.stream(type_var.clone(), streamHash.clone(), &[subParamsLength.clone()]));
let mut requestId: Value = self.request_id(url.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("SUBSCRIBE".to_string()));
m.insert("params".to_string(), subParams.clone());
m.insert("id".to_string(), requestId.clone());
m
});
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m
});
let __ws_arg_6 = self.extend(request.clone(), &[query.clone()]);
let mut trades: Value = self.watch_multiple(url.clone(), messageHashes.clone(), &[__ws_arg_6, messageHashes.clone(), subscribe.clone()]).await;
if is_true(&self.newUpdates) {
let mut first: Value = self.safe_value(trades.clone(), Value::Int(0), &[]);
let mut tradeSymbol: Value = self.safe_string_k(first.clone(), "symbol", &[]);
limit = trades.get_limit(tradeSymbol.clone(), limit.clone());
}
return self.filter_by_since_limit(trades.clone(), &[since.clone(), limit.clone(), Value::Str("timestamp".to_string()), Value::Bool(true)]);
Value::Null
}
pub async fn un_watch_trades_for_symbols(&mut self, mut symbols: 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;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(true), Value::Bool(true)]);
let mut streamHash: Value = Value::Str("multipleTrades".to_string());
if !is_equal(&symbols, &Value::Null) {
let mut symbolsLength: Value = get_array_length(&symbols);
if is_greater_than(&symbolsLength, &Value::Int(200)) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" watchTradesForSymbols() accepts 200 symbols at most. To watch more symbols call watchTradesForSymbols() multiple times".to_string()))));
}
streamHash = add(&streamHash, &add(&Value::Str("::".to_string()), &join(&symbols, &Value::Str(",".to_string()))));
}
let mut name: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchTradesForSymbols".to_string()), Value::Str("name".to_string()), &[Value::Str("trade".to_string())]); name = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
params = self.omit(params.clone(), Value::Str("callerMethodName".to_string()), &[]);
let mut firstMarket: Value = self.market(get_value(&symbols, &Value::Int(0)));
let mut type_var: Value = get_value(&firstMarket, &Value::Str("type".to_string()));
let mut isOption: Value = get_value(&firstMarket, &Value::Str("option".to_string()));
if is_equal(&isOption, &Value::Bool(true)) {
type_var = Value::Str("option".to_string());
} else if is_equal(&get_value(&firstMarket, &Value::Str("contract".to_string())), &Value::Bool(true)) {
type_var = ternary(is_true(&(is_equal(&get_value(&firstMarket, &Value::Str("linear".to_string())), &Value::Bool(true)))), Value::Str("future".to_string()), Value::Str("delivery".to_string()));
}
let mut subMessageHashes: Value = Value::List(vec![]);
let mut subParams: Value = Value::List(vec![]);
let mut messageHashes: Value = Value::List(vec![]);
if is_equal(&isOption, &Value::Bool(true)) {
let mut seenUnderlyings: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_65: bool = true;
while { if !__for_first_65 { i = add(&i, &Value::Int(1)); } __for_first_65 = false; is_less_than(&i, &get_array_length(&symbols)) } {
let mut symbol: Value = get_value(&symbols, &i);
let mut symbol: Value = get_value(&symbols, &i);
let mut market: Value = self.market(symbol.clone());
append_to_array(&mut subMessageHashes, add(&Value::Str("trade::".to_string()), &symbol));
append_to_array(&mut messageHashes, add(&Value::Str("unsubscribe:trade:".to_string()), &symbol));
let mut baseIdLower: Value = self.safe_string_lower(market.clone(), Value::Str("baseId".to_string()), &[Value::Str("".to_string())]);
let mut quoteIdLower: Value = self.safe_string_lower(market.clone(), Value::Str("quoteId".to_string()), &[Value::Str("".to_string())]);
let mut underlying: Value = add(&add(&baseIdLower, &Value::Str("".to_string())), "eIdLower);
if !is_true(&(Value::Bool(in_op(&seenUnderlyings, &underlying)))) {
add_element_to_object(&mut seenUnderlyings, &underlying, Value::Bool(true));
append_to_array(&mut subParams, add(&underlying, &Value::Str("@optionTrade".to_string())));
}
}
}
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_66: bool = true;
while { if !__for_first_66 { i = add(&i, &Value::Int(1)); } __for_first_66 = false; is_less_than(&i, &get_array_length(&symbols)) } {
let mut symbol: Value = get_value(&symbols, &i);
let mut symbol: Value = get_value(&symbols, &i);
let mut market: Value = self.market(symbol.clone());
append_to_array(&mut subMessageHashes, add(&Value::Str("trade::".to_string()), &symbol));
append_to_array(&mut messageHashes, add(&Value::Str("unsubscribe:trade:".to_string()), &symbol));
let mut rawHash: Value = add(&add(&get_value(&market, &Value::Str("lowercaseId".to_string())), &Value::Str("@".to_string())), &name);
append_to_array(&mut subParams, rawHash.clone());
}
}
}
let mut query: Value = self.omit(params.clone(), Value::Str("type".to_string()), &[]);
let mut subParamsLength: Value = get_array_length(&subParams);
let mut url: Value = add(&add(&self.get_ws_url(type_var.clone(), self.get_future_ws_category(name.clone())), &Value::Str("/".to_string())), &self.stream(type_var.clone(), streamHash.clone(), &[subParamsLength.clone()]));
let mut requestId: Value = self.request_id(url.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("UNSUBSCRIBE".to_string()));
m.insert("params".to_string(), subParams.clone());
m.insert("id".to_string(), requestId.clone());
m
});
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(), to_string_val(&requestId));
m.insert("subMessageHashes".to_string(), subMessageHashes.clone());
m.insert("messageHashes".to_string(), messageHashes.clone());
m.insert("symbols".to_string(), symbols.clone());
m.insert("topic".to_string(), Value::Str("trades".to_string()));
m
});
let __ws_arg_7 = self.extend(request.clone(), &[query.clone()]);
return self.watch_multiple(url.clone(), messageHashes.clone(), &[__ws_arg_7, messageHashes.clone(), subscription.clone()]).await;
Value::Null
}
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
}));
return self.un_watch_trades_for_symbols(Value::List(vec![symbol.clone()]), &[params.clone()]).await;
Value::Null
}
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
}));
add_element_to_object(&mut params, &Value::Str("callerMethodName".to_string()), Value::Str("watchTrades".to_string()));
return self.watch_trades_for_symbols(Value::List(vec![symbol.clone()]), &[since.clone(), limit.clone(), params.clone()]).await;
Value::Null
}
pub fn parse_ws_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut executionType: Value = self.safe_string_k(trade.clone(), "x", &[]);
let mut isTradeExecution: bool = is_equal(&executionType, &Value::Str("TRADE".to_string()));
if !is_true(&isTradeExecution) {
return self.parse_trade(trade.clone(), &[market.clone()]);
}
let mut id: Value = self.safe_string2(trade.clone(), Value::Str("t".to_string()), Value::Str("a".to_string()), &[]);
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "T", &[]);
let mut price: Value = self.safe_string2(trade.clone(), Value::Str("L".to_string()), Value::Str("p".to_string()), &[]);
let mut amount: Value = self.safe_string_k(trade.clone(), "q", &[]);
if is_true(&isTradeExecution) {
amount = self.safe_string_k(trade.clone(), "l", &[amount.clone()]);
}
let mut cost: Value = self.safe_string_k(trade.clone(), "Y", &[]);
if is_equal(&cost, &Value::Null) {
if is_true(&(!is_equal(&price, &Value::Null))) && is_true(&(!is_equal(&amount, &Value::Null))) {
cost = crate::precise::Precise::stringMul(&price, &amount);
}
}
let mut marketId: Value = self.safe_string_k(trade.clone(), "s", &[]);
let mut fallbackType: Value = ternary(is_true(&(Value::Bool(in_op(&trade, &Value::Str("ps".to_string()))))), Value::Str("contract".to_string()), Value::Str("spot".to_string()));
let mut marketType: Value = ternary(is_true(&(!is_equal(&market, &Value::Null))), get_value(&market, &Value::Str("type".to_string())), fallbackType.clone());
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[market.clone(), Value::Null, marketType.clone()]);
let mut side: Value = self.safe_string_lower(trade.clone(), Value::Str("S".to_string()), &[]);
let mut takerOrMaker: Value = Value::Null;
let mut orderId: Value = self.safe_string_k(trade.clone(), "i", &[]);
if is_true(&Value::Bool(in_op(&trade, &Value::Str("m".to_string())))) {
if is_equal(&side, &Value::Null) {
side = ternary(is_true(&(is_equal(&get_value(&trade, &Value::Str("m".to_string())), &Value::Bool(true)))), Value::Str("sell".to_string()), Value::Str("buy".to_string())); }
takerOrMaker = ternary(is_true(&(is_equal(&get_value(&trade, &Value::Str("m".to_string())), &Value::Bool(true)))), Value::Str("maker".to_string()), Value::Str("taker".to_string()));
}
let mut fee: Value = Value::Null;
let mut feeCost: Value = self.safe_string_k(trade.clone(), "n", &[]);
if !is_equal(&feeCost, &Value::Null) {
let mut feeCurrencyId: Value = self.safe_string_k(trade.clone(), "N", &[]);
let mut feeCurrencyCode: Value = self.safe_currency_code(feeCurrencyId.clone(), &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost.clone());
m.insert("currency".to_string(), feeCurrencyCode.clone());
m
});
}
let mut type_var: Value = self.safe_string_lower(trade.clone(), Value::Str("o".to_string()), &[]);
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("symbol".to_string(), symbol.clone());
m.insert("id".to_string(), id.clone());
m.insert("order".to_string(), orderId.clone());
m.insert("type".to_string(), type_var.clone());
m.insert("takerOrMaker".to_string(), takerOrMaker.clone());
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), price.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("cost".to_string(), cost.clone());
m.insert("fee".to_string(), fee.clone());
m
}), &[]);
Value::Null
}
pub fn handle_trade(&mut self, mut client: Value, mut message: Value) {
let mut marketId: Value = self.safe_string_k(message.clone(), "s", &[]);
let mut isSpot: Value = self.is_spot_url(client.clone());
let mut marketType: Value = ternary(is_true(&isSpot), Value::Str("spot".to_string()), Value::Str("contract".to_string()));
let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, Value::Null, marketType.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut messageHash: Value = add(&Value::Str("trade::".to_string()), &symbol);
let mut trade: Value = self.parse_ws_trade(message.clone(), &[market.clone()]);
let mut tradesArray: Value = self.safe_value(self.trades.clone(), symbol.clone(), &[]);
if is_equal(&tradesArray, &Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
tradesArray = ArrayCache::new(limit.clone());
}
tradesArray.append(trade.clone());
add_element_to_object(&mut self.trades, &symbol, tradesArray.clone());
client.resolve(&[tradesArray.clone(), messageHash.clone()]);
}
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());
symbol = get_value(&market, &Value::Str("symbol".to_string()));
let mut stock: Value = self.safe_bool_k(market.clone(), "stock", &[Value::Bool(false)]);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOHLCV".to_string()), Value::Str("stock".to_string()), &[]); stock = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&stock, &Value::Bool(true)) {
if is_true(&(!is_equal(&timeframe, &Value::Str("5m".to_string())))) && is_true(&(!is_equal(&timeframe, &Value::Str("1h".to_string())))) && is_true(&(!is_equal(&timeframe, &Value::Str("1d".to_string())))) && is_true(&(!is_equal(&timeframe, &Value::Str("1w".to_string())))) && is_true(&(!is_equal(&timeframe, &Value::Str("1M".to_string())))) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" watchOHLCV only supports 5m, 1h, 1d, 1w, and 1M timeframes".to_string()))));
}
add_element_to_object(&mut params, &Value::Str("stock".to_string()), Value::Bool(true));
}
add_element_to_object(&mut params, &Value::Str("callerMethodName".to_string()), Value::Str("watchOHLCV".to_string()));
let mut result: Value = self.watch_ohlcv_for_symbols(Value::List(vec![Value::List(vec![symbol.clone(), timeframe.clone()])]), &[since.clone(), limit.clone(), params.clone()]).await;
return get_value(&get_value(&result, &symbol), &timeframe);
Value::Null
}
pub async fn watch_ohlcv_for_symbols(&mut self, mut symbolsAndTimeframes: 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 stock: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOHLCVForSymbols".to_string()), Value::Str("stock".to_string()), &[Value::Bool(false)]); stock = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&stock) {
let mut stockStreams: Value = Value::List(vec![]);
let mut stockMessageHashes: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_67: bool = true;
while { if !__for_first_67 { i = add(&i, &Value::Int(1)); } __for_first_67 = false; is_less_than(&i, &get_array_length(&symbolsAndTimeframes)) } {
let mut stockSymAndTf: Value = get_value(&symbolsAndTimeframes, &i);
let mut stockSymAndTf: Value = get_value(&symbolsAndTimeframes, &i);
let mut stockSymbolString: Value = self.symbol(get_value(&stockSymAndTf, &Value::Int(0)));
let mut stockMarket: Value = self.market(stockSymbolString.clone());
let mut stockTicker: Value = self.safe_string2(stockMarket.clone(), Value::Str("base".to_string()), Value::Str("id".to_string()), &[]);
let mut stockTickerString: Value = ternary(is_true(&(is_equal(&stockTicker, &Value::Null))), Value::Str("".to_string()), to_lower(&stockTicker));
let mut stockTimeframeString: Value = get_value(&stockSymAndTf, &Value::Int(1));
let mut stockInterval: Value = self.safe_string(self.timeframes.clone(), stockTimeframeString.clone(), &[stockTimeframeString.clone()]);
if is_true(&(!is_equal(&stockInterval, &Value::Str("5m".to_string())))) && is_true(&(!is_equal(&stockInterval, &Value::Str("1h".to_string())))) && is_true(&(!is_equal(&stockInterval, &Value::Str("1d".to_string())))) && is_true(&(!is_equal(&stockInterval, &Value::Str("1w".to_string())))) && is_true(&(!is_equal(&stockInterval, &Value::Str("1M".to_string())))) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" watchOHLCVForSymbols only supports 5m, 1h, 1d, 1w, and 1M timeframes".to_string()))));
}
append_to_array(&mut stockStreams, add(&add(&stockTickerString, &Value::Str("@kline_".to_string())), &stockInterval));
append_to_array(&mut stockMessageHashes, add(&add(&add(&Value::Str("ohlcv::".to_string()), &get_value(&stockMarket, &Value::Str("symbol".to_string()))), &Value::Str("::".to_string())), &stockTimeframeString));
}
}
let mut stockRes: Value = self.watch_stock_market_stream(stockStreams.clone(), stockMessageHashes.clone(), &[params.clone()]).await;
let mut stockSymbolstockTimeframestockCandlesVariable = stockRes;
let mut stockSymbol: Value = get_value(&stockSymbolstockTimeframestockCandlesVariable, &Value::Int(0));
let mut stockTimeframe: Value = get_value(&stockSymbolstockTimeframestockCandlesVariable, &Value::Int(1));
let mut stockCandles: Value = get_value(&stockSymbolstockTimeframestockCandlesVariable, &Value::Int(2));
if is_true(&self.newUpdates) {
limit = stockCandles.get_limit(stockSymbol.clone(), limit.clone());
}
let mut stockFiltered: Value = self.filter_by_since_limit(stockCandles.clone(), &[since.clone(), limit.clone(), Value::Int(0), Value::Bool(true)]);
return self.create_ohlcv_object(stockSymbol.clone(), stockTimeframe.clone(), stockFiltered.clone());
}
let mut klineType: Value = Value::Null;
{ let __destr_tmp = self.handle_param_string2(params.clone(), Value::Str("channel".to_string()), Value::Str("name".to_string()), &[Value::Str("kline".to_string())]); klineType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut symbols: Value = self.get_list_from_object_values(symbolsAndTimeframes.clone(), Value::Int(0));
let mut marketSymbols: Value = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(false), Value::Bool(true)]);
let mut firstMarket: Value = self.market(get_value(&marketSymbols, &Value::Int(0)));
let mut type_var: Value = get_value(&firstMarket, &Value::Str("type".to_string()));
let mut wsUrlType: Value = type_var.clone();
if is_equal(&get_value(&firstMarket, &Value::Str("option".to_string())), &Value::Bool(true)) {
type_var = Value::Str("option".to_string());
wsUrlType = Value::Str("optionMarket".to_string()); } else if is_equal(&get_value(&firstMarket, &Value::Str("contract".to_string())), &Value::Bool(true)) {
type_var = ternary(is_true(&(is_equal(&get_value(&firstMarket, &Value::Str("linear".to_string())), &Value::Bool(true)))), Value::Str("future".to_string()), Value::Str("delivery".to_string()));
wsUrlType = type_var.clone();
}
let mut isSpot: bool = is_equal(&type_var, &Value::Str("spot".to_string()));
let mut timezone: Value = Value::Null;
{ let __destr_tmp = self.handle_param_string(params.clone(), Value::Str("timezone".to_string()), &[]); timezone = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut isUtc8: bool = is_true(&(!is_equal(&timezone, &Value::Null))) && is_true(&(is_true(&(is_equal(&timezone, &Value::Str("+08:00".to_string())))) || is_true(&crate::precise::Precise::stringEq(&timezone, &Value::Str("8".to_string())))));
let mut rawHashes: Value = Value::List(vec![]);
let mut messageHashes: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_68: bool = true;
while { if !__for_first_68 { i = add(&i, &Value::Int(1)); } __for_first_68 = false; is_less_than(&i, &get_array_length(&symbolsAndTimeframes)) } {
let mut symAndTf: Value = get_value(&symbolsAndTimeframes, &i);
let mut symAndTf: Value = get_value(&symbolsAndTimeframes, &i);
let mut symbolString: Value = get_value(&symAndTf, &Value::Int(0));
let mut timeframeString: Value = get_value(&symAndTf, &Value::Int(1));
let mut interval: Value = self.safe_string(self.timeframes.clone(), timeframeString.clone(), &[timeframeString.clone()]);
let mut market: Value = self.market(symbolString.clone());
let mut marketId: Value = get_value(&market, &Value::Str("lowercaseId".to_string()));
if is_equal(&marketId, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" watchOHLCVForSymbols() marketId is required".to_string()))));
}
if is_equal(&klineType, &Value::Str("indexPriceKline".to_string())) {
marketId = replace_str(&marketId, &Value::Str("_perp".to_string()), &Value::Str("".to_string()));
}
let mut shouldUseUTC8: bool = is_true(&isUtc8) && is_true(&isSpot);
let mut suffix: Value = Value::Str("@+08:00".to_string());
let mut utcSuffix: Value = ternary(is_true(&shouldUseUTC8), suffix.clone(), Value::Str("".to_string()));
append_to_array(&mut rawHashes, add(&add(&add(&add(&add(&marketId, &Value::Str("@".to_string())), &klineType), &Value::Str("_".to_string())), &interval), &utcSuffix));
append_to_array(&mut messageHashes, add(&add(&add(&Value::Str("ohlcv::".to_string()), &get_value(&market, &Value::Str("symbol".to_string()))), &Value::Str("::".to_string())), &timeframeString));
}
}
let mut url: Value = add(&add(&self.get_ws_url(wsUrlType.clone(), self.get_future_ws_category(klineType.clone())), &Value::Str("/".to_string())), &self.stream(wsUrlType.clone(), Value::Str("multipleOHLCV".to_string()), &[]));
let mut requestId: Value = self.request_id(url.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("SUBSCRIBE".to_string()));
m.insert("params".to_string(), rawHashes.clone());
m.insert("id".to_string(), requestId.clone());
m
});
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m
});
params = self.omit(params.clone(), Value::Str("callerMethodName".to_string()), &[]);
let __ws_arg_8 = self.extend(request.clone(), &[params.clone()]);
let mut res: Value = self.watch_multiple(url.clone(), messageHashes.clone(), &[__ws_arg_8, messageHashes.clone(), subscribe.clone()]).await;
let mut symboltimeframecandlesVariable = res;
let mut symbol: Value = get_value(&symboltimeframecandlesVariable, &Value::Int(0));
let mut timeframe: Value = get_value(&symboltimeframecandlesVariable, &Value::Int(1));
let mut candles: Value = get_value(&symboltimeframecandlesVariable, &Value::Int(2));
if is_true(&self.newUpdates) {
limit = candles.get_limit(symbol.clone(), limit.clone());
}
let mut filtered: Value = self.filter_by_since_limit(candles.clone(), &[since.clone(), limit.clone(), Value::Int(0), Value::Bool(true)]);
return self.create_ohlcv_object(symbol.clone(), timeframe.clone(), filtered.clone());
Value::Null
}
pub async fn un_watch_ohlcv_for_symbols(&mut self, mut symbolsAndTimeframes: 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 klineType: Value = Value::Null;
{ let __destr_tmp = self.handle_param_string2(params.clone(), Value::Str("channel".to_string()), Value::Str("name".to_string()), &[Value::Str("kline".to_string())]); klineType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut symbols: Value = self.get_list_from_object_values(symbolsAndTimeframes.clone(), Value::Int(0));
let mut marketSymbols: Value = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(false), Value::Bool(true)]);
let mut firstMarket: Value = self.market(get_value(&marketSymbols, &Value::Int(0)));
let mut type_var: Value = get_value(&firstMarket, &Value::Str("type".to_string()));
let mut wsUrlType: Value = type_var.clone();
if is_equal(&get_value(&firstMarket, &Value::Str("option".to_string())), &Value::Bool(true)) {
type_var = Value::Str("option".to_string());
wsUrlType = Value::Str("optionMarket".to_string()); } else if is_equal(&get_value(&firstMarket, &Value::Str("contract".to_string())), &Value::Bool(true)) {
type_var = ternary(is_true(&(is_equal(&get_value(&firstMarket, &Value::Str("linear".to_string())), &Value::Bool(true)))), Value::Str("future".to_string()), Value::Str("delivery".to_string()));
wsUrlType = type_var.clone();
}
let mut isSpot: bool = is_equal(&type_var, &Value::Str("spot".to_string()));
let mut timezone: Value = Value::Null;
{ let __destr_tmp = self.handle_param_string(params.clone(), Value::Str("timezone".to_string()), &[]); timezone = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut isUtc8: bool = is_true(&(!is_equal(&timezone, &Value::Null))) && is_true(&(is_true(&(is_equal(&timezone, &Value::Str("+08:00".to_string())))) || is_true(&crate::precise::Precise::stringEq(&timezone, &Value::Str("8".to_string())))));
let mut rawHashes: Value = Value::List(vec![]);
let mut subMessageHashes: Value = Value::List(vec![]);
let mut messageHashes: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_69: bool = true;
while { if !__for_first_69 { i = add(&i, &Value::Int(1)); } __for_first_69 = false; is_less_than(&i, &get_array_length(&symbolsAndTimeframes)) } {
let mut symAndTf: Value = get_value(&symbolsAndTimeframes, &i);
let mut symAndTf: Value = get_value(&symbolsAndTimeframes, &i);
let mut symbolString: Value = get_value(&symAndTf, &Value::Int(0));
let mut timeframeString: Value = get_value(&symAndTf, &Value::Int(1));
let mut interval: Value = self.safe_string(self.timeframes.clone(), timeframeString.clone(), &[timeframeString.clone()]);
let mut market: Value = self.market(symbolString.clone());
let mut marketId: Value = get_value(&market, &Value::Str("lowercaseId".to_string()));
if is_equal(&marketId, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" unWatchOHLCVForSymbols() marketId is required".to_string()))));
}
if is_equal(&klineType, &Value::Str("indexPriceKline".to_string())) {
marketId = replace_str(&marketId, &Value::Str("_perp".to_string()), &Value::Str("".to_string()));
}
let mut shouldUseUTC8: bool = is_true(&isUtc8) && is_true(&isSpot);
let mut suffix: Value = Value::Str("@+08:00".to_string());
let mut utcSuffix: Value = ternary(is_true(&shouldUseUTC8), suffix.clone(), Value::Str("".to_string()));
append_to_array(&mut rawHashes, add(&add(&add(&add(&add(&marketId, &Value::Str("@".to_string())), &klineType), &Value::Str("_".to_string())), &interval), &utcSuffix));
append_to_array(&mut subMessageHashes, add(&add(&add(&Value::Str("ohlcv::".to_string()), &get_value(&market, &Value::Str("symbol".to_string()))), &Value::Str("::".to_string())), &timeframeString));
append_to_array(&mut messageHashes, add(&add(&add(&Value::Str("unsubscribe::ohlcv::".to_string()), &get_value(&market, &Value::Str("symbol".to_string()))), &Value::Str("::".to_string())), &timeframeString));
}
}
let mut url: Value = add(&add(&self.get_ws_url(wsUrlType.clone(), self.get_future_ws_category(klineType.clone())), &Value::Str("/".to_string())), &self.stream(wsUrlType.clone(), Value::Str("multipleOHLCV".to_string()), &[]));
let mut requestId: Value = self.request_id(url.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("UNSUBSCRIBE".to_string()));
m.insert("params".to_string(), rawHashes.clone());
m.insert("id".to_string(), requestId.clone());
m
});
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("id".to_string(), to_string_val(&requestId));
m.insert("symbols".to_string(), symbols.clone());
m.insert("symbolsAndTimeframes".to_string(), symbolsAndTimeframes.clone());
m.insert("subMessageHashes".to_string(), subMessageHashes.clone());
m.insert("messageHashes".to_string(), messageHashes.clone());
m.insert("topic".to_string(), Value::Str("ohlcv".to_string()));
m
});
params = self.omit(params.clone(), Value::Str("callerMethodName".to_string()), &[]);
let __ws_arg_9 = self.extend(request.clone(), &[params.clone()]);
return self.watch_multiple(url.clone(), messageHashes.clone(), &[__ws_arg_9, messageHashes.clone(), subscribe.clone()]).await;
Value::Null
}
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());
symbol = get_value(&market, &Value::Str("symbol".to_string()));
add_element_to_object(&mut params, &Value::Str("callerMethodName".to_string()), Value::Str("watchOHLCV".to_string()));
return self.un_watch_ohlcv_for_symbols(Value::List(vec![Value::List(vec![symbol.clone(), timeframe.clone()])]), &[params.clone()]).await;
Value::Null
}
pub fn handle_ohlcv(&mut self, mut client: Value, mut message: Value) {
let mut event: Value = self.safe_string_k(message.clone(), "e", &[]);
let mut eventMap: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("indexPrice_kline".to_string(), Value::Str("indexPriceKline".to_string()));
m.insert("markPrice_kline".to_string(), Value::Str("markPriceKline".to_string()));
m
});
event = self.safe_string(eventMap.clone(), event.clone(), &[event.clone()]);
let mut kline: Value = self.safe_value_k(message.clone(), "k", &[]);
let mut marketId: Value = self.safe_string2(kline.clone(), Value::Str("s".to_string()), Value::Str("ps".to_string()), &[]);
if is_equal(&event, &Value::Str("indexPriceKline".to_string())) {
marketId = self.safe_string_k(message.clone(), "ps", &[]);
}
let mut interval: Value = self.safe_string_k(kline.clone(), "i", &[]);
let mut unifiedTimeframe: Value = self.find_timeframe(interval.clone(), &[]);
let mut parsed: Value = Value::List(vec![self.safe_integer_k(kline.clone(), "t", &[]), self.safe_float_k(kline.clone(), "o", &[]), self.safe_float_k(kline.clone(), "h", &[]), self.safe_float_k(kline.clone(), "l", &[]), self.safe_float_k(kline.clone(), "c", &[]), self.safe_float_k(kline.clone(), "v", &[])]);
let mut isSpot: Value = self.is_spot_url(client.clone());
let mut marketType: Value = ternary(is_true(&isSpot), Value::Str("spot".to_string()), Value::Str("contract".to_string()));
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[Value::Null, Value::Null, marketType.clone()]);
let mut messageHash: Value = add(&add(&add(&Value::Str("ohlcv::".to_string()), &symbol), &Value::Str("::".to_string())), &unifiedTimeframe);
{ let __be_tmp = self.safe_value(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(self.safe_value(self.ohlcvs.clone(), symbol.clone(), &[]), unifiedTimeframe.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());
if !is_equal(&symbol, &Value::Null) && !is_equal(&unifiedTimeframe, &Value::Null) {
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.ohlcvs) }, &symbol), &unifiedTimeframe, stored.clone());
}
}
stored.append(parsed.clone());
let mut resolveData: Value = Value::List(vec![symbol.clone(), unifiedTimeframe.clone(), stored.clone()]);
client.resolve(&[resolveData.clone(), messageHash.clone()]);
}
pub async fn fetch_ticker_ws(&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 payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut type_var: Value = self.get_market_type(Value::Str("fetchTickerWs".to_string()), market.clone(), &[params.clone()]);
if !is_equal(&type_var, &Value::Str("future".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchTickerWs only supports swap markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &type_var);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_ticker_ws".to_string()).clone());
m
});
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchTickerWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
add_element_to_object(&mut payload, &Value::Str("returnRateLimits".to_string()), returnRateLimits.clone());
params = self.omit(params.clone(), Value::Str("test".to_string()), &[]);
let mut method: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchTickerWs".to_string()), Value::Str("method".to_string()), &[Value::Str("ticker.book".to_string())]); method = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), method.clone());
let __ws_arg_10 = self.extend(payload.clone(), &[params.clone()]);
m.insert("params".to_string(), self.sign_params(&[__ws_arg_10]));
m
});
let mut ticker: Value = self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
return ticker;
Value::Null
}
pub async fn fetch_ohlcv_ws(&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 marketType: Value = self.get_market_type(Value::Str("fetchOHLCVWs".to_string()), market.clone(), &[params.clone()]);
if !is_equal(&marketType, &Value::Str("spot".to_string())) && !is_equal(&marketType, &Value::Str("future".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchOHLCVWs only supports spot or swap markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &marketType);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOHLCVWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.market_id(symbol.clone()));
m.insert("returnRateLimits".to_string(), returnRateLimits.clone());
m.insert("interval".to_string(), get_value(&self.timeframes, &timeframe));
m
});
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
params = self.omit(params.clone(), Value::Str("until".to_string()), &[]);
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut payload, &Value::Str("startTime".to_string()), since.clone());
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut payload, &Value::Str("limit".to_string()), limit.clone());
}
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut payload, &Value::Str("endTime".to_string()), until.clone());
}
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), Value::Str("klines".to_string()));
m.insert("params".to_string(), self.extend(payload.clone(), &[params.clone()]));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_fetch_ohlcv".to_string()).clone());
m
});
return self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
Value::Null
}
pub fn handle_fetch_ohlcv(&self, mut client: Value, mut message: Value) {
let mut result: Value = self.safe_list_k(message.clone(), "result", &[]);
let mut parsed: Value = self.parse_ohlc_vs(result.clone(), &[]);
let mut messageHash: Value = self.safe_string_k(message.clone(), "id", &[]);
client.resolve(&[parsed.clone(), messageHash.clone()]);
}
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;
}
symbol = self.symbol(symbol.clone());
let __ws_arg_11 = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("callerMethodName".to_string(), Value::Str("watchTicker".to_string()));
m
})]);
let mut tickers: Value = self.watch_tickers(&[Value::List(vec![symbol.clone()]), __ws_arg_11]).await;
return get_value(&tickers, &symbol);
Value::Null
}
pub async fn watch_mark_price(&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;
}
symbol = self.symbol(symbol.clone());
let __ws_arg_12 = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("callerMethodName".to_string(), Value::Str("watchMarkPrice".to_string()));
m
})]);
let mut tickers: Value = self.watch_mark_prices(&[Value::List(vec![symbol.clone()]), __ws_arg_12]).await;
return get_value(&tickers, &symbol);
Value::Null
}
pub async fn watch_mark_prices(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut channelName: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchMarkPrices".to_string()), Value::Str("name".to_string()), &[Value::Str("markPrice".to_string())]); channelName = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut newTickers: Value = self.watch_multi_ticker_helper(Value::Str("watchMarkPrices".to_string()), channelName.clone(), &[symbols.clone(), params.clone()]).await;
if is_true(&self.newUpdates) {
return newTickers;
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".to_string()), &[symbols.clone()]);
Value::Null
}
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
}));
let mut stock: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchTickers".to_string()), Value::Str("stock".to_string()), &[Value::Bool(false)]); stock = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&stock) {
if is_equal(&symbols, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" watchTickers() with stock stream requires symbols".to_string()))));
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(false), Value::Bool(true)]);
let mut stockResult: Value = self.watch_stock_market_stream(Value::List(vec![Value::Str("price".to_string())]), Value::List(vec![Value::Str("stock:price".to_string())]), &[params.clone()]).await;
if is_true(&self.newUpdates) {
return stockResult;
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".to_string()), &[symbols.clone()]);
}
let mut channelName: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchTickers".to_string()), Value::Str("name".to_string()), &[Value::Str("miniTicker".to_string())]); channelName = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&channelName, &Value::Str("bookTicker".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" deprecation notice - to subscribe for bids-asks, use watch_bids_asks() method instead".to_string()))));
}
let mut newTickers: Value = self.watch_multi_ticker_helper(Value::Str("watchTickers".to_string()), channelName.clone(), &[symbols.clone(), params.clone()]).await;
if is_true(&self.newUpdates) {
return newTickers;
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".to_string()), &[symbols.clone()]);
Value::Null
}
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
}));
let mut channelName: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchTickers".to_string()), Value::Str("name".to_string()), &[Value::Str("ticker".to_string())]); channelName = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&channelName, &Value::Str("bookTicker".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" deprecation notice - to subscribe for bids-asks, use watch_bids_asks() method instead".to_string()))));
}
return self.watch_multi_ticker_helper(Value::Str("unWatchTickers".to_string()), channelName.clone(), &[symbols.clone(), params.clone(), Value::Bool(true)]).await;
Value::Null
}
pub async fn un_watch_mark_prices(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut channelName: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchMarkPrices".to_string()), Value::Str("name".to_string()), &[Value::Str("markPrice".to_string())]); channelName = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
return self.watch_multi_ticker_helper(Value::Str("unWatchMarkPrices".to_string()), channelName.clone(), &[symbols.clone(), params.clone(), Value::Bool(true)]).await;
Value::Null
}
pub async fn un_watch_mark_price(&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
}));
return self.un_watch_mark_prices(&[Value::List(vec![symbol.clone()]), params.clone()]).await;
Value::Null
}
pub async fn un_watch_bids_asks(&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
}));
return self.watch_multi_ticker_helper(Value::Str("unWatchBidsAsks".to_string()), Value::Str("bookTicker".to_string()), &[symbols.clone(), params.clone(), Value::Bool(true)]).await;
Value::Null
}
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
}));
return self.un_watch_tickers(&[Value::List(vec![symbol.clone()]), params.clone()]).await;
Value::Null
}
pub async fn watch_bids_asks(&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 stock: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchBidsAsks".to_string()), Value::Str("stock".to_string()), &[Value::Bool(false)]); stock = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&stock) {
if is_equal(&symbols, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" watchBidsAsks() with stock stream requires symbols".to_string()))));
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(false), Value::Bool(true)]);
let mut stockStreams: Value = Value::List(vec![]);
let mut stockMessageHashes: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_70: bool = true;
while { if !__for_first_70 { i = add(&i, &Value::Int(1)); } __for_first_70 = false; is_less_than(&i, &get_array_length(&symbols)) } {
let mut stockTicker: Value = self.get_stock_ticker_from_symbol(get_value(&symbols, &i));
append_to_array(&mut stockStreams, add(&stockTicker, &Value::Str("@quote".to_string())));
append_to_array(&mut stockMessageHashes, add(&Value::Str("stock:quote:".to_string()), &get_value(&symbols, &i)));
}
}
let mut stockResult: Value = self.watch_stock_market_stream(stockStreams.clone(), stockMessageHashes.clone(), &[params.clone()]).await;
if is_true(&self.newUpdates) {
return stockResult;
}
return self.filter_by_array(self.bidsasks.clone(), Value::Str("symbol".to_string()), &[symbols.clone()]);
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(true), Value::Bool(false), Value::Bool(true)]);
let mut result: Value = self.watch_multi_ticker_helper(Value::Str("watchBidsAsks".to_string()), Value::Str("bookTicker".to_string()), &[symbols.clone(), params.clone()]).await;
if is_true(&self.newUpdates) {
return result;
}
return self.filter_by_array(self.bidsasks.clone(), Value::Str("symbol".to_string()), &[symbols.clone()]);
Value::Null
}
pub async fn watch_multi_ticker_helper(&mut self, mut methodName: Value, mut channelName: Value, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut isUnsubscribe = get_arg(optional_args, 2, Value::Bool(false));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(true), Value::Bool(false), Value::Bool(true)]);
let mut isBidAsk: bool = is_equal(&channelName, &Value::Str("bookTicker".to_string()));
let mut isMarkPrice: bool = is_equal(&channelName, &Value::Str("markPrice".to_string()));
let mut use1sFreq: Value = self.safe_bool_k(params.clone(), "use1sFreq", &[Value::Bool(true)]);
let mut firstMarket: Value = Value::Null;
let mut marketType: Value = Value::Null;
let mut symbolsDefined: bool = !is_equal(&symbols, &Value::Null);
if !is_equal(&symbols, &Value::Null) {
firstMarket = self.market(get_value(&symbols, &Value::Int(0)));
}
let mut userDefaultType: Value = self.safe_string_k(self.options.clone(), "defaultType", &[]);
let mut defaultMarket: Value = ternary(is_true(&(is_true(&isMarkPrice) && !is_equal(&userDefaultType, &Value::Str("option".to_string())))), Value::Str("swap".to_string()), Value::Null);
{ let __destr_tmp = self.handle_market_type_and_params(methodName.clone(), &[firstMarket.clone(), params.clone(), defaultMarket.clone()]); marketType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.handle_sub_type_and_params(methodName.clone(), &[firstMarket.clone(), params.clone()]); subType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut isOptionMarkPrice: Value = Value::Bool(is_true(&isMarkPrice) && is_equal(&marketType, &Value::Str("option".to_string())));
let mut rawMarketType: Value = Value::Null;
if is_equal(&marketType, &Value::Str("option".to_string())) {
rawMarketType = ternary(is_true(&(isOptionMarkPrice)), Value::Str("optionMarket".to_string()), Value::Str("option".to_string()));
} else if is_true(&self.parent.is_linear(marketType.clone(), &[subType.clone()])) {
rawMarketType = Value::Str("future".to_string());
} else if is_true(&self.parent.is_inverse(marketType.clone(), &[subType.clone()])) {
rawMarketType = Value::Str("delivery".to_string());
} else if is_equal(&marketType, &Value::Str("spot".to_string())) {
rawMarketType = marketType.clone();
} else {
panic!("{}", crate::exchange_errors::not_supported(add(&add(&add(&self.id, &Value::Str(" ".to_string())), &methodName), &Value::Str("() does not support options markets".to_string()))));
}
let mut isOptionTicker: bool = is_equal(&marketType, &Value::Str("option".to_string())) && !is_true(&isMarkPrice) && !is_true(&isBidAsk);
if is_true(&isMarkPrice) && !is_true(&self.in_array(marketType.clone(), Value::List(vec![Value::Str("swap".to_string()), Value::Str("future".to_string()), Value::Str("option".to_string())]))) {
panic!("{}", crate::exchange_errors::not_supported(add(&add(&add(&add(&add(&self.id, &Value::Str(" ".to_string())), &methodName), &Value::Str("() does not support ".to_string())), &marketType), &Value::Str(" markets yet".to_string()))));
}
let mut subscriptionArgs: Value = Value::List(vec![]);
let mut messageHashes: Value = Value::List(vec![]);
let mut unsubscribeMessageHashes: Value = Value::List(vec![]);
let mut suffix: Value = Value::Str("".to_string());
if is_true(&isMarkPrice) && !is_true(&isOptionMarkPrice) {
suffix = ternary(is_true(&(is_equal(&use1sFreq, &Value::Bool(true)))), Value::Str("@1s".to_string()), Value::Str("".to_string()));
}
let mut unifiedPrefix: Value = Value::Null;
if is_true(&isBidAsk) {
unifiedPrefix = Value::Str("bidask".to_string());
} else if is_true(&isMarkPrice) {
unifiedPrefix = Value::Str("markPrice".to_string());
} else {
unifiedPrefix = Value::Str("ticker".to_string());
}
if !is_equal(&symbols, &Value::Null) {
let mut seenUnderlyings: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_71: bool = true;
while { if !__for_first_71 { i = add(&i, &Value::Int(1)); } __for_first_71 = false; is_less_than(&i, &get_array_length(&symbols)) } {
let mut symbol: Value = get_value(&symbols, &i);
let mut symbol: Value = get_value(&symbols, &i);
let mut market: Value = self.market(symbol.clone());
append_to_array(&mut messageHashes, add(&add(&add(&add(&unifiedPrefix, &Value::Str(":".to_string())), &channelName), &Value::Str("@".to_string())), &symbol));
if is_true(&isUnsubscribe) {
append_to_array(&mut unsubscribeMessageHashes, add(&add(&add(&add(&add(&Value::Str("unsubscribe::".to_string()), &unifiedPrefix), &Value::Str(":".to_string())), &channelName), &Value::Str("@".to_string())), &symbol));
}
if is_true(&isOptionMarkPrice) {
let mut baseIdLower: Value = self.safe_string_lower(market.clone(), Value::Str("baseId".to_string()), &[Value::Str("".to_string())]);
let mut quoteIdLower: Value = self.safe_string_lower(market.clone(), Value::Str("quoteId".to_string()), &[Value::Str("".to_string())]);
let mut underlying: Value = add(&add(&baseIdLower, &Value::Str("".to_string())), "eIdLower);
if !is_true(&(Value::Bool(in_op(&seenUnderlyings, &underlying)))) {
add_element_to_object(&mut seenUnderlyings, &underlying, Value::Bool(true));
append_to_array(&mut subscriptionArgs, add(&underlying, &Value::Str("@optionMarkPrice".to_string())));
}
} else if is_true(&isOptionTicker) {
let mut marketId: Value = self.safe_string_k(market.clone(), "id", &[Value::Str("".to_string())]);
let mut parts: Value = split(&marketId, &Value::Str("-".to_string()));
let mut expiryDate: Value = self.safe_string(parts.clone(), Value::Int(1), &[]);
let mut baseIdLower: Value = self.safe_string_lower(market.clone(), Value::Str("baseId".to_string()), &[Value::Str("".to_string())]);
let mut quoteIdLower: Value = self.safe_string_lower(market.clone(), Value::Str("quoteId".to_string()), &[Value::Str("".to_string())]);
let mut underlying: Value = add(&add(&baseIdLower, &Value::Str("".to_string())), "eIdLower);
let mut subscriptionArg: Value = add(&add(&underlying, &Value::Str("@optionTicker@".to_string())), &expiryDate);
if !is_true(&(Value::Bool(in_op(&seenUnderlyings, &subscriptionArg)))) {
add_element_to_object(&mut seenUnderlyings, &subscriptionArg, Value::Bool(true));
append_to_array(&mut subscriptionArgs, subscriptionArg.clone());
}
} else {
let mut streamId: Value = get_value(&market, &Value::Str("lowercaseId".to_string()));
append_to_array(&mut subscriptionArgs, add(&add(&add(&streamId, &Value::Str("@".to_string())), &channelName), &suffix));
}
}
}
} else {
if is_equal(&marketType, &Value::Str("option".to_string())) {
let mut underlying: Value = self.safe_string_lower(params.clone(), Value::Str("underlying".to_string()), &[]);
if is_equal(&underlying, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&add(&add(&self.id, &Value::Str(" ".to_string())), &methodName), &Value::Str("() requires either symbols or params[\"underlying\"] for eOptions".to_string()))));
}
if is_true(&isOptionTicker) {
let mut expirationDate: Value = self.safe_string_k(params.clone(), "expirationDate", &[]);
if is_equal(&expirationDate, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&add(&add(&self.id, &Value::Str(" ".to_string())), &methodName), &Value::Str("() requires params[\"expirationDate\"] (e.g. \"260227\") for eOptions tickers when no symbols are provided".to_string()))));
}
append_to_array(&mut subscriptionArgs, add(&add(&underlying, &Value::Str("@optionTicker@".to_string())), &expirationDate));
} else {
append_to_array(&mut subscriptionArgs, add(&underlying, &Value::Str("@optionMarkPrice".to_string())));
}
append_to_array(&mut messageHashes, add(&add(&unifiedPrefix, &Value::Str("s:".to_string())), &channelName));
append_to_array(&mut unsubscribeMessageHashes, add(&Value::Str("unsubscribe::".to_string()), &channelName));
} else if is_true(&isBidAsk) {
if is_equal(&marketType, &Value::Str("spot".to_string())) {
panic!("{}", crate::exchange_errors::arguments_required(add(&add(&add(&self.id, &Value::Str(" ".to_string())), &methodName), &Value::Str("() requires symbols for this channel for spot markets".to_string()))));
}
append_to_array(&mut subscriptionArgs, add(&Value::Str("!".to_string()), &channelName));
append_to_array(&mut messageHashes, add(&add(&unifiedPrefix, &Value::Str("s:".to_string())), &channelName));
append_to_array(&mut unsubscribeMessageHashes, add(&Value::Str("unsubscribe::".to_string()), &channelName));
} else if is_true(&isMarkPrice) {
append_to_array(&mut subscriptionArgs, add(&add(&add(&Value::Str("!".to_string()), &channelName), &Value::Str("@arr".to_string())), &suffix));
append_to_array(&mut messageHashes, add(&add(&unifiedPrefix, &Value::Str("s:".to_string())), &channelName));
append_to_array(&mut unsubscribeMessageHashes, add(&Value::Str("unsubscribe::".to_string()), &channelName));
} else {
append_to_array(&mut subscriptionArgs, add(&add(&Value::Str("!".to_string()), &channelName), &Value::Str("@arr".to_string())));
append_to_array(&mut messageHashes, add(&add(&unifiedPrefix, &Value::Str("s:".to_string())), &channelName));
append_to_array(&mut unsubscribeMessageHashes, add(&Value::Str("unsubscribe::".to_string()), &channelName));
}
}
let mut streamHash: Value = channelName.clone();
if !is_equal(&symbols, &Value::Null) {
streamHash = add(&add(&channelName, &Value::Str("::".to_string())), &join(&symbols, &Value::Str(",".to_string())));
}
let mut url: Value = add(&add(&self.get_ws_url(rawMarketType.clone(), self.get_future_ws_category(channelName.clone())), &Value::Str("/".to_string())), &self.stream(rawMarketType.clone(), streamHash.clone(), &[]));
let mut requestId: Value = self.request_id(url.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), ternary(is_true(&isUnsubscribe), Value::Str("UNSUBSCRIBE".to_string()), Value::Str("SUBSCRIBE".to_string())));
m.insert("params".to_string(), subscriptionArgs.clone());
m.insert("id".to_string(), requestId.clone());
m
});
let mut hashes: Value = messageHashes.clone();
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m
});
if is_true(&isUnsubscribe) {
subscription = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("id".to_string(), to_string_val(&requestId));
m.insert("subMessageHashes".to_string(), messageHashes.clone());
m.insert("messageHashes".to_string(), unsubscribeMessageHashes.clone());
m.insert("symbols".to_string(), symbols.clone());
m.insert("topic".to_string(), Value::Str("ticker".to_string()));
m
});
hashes = unsubscribeMessageHashes.clone();
}
let mut waitHashes: Value = hashes.clone();
if is_true(&isOptionMarkPrice) && !is_true(&isUnsubscribe) {
waitHashes = Value::List(vec![add(&add(&unifiedPrefix, &Value::Str("s:".to_string())), &channelName)]);
}
let __ws_arg_13 = self.deep_extend(request.clone(), &[params.clone()]);
let mut result: Value = self.watch_multiple(url.clone(), waitHashes.clone(), &[__ws_arg_13, hashes.clone(), subscription.clone()]).await;
if is_true(&isUnsubscribe) {
return result;
}
if !is_true(&symbolsDefined) || is_true(&isOptionMarkPrice) {
return result;
} else {
let mut newDict: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut newDict, &get_value(&result, &Value::Str("symbol".to_string())), result.clone());
return newDict;
}
Value::Null
}
pub fn parse_ws_ticker(&self, mut message: Value, mut marketType: Value) -> Value {
let mut marketId: Value = self.safe_string2(message.clone(), Value::Str("s".to_string()), Value::Str("symbol".to_string()), &[]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[Value::Null, Value::Null, marketType.clone()]);
let mut event: Value = self.safe_string_k(message.clone(), "e", &[Value::Str("bookTicker".to_string())]);
if is_equal(&event, &Value::Str("24hrTicker".to_string())) {
event = Value::Str("ticker".to_string());
}
if is_equal(&event, &Value::Str("markPriceUpdate".to_string())) || is_equal(&event, &Value::Str("markPrice".to_string())) {
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.clone());
m.insert("timestamp".to_string(), self.safe_integer_k(message.clone(), "E", &[]));
m.insert("datetime".to_string(), self.iso8601(self.safe_integer_k(message.clone(), "E", &[])));
m.insert("info".to_string(), message.clone());
m.insert("markPrice".to_string(), self.safe_string2(message.clone(), Value::Str("mp".to_string()), Value::Str("p".to_string()), &[]));
m.insert("indexPrice".to_string(), self.safe_string_k(message.clone(), "i", &[]));
m
}), &[]);
}
let mut timestamp: Value = Value::Null;
if is_equal(&event, &Value::Str("bookTicker".to_string())) {
timestamp = self.safe_integer2(message.clone(), Value::Str("E".to_string()), Value::Str("time".to_string()), &[]);
} else {
timestamp = self.safe_integer_n(message.clone(), Value::List(vec![Value::Str("C".to_string()), Value::Str("E".to_string()), Value::Str("time".to_string())]), &[]);
}
let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, Value::Null, marketType.clone()]);
let mut last: Value = self.safe_string2(message.clone(), Value::Str("c".to_string()), Value::Str("price".to_string()), &[]);
let mut baseVolume: Value = self.safe_string_k(message.clone(), "v", &[]);
let mut quoteVolume: Value = self.safe_string_k(message.clone(), "q", &[]);
if is_equal(&get_value(&market, &Value::Str("inverse".to_string())), &Value::Bool(true)) {
let mut contracts: Value = baseVolume.clone();
baseVolume = quoteVolume.clone();
let mut weightedAverage: Value = self.safe_string_k(message.clone(), "w", &[]);
if is_equal(&weightedAverage, &Value::Null) {
quoteVolume = crate::precise::Precise::stringMul(&contracts, &self.safe_string_k(market.clone(), "contractSize", &[]));
} else {
quoteVolume = crate::precise::Precise::stringMul(&baseVolume, &weightedAverage);
}
}
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("high".to_string(), self.safe_string_k(message.clone(), "h", &[]));
m.insert("low".to_string(), self.safe_string_k(message.clone(), "l", &[]));
m.insert("bid".to_string(), self.safe_string2(message.clone(), Value::Str("b".to_string()), Value::Str("bidPrice".to_string()), &[]));
m.insert("bidVolume".to_string(), self.safe_string2(message.clone(), Value::Str("B".to_string()), Value::Str("bidQty".to_string()), &[]));
m.insert("ask".to_string(), self.safe_string2(message.clone(), Value::Str("a".to_string()), Value::Str("askPrice".to_string()), &[]));
m.insert("askVolume".to_string(), self.safe_string2(message.clone(), Value::Str("A".to_string()), Value::Str("askQty".to_string()), &[]));
m.insert("vwap".to_string(), self.safe_string_k(message.clone(), "w", &[]));
m.insert("open".to_string(), self.safe_string_k(message.clone(), "o", &[]));
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last.clone());
m.insert("previousClose".to_string(), self.safe_string_k(message.clone(), "x", &[]));
m.insert("change".to_string(), self.safe_string_k(message.clone(), "p", &[]));
m.insert("percentage".to_string(), self.safe_string_k(message.clone(), "P", &[]));
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), baseVolume.clone());
m.insert("quoteVolume".to_string(), quoteVolume.clone());
m.insert("info".to_string(), message.clone());
m
}), &[market.clone()]);
Value::Null
}
pub fn handle_ticker_ws(&self, mut client: Value, mut message: Value) {
let mut messageHash: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut result: Value = self.safe_value_k(message.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ticker: Value = self.parse_ws_ticker(result.clone(), Value::Str("future".to_string()));
client.resolve(&[ticker.clone(), messageHash.clone()]);
}
pub fn handle_bids_asks(&mut self, mut client: Value, mut message: Value) {
self.handle_tickers_and_bids_asks(client.clone(), message.clone(), Value::Str("bidasks".to_string()));
}
pub fn handle_tickers(&mut self, mut client: Value, mut message: Value) {
self.handle_tickers_and_bids_asks(client.clone(), message.clone(), Value::Str("tickers".to_string()));
}
pub fn handle_mark_prices(&mut self, mut client: Value, mut message: Value) {
self.handle_tickers_and_bids_asks(client.clone(), message.clone(), Value::Str("markPrices".to_string()));
}
pub fn handle_tickers_and_bids_asks(&mut self, mut client: Value, mut message: Value, mut methodType: Value) {
let mut isBidAsk: bool = is_equal(&methodType, &Value::Str("bidasks".to_string()));
let mut isMarkPrice: bool = is_equal(&methodType, &Value::Str("markPrices".to_string()));
let mut unifiedPrefix: Value = Value::Null;
if is_true(&isBidAsk) {
unifiedPrefix = Value::Str("bidask".to_string());
} else if is_true(&isMarkPrice) {
unifiedPrefix = Value::Str("markPrice".to_string());
} else {
unifiedPrefix = Value::Str("ticker".to_string());
}
let mut channelName: Value = Value::Null;
let mut resolvedMessageHashes: Value = Value::List(vec![]);
let mut rawTickers: Value = Value::List(vec![]);
let mut newTickers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_true(&Value::Bool(is_array(&message))) {
rawTickers = message.clone();
} else {
append_to_array(&mut rawTickers, message.clone());
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_72: bool = true;
while { if !__for_first_72 { i = add(&i, &Value::Int(1)); } __for_first_72 = false; is_less_than(&i, &get_array_length(&rawTickers)) } {
let mut ticker: Value = get_value(&rawTickers, &i);
let mut ticker: Value = get_value(&rawTickers, &i);
let mut event: Value = self.safe_string_k(ticker.clone(), "e", &[]);
if is_true(&isBidAsk) {
event = Value::Str("bookTicker".to_string()); }
channelName = self.safe_string(get_value(&self.options, &Value::Str("tickerChannelsMap".to_string())), event.clone(), &[event.clone()]);
if is_equal(&channelName, &Value::Null) {
continue;
}
let mut tickerMarketId: Value = self.safe_string_k(ticker.clone(), "s", &[]);
let mut tickerMarketsByIdList: Value = self.safe_value(self.markets_by_id.clone(), tickerMarketId.clone(), &[]);
let mut numTickerMarkets: Value = ternary(is_true(&(is_equal(&tickerMarketsByIdList, &Value::Null))), Value::Int(0), get_array_length(&tickerMarketsByIdList));
let mut tickerMarketById: Value = ternary(is_true(&(is_equal(&numTickerMarkets, &Value::Int(1)))), self.safe_value(tickerMarketsByIdList.clone(), Value::Int(0), &[]), Value::Null);
let mut isSpot: Value = self.is_spot_url(client.clone());
let mut tickerFallbackType: Value = ternary(is_true(&isSpot), Value::Str("spot".to_string()), Value::Str("contract".to_string()));
let mut tickerMarketType: Value = ternary(is_true(&(!is_equal(&tickerMarketById, &Value::Null))), get_value(&tickerMarketById, &Value::Str("type".to_string())), tickerFallbackType.clone());
let mut parsedTicker: Value = self.parse_ws_ticker(ticker.clone(), tickerMarketType.clone());
let mut symbol: Value = get_value(&parsedTicker, &Value::Str("symbol".to_string()));
if !is_equal(&symbol, &Value::Null) {
add_element_to_object(&mut newTickers, &symbol, parsedTicker.clone());
}
if is_true(&isBidAsk) {
if !is_equal(&symbol, &Value::Null) {
add_element_to_object(&mut self.bidsasks, &symbol, parsedTicker.clone());
}
} else {
if !is_equal(&symbol, &Value::Null) {
add_element_to_object(&mut self.tickers, &symbol, parsedTicker.clone());
}
}
let mut messageHash: Value = add(&add(&add(&add(&unifiedPrefix, &Value::Str(":".to_string())), &channelName), &Value::Str("@".to_string())), &symbol);
append_to_array(&mut resolvedMessageHashes, messageHash.clone());
client.resolve(&[parsedTicker.clone(), messageHash.clone()]);
}
}
let mut length: Value = get_array_length(&resolvedMessageHashes);
if is_greater_than(&length, &Value::Int(0)) {
let mut batchMessageHash: Value = add(&add(&unifiedPrefix, &Value::Str("s:".to_string())), &channelName);
client.resolve(&[newTickers.clone(), batchMessageHash.clone()]);
}
}
pub fn sign_params(&self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
let mut defaultRecvWindow: Value = self.safe_integer_k(self.options.clone(), "recvWindow", &[]);
if !is_equal(&defaultRecvWindow, &Value::Null) {
add_element_to_object(&mut params, &Value::Str("recvWindow".to_string()), defaultRecvWindow.clone());
}
let mut recvWindow: Value = self.safe_integer_k(params.clone(), "recvWindow", &[]);
if !is_equal(&recvWindow, &Value::Null) {
add_element_to_object(&mut params, &Value::Str("recvWindow".to_string()), recvWindow.clone());
}
let __ws_arg_14 = self.nonce();
let mut extendedParams: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timestamp".to_string(), __ws_arg_14);
m.insert("apiKey".to_string(), self.apiKey.clone());
m
}), &[params.clone()]);
extendedParams = self.keysort(extendedParams.clone(), &[]);
let mut query: Value = self.rawencode(extendedParams.clone(), &[]);
let mut signature: Value = Value::Null;
if is_greater_than(&get_index_of(&self.secret, &Value::Str("PRIVATE KEY".to_string())), &negate(&Value::Int(1))) {
if is_greater_than(&get_array_length(&self.secret), &Value::Int(120)) {
signature = rsa(query.clone(), self.secret.clone(), Value::Str("sha256".to_string()));
} else {
signature = eddsa(self.encode(query.clone()), self.secret.clone(), Value::Str("ed25519".to_string()));
}
} else {
signature = self.hmac(self.encode(query.clone()), self.encode(self.secret.clone()), Value::Str("sha256".to_string()), &[]);
}
add_element_to_object(&mut extendedParams, &Value::Str("signature".to_string()), signature.clone());
return extendedParams;
Value::Null
}
pub async fn ensure_user_data_stream_ws_subscribe_signature(&mut self, optional_args: &[Value]) -> Value {
let mut marketType = get_arg(optional_args, 0, Value::Str("spot".to_string()));
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &marketType);
let mut client: Value = self.client(&[url.clone()]);
let mut subscriptions: Value = get_value(&client, &Value::Str("subscriptions".to_string()));
let mut subscriptionsKeys: Value = object_keys(&subscriptions);
let mut accountType: Value = self.get_account_type_from_subscriptions(subscriptionsKeys.clone());
if is_equal(&accountType, &marketType) {
return Value::Null;
}
let mut messageHash: Value = add(&Value::Str("authenticate:signature:".to_string()), &marketType);
if is_true(&Value::Bool(in_op(&get_value(&client, &Value::Str("futures".to_string())), &messageHash))) {
crate::exchange_stubs::ws_await_flight(&client.future(&[messageHash.clone()])).await;
return Value::Null;
}
client.future(&[messageHash.clone()]); add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &marketType, Value::Bool(true));
let mut requestId: Value = self.request_id(url.clone());
let mut requestHash: Value = to_string_val(&requestId);
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestHash.clone());
m.insert("method".to_string(), Value::Str("userDataStream.subscribe.signature".to_string()));
m.insert("params".to_string(), self.sign_params(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestHash.clone());
m.insert("method".to_string(), Value::Str("handle_user_data_stream_subscribe".to_string()).clone());
m.insert("subscription".to_string(), marketType.clone());
m
});
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
self.watch(url.clone(), requestHash.clone(), &[message.clone(), requestHash.clone(), subscription.clone()]).await;
client.resolve(&[marketType.clone(), messageHash.clone()]);
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
remove(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &marketType);
client.reject(&[e.clone(), messageHash.clone()]);
panic!("{}", e);
}
Value::Null
}
pub fn handle_user_data_stream_subscribe(&self, mut client: Value, mut message: Value) {
let mut messageHash: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut subscriptions: Value = get_value(&client, &Value::Str("subscriptions".to_string()));
let mut subscriptionsKeys: Value = object_keys(&subscriptions);
let mut accountType: Value = self.get_account_type_from_subscriptions(subscriptionsKeys.clone());
let mut result: Value = self.safe_dict_k(message.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut subscriptionId: Value = self.safe_integer_k(result.clone(), "subscriptionId", &[]);
if is_equal(&subscriptionId, &Value::Null) {
remove(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &accountType);
client.reject(&[message.clone(), accountType.clone()]);
client.reject(&[message.clone(), messageHash.clone()]);
return;
}
client.resolve(&[message.clone(), messageHash.clone()]);
}
pub async fn ensure_user_data_stream_ws_subscribe_listen_token(&mut self, optional_args: &[Value]) -> Value {
let mut marketType = get_arg(optional_args, 0, Value::Str("margin".to_string()));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &Value::Str("spot".to_string()));
let mut options: Value = self.safe_dict(self.options.clone(), marketType.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut lastAuthenticatedTime: Value = self.safe_integer_k(options.clone(), "lastAuthenticatedTime", &[Value::Int(0)]);
let mut listenTokenRefreshRate: Value = self.safe_integer_k(self.options.clone(), "listenTokenRefreshRate", &[Value::Int(82800000)]); let mut time: Value = self.milliseconds();
let mut delay: Value = self.sum(&[listenTokenRefreshRate.clone(), Value::Int(10000)]);
if is_greater_than(&subtract(&time, &lastAuthenticatedTime), &delay) {
let mut client: Value = self.client(&[url.clone()]);
let mut messageHash: Value = add(&add(&Value::Str("authenticate:".to_string()), &marketType), &Value::Str(":listenToken".to_string()));
if is_true(&Value::Bool(in_op(&get_value(&client, &Value::Str("futures".to_string())), &messageHash))) {
crate::exchange_stubs::ws_await_flight(&client.future(&[messageHash.clone()])).await;
return Value::Null;
}
client.future(&[messageHash.clone()]); let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut symbol: Value = self.safe_string_k(params.clone(), "symbol", &[]);
let mut isIsolated: Value = self.safe_bool_k(params.clone(), "isIsolated", &[Value::Bool(false)]);
let mut validity: Value = self.safe_integer_k(params.clone(), "validity", &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_equal(&isIsolated, &Value::Bool(true)) {
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" ensureUserDataStreamWsSubscribeListenToken() requires a symbol argument for isolated margin mode".to_string()))));
}
let mut marketId: Value = self.market_id(symbol.clone());
add_element_to_object(&mut request, &Value::Str("symbol".to_string()), marketId.clone());
add_element_to_object(&mut request, &Value::Str("isIsolated".to_string()), Value::Bool(true));
}
if !is_equal(&validity, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("validity".to_string()), validity.clone());
}
let mut response: Value = self.parent.sapi_post_user_listen_token(&[request.clone()]).await;
let mut listenToken: Value = self.safe_string_k(response.clone(), "token", &[]);
if is_equal(&listenToken, &Value::Null) {
panic!("{}", crate::exchange_errors::authentication_error(add(&self.id, &Value::Str(" ensureUserDataStreamWsSubscribeListenToken() failed to obtain a listenToken".to_string()))));
}
let mut expirationTime: Value = self.safe_integer_k(response.clone(), "expirationTime", &[]);
let mut requestId: Value = self.request_id(url.clone());
let mut requestHash: Value = to_string_val(&requestId);
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestHash.clone());
m.insert("method".to_string(), Value::Str("userDataStream.subscribe.listenToken".to_string()));
m.insert("params".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("listenToken".to_string(), listenToken.clone());
m
}));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestHash.clone());
m.insert("method".to_string(), Value::Str("handle_user_data_stream_subscribe".to_string()).clone());
m.insert("subscription".to_string(), marketType.clone());
m
});
self.watch(url.clone(), requestHash.clone(), &[message.clone(), requestHash.clone(), subscription.clone()]).await;
{ let __be_tmp = self.extend(options.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("listenToken".to_string(), listenToken.clone());
m.insert("expirationTime".to_string(), expirationTime.clone());
m.insert("lastAuthenticatedTime".to_string(), time.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("isIsolated".to_string(), isIsolated.clone());
m.insert("validity".to_string(), validity.clone());
m
})]); add_element_to_object(&mut self.options, &marketType, __be_tmp); };
if !is_equal(&expirationTime, &Value::Null) {
let mut renewalTime: Value = subtract(&subtract(&expirationTime, &time), &Value::Int(60000)); if is_greater_than(&renewalTime, &Value::Int(0)) {
let mut extendedParams: Value = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), marketType.clone());
m
})]);
self.delay(renewalTime.clone(), &[Value::Str("renew_listen_token".to_string()).clone(), extendedParams.clone()]).await;
}
}
client.resolve(&[listenToken.clone(), messageHash.clone()]);
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
{ let __be_tmp = self.extend(options.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("lastAuthenticatedTime".to_string(), Value::Int(0));
m
})]); add_element_to_object(&mut self.options, &marketType, __be_tmp); };
client.reject(&[e.clone(), messageHash.clone()]);
panic!("{}", e);
}
}
Value::Null
}
pub async fn renew_listen_token(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut type_var: Value = self.safe_string_k(params.clone(), "type", &[Value::Str("margin".to_string())]);
let mut options: Value = self.safe_dict(self.options.clone(), type_var.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut symbol: Value = self.safe_string_k(options.clone(), "symbol", &[]);
let mut isIsolated: Value = self.safe_bool_k(options.clone(), "isIsolated", &[Value::Bool(false)]);
let mut validity: Value = self.safe_integer_k(options.clone(), "validity", &[]);
let mut renewParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&symbol, &Value::Null) {
add_element_to_object(&mut renewParams, &Value::Str("symbol".to_string()), symbol.clone());
}
if is_equal(&isIsolated, &Value::Bool(true)) {
add_element_to_object(&mut renewParams, &Value::Str("isIsolated".to_string()), isIsolated.clone());
}
if !is_equal(&validity, &Value::Null) {
add_element_to_object(&mut renewParams, &Value::Str("validity".to_string()), validity.clone());
}
self.ensure_user_data_stream_ws_subscribe_listen_token(&[type_var.clone(), renewParams.clone()]).await;
Value::Null
}
pub async fn authenticate(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut time: Value = self.milliseconds();
let mut resolvedAuth: Value = self.resolve_auth_type(Value::Str("authenticate".to_string()), &[Value::Null, params.clone()]);
let mut type_var: Value = get_value(&resolvedAuth, &Value::Int(0));
params = get_value(&resolvedAuth, &Value::Int(2));
let mut isPortfolioMargin: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("authenticate".to_string()), Value::Str("papi".to_string()), Value::Str("portfolioMargin".to_string()), &[Value::Bool(false)]); isPortfolioMargin = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&type_var, &Value::Str("spot".to_string())) {
self.ensure_user_data_stream_ws_subscribe_signature(&[Value::Str("spot".to_string())]).await;
return Value::Null;
}
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("authenticate".to_string()), &[params.clone()]); marginMode = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut isIsolatedMargin: bool = is_equal(&marginMode, &Value::Str("isolated".to_string()));
let mut symbol: Value = self.safe_string_k(params.clone(), "symbol", &[]);
if is_equal(&type_var, &Value::Str("margin".to_string())) || is_true(&isIsolatedMargin) {
let mut marginParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&symbol, &Value::Null) {
add_element_to_object(&mut marginParams, &Value::Str("symbol".to_string()), symbol.clone());
}
if is_true(&isIsolatedMargin) {
add_element_to_object(&mut marginParams, &Value::Str("isIsolated".to_string()), Value::Bool(true));
}
self.ensure_user_data_stream_ws_subscribe_listen_token(&[Value::Str("margin".to_string()), marginParams.clone()]).await;
return Value::Null;
}
params = self.omit(params.clone(), Value::Str("symbol".to_string()), &[]);
let mut isStock: bool = is_equal(&type_var, &Value::Str("stock".to_string()));
let mut options: Value = self.safe_value(self.options.clone(), type_var.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut lastAuthenticatedTime: Value = self.safe_integer_k(options.clone(), "lastAuthenticatedTime", &[Value::Int(0)]);
let mut refreshRateKey: Value = ternary(is_true(&isStock), Value::Str("stockListenKeyRefreshRate".to_string()), Value::Str("listenKeyRefreshRate".to_string()));
let mut listenKeyRefreshRate: Value = self.safe_integer(self.options.clone(), refreshRateKey.clone(), &[Value::Int(1200000)]);
let mut delay: Value = self.sum(&[listenKeyRefreshRate.clone(), Value::Int(10000)]);
if is_greater_than(&subtract(&time, &lastAuthenticatedTime), &delay) {
let mut messageHash: Value = add(&Value::Str("authenticate:".to_string()), &type_var);
let mut client: Value = self.client(&[Value::Str("authenticationFlights".to_string())]);
if is_true(&Value::Bool(in_op(&get_value(&client, &Value::Str("futures".to_string())), &messageHash))) {
crate::exchange_stubs::ws_await_flight(&client.future(&[messageHash.clone()])).await;
return Value::Null;
}
let mut future: Value = client.reusable_future(messageHash.clone());
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut response: Value = Value::Null;
if is_true(&isStock) {
let mut requestParams: Value = self.omit(params.clone(), Value::List(vec![Value::Str("stock".to_string()), Value::Str("name".to_string()), Value::Str("callerMethodName".to_string()), Value::Str("type".to_string()), Value::Str("subType".to_string()), Value::Str("symbol".to_string()), Value::Str("timeframe".to_string())]), &[]);
response = self.parent.sapi_post_equity_listen_key(&[requestParams.clone()]).await;
} else if is_true(&isPortfolioMargin) {
response = self.parent.papi_post_listen_key(&[params.clone()]).await;
params = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("portfolioMargin".to_string(), Value::Bool(true));
m
})]);
} else if is_equal(&type_var, &Value::Str("future".to_string())) {
response = self.parent.fapi_private_post_listen_key(&[params.clone()]).await;
} else if is_equal(&type_var, &Value::Str("delivery".to_string())) {
response = self.parent.dapi_private_post_listen_key(&[params.clone()]).await;
} else if is_equal(&type_var, &Value::Str("option".to_string())) {
response = self.parent.eapi_private_post_listen_key(&[params.clone()]).await;
} else {
response = self.parent.public_post_user_data_stream(&[params.clone()]).await;
}
let mut listenKey: Value = self.safe_string_k(response.clone(), "listenKey", &[]);
if is_equal(&listenKey, &Value::Null) {
panic!("{}", crate::exchange_errors::authentication_error(add(&self.id, &Value::Str(" authenticate() received an empty listenKey".to_string()))));
}
{ let __be_tmp = self.extend(options.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("listenKey".to_string(), listenKey.clone());
m.insert("lastAuthenticatedTime".to_string(), time.clone());
m
})]); add_element_to_object(&mut self.options, &type_var, __be_tmp); };
let mut delayParams: Value = params.clone();
if is_true(&isStock) {
delayParams = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("stock".to_string()));
m.insert("defaultType".to_string(), Value::Str("stock".to_string()));
m
})]);
}
self.delay(listenKeyRefreshRate.clone(), &[Value::Str("keep_alive_listen_key".to_string()).clone(), delayParams.clone()]).await;
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);
client.reject(&[e.clone(), messageHash.clone()]);
}
crate::exchange_stubs::ws_await_flight(&future).await;
}
Value::Null
}
pub async fn keep_alive_listen_key(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut type_var: Value = self.safe_string2(self.options.clone(), Value::Str("defaultType".to_string()), Value::Str("authenticate".to_string()), &[Value::Str("spot".to_string())]);
type_var = self.safe_string_k(params.clone(), "type", &[type_var.clone()]);
let mut isPortfolioMargin: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("keepAliveListenKey".to_string()), Value::Str("papi".to_string()), Value::Str("portfolioMargin".to_string()), &[Value::Bool(false)]); isPortfolioMargin = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut subTypeInfo: Value = self.handle_sub_type_and_params(Value::Str("keepAliveListenKey".to_string()), &[Value::Null, params.clone()]);
let mut subType: Value = get_value(&subTypeInfo, &Value::Int(0));
if !is_equal(&type_var, &Value::Str("option".to_string())) && !is_equal(&type_var, &Value::Str("stock".to_string())) {
if is_true(&self.parent.is_linear(type_var.clone(), &[subType.clone()])) {
type_var = Value::Str("future".to_string());
} else if is_true(&self.parent.is_inverse(type_var.clone(), &[subType.clone()])) {
type_var = Value::Str("delivery".to_string());
}
}
if is_equal(&type_var, &Value::Str("margin".to_string())) {
return Value::Null;
}
let mut isStock: bool = is_equal(&type_var, &Value::Str("stock".to_string()));
let mut options: Value = self.safe_value(self.options.clone(), type_var.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut listenKey: Value = self.safe_string_k(options.clone(), "listenKey", &[]);
if is_equal(&listenKey, &Value::Null) {
return Value::Null;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
params = self.omit(params.clone(), Value::List(vec![Value::Str("type".to_string()), Value::Str("symbol".to_string())]), &[]);
let mut time: Value = self.milliseconds();
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
if is_true(&isStock) {
let mut requestParams: Value = self.omit(params.clone(), Value::List(vec![Value::Str("stock".to_string()), Value::Str("name".to_string()), Value::Str("callerMethodName".to_string()), Value::Str("subType".to_string()), Value::Str("timeframe".to_string())]), &[]);
self.parent.sapi_post_equity_listen_key(&[requestParams.clone()]).await;
} else if is_true(&isPortfolioMargin) {
let __ws_arg_15 = self.extend(request.clone(), &[params.clone()]);
self.parent.papi_put_listen_key(&[__ws_arg_15]).await;
params = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("portfolioMargin".to_string(), Value::Bool(true));
m
})]);
} else if is_equal(&type_var, &Value::Str("future".to_string())) {
let __ws_arg_16 = self.extend(request.clone(), &[params.clone()]);
self.parent.fapi_private_put_listen_key(&[__ws_arg_16]).await;
} else if is_equal(&type_var, &Value::Str("delivery".to_string())) {
let __ws_arg_17 = self.extend(request.clone(), &[params.clone()]);
self.parent.dapi_private_put_listen_key(&[__ws_arg_17]).await;
} else if is_equal(&type_var, &Value::Str("option".to_string())) {
let __ws_arg_18 = self.extend(request.clone(), &[params.clone()]);
self.parent.eapi_private_put_listen_key(&[__ws_arg_18]).await;
} else {
add_element_to_object(&mut request, &Value::Str("listenKey".to_string()), listenKey.clone());
let __ws_arg_19 = self.extend(request.clone(), &[params.clone()]);
self.parent.public_put_user_data_stream(&[__ws_arg_19]).await;
}
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let error: Value = panic_to_value(_try_err);
let mut url: Value = Value::Null;
if is_true(&isStock) {
url = self.get_stock_ws_url(&[Value::Str("user".to_string())]);
} else {
let mut urlType: Value = type_var.clone();
if is_true(&isPortfolioMargin) {
urlType = Value::Str("papi".to_string());
}
if is_equal(&type_var, &Value::Str("option".to_string())) {
urlType = Value::Str("optionPrivate".to_string());
}
let mut cachedListenKey: Value = get_value(&get_value(&self.options, &type_var), &Value::Str("listenKey".to_string()));
url = self.get_private_ws_url(urlType.clone(), cachedListenKey.clone());
}
let mut client: Value = self.client(&[url.clone()]);
let mut messageHashes: Value = object_keys(&get_value(&client, &Value::Str("futures".to_string())));
{
let mut i: Value = Value::Int(0);
let mut __for_first_73: bool = true;
while { if !__for_first_73 { i = add(&i, &Value::Int(1)); } __for_first_73 = 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);
client.reject(&[Value::from(error.clone()), messageHash.clone()]);
}
}
{ let __be_tmp = self.extend(options.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("listenKey".to_string(), Value::Null);
m.insert("lastAuthenticatedTime".to_string(), Value::Int(0));
m
})]); add_element_to_object(&mut self.options, &type_var, __be_tmp); };
return Value::Null;
}
{ let __be_tmp = self.extend(options.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("listenKey".to_string(), listenKey.clone());
m.insert("lastAuthenticatedTime".to_string(), time.clone());
m
})]); add_element_to_object(&mut self.options, &type_var, __be_tmp); };
let mut clients: Value = object_values(&self.clients);
let mut refreshRateKey: Value = ternary(is_true(&isStock), Value::Str("stockListenKeyRefreshRate".to_string()), Value::Str("listenKeyRefreshRate".to_string()));
let mut listenKeyRefreshRate: Value = self.safe_integer(self.options.clone(), refreshRateKey.clone(), &[Value::Int(1200000)]);
let mut delayParams: Value = params.clone();
if is_true(&isStock) {
delayParams = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("stock".to_string()));
m
})]);
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_75: bool = true;
while { if !__for_first_75 { i = add(&i, &Value::Int(1)); } __for_first_75 = false; is_less_than(&i, &get_array_length(&clients)) } {
let mut client: Value = get_value(&clients, &i);
let mut client: Value = get_value(&clients, &i);
let mut clientSubscriptions: Value = self.safe_dict_k(client.clone(), "subscriptions", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut subscriptionKeys: Value = object_keys(&clientSubscriptions);
{
let mut j: Value = Value::Int(0);
let mut __for_first_74: bool = true;
while { if !__for_first_74 { j = add(&j, &Value::Int(1)); } __for_first_74 = false; is_less_than(&j, &get_array_length(&subscriptionKeys)) } {
let mut subscribeType: Value = get_value(&subscriptionKeys, &j);
let mut subscribeType: Value = get_value(&subscriptionKeys, &j);
if is_equal(&subscribeType, &type_var) {
self.delay(listenKeyRefreshRate.clone(), &[Value::Str("keep_alive_listen_key".to_string()).clone(), delayParams.clone()]).await;
return Value::Null;
}
}
}
}
}
Value::Null
}
pub fn set_balance_cache(&mut self, mut client: Value, mut type_var: Value, optional_args: &[Value]) {
let mut isPortfolioMargin = get_arg(optional_args, 0, Value::Bool(false));
if is_true(&(Value::Bool(in_op(&get_value(&client, &Value::Str("subscriptions".to_string())), &type_var)))) && is_true(&(Value::Bool(in_op(&self.balance, &type_var)))) {
return;
}
let mut options: Value = self.safe_value_k(self.options.clone(), "watchBalance", &[]);
let mut fetchBalanceSnapshot: Value = self.safe_bool_k(options.clone(), "fetchBalanceSnapshot", &[Value::Bool(false)]);
if is_equal(&fetchBalanceSnapshot, &Value::Bool(true)) {
let mut messageHash: Value = add(&type_var, &Value::Str(":fetchBalanceSnapshot".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_balance_snapshot".to_string()).clone(), client.clone(), messageHash.clone(), type_var.clone(), isPortfolioMargin.clone()]);
}
} else {
add_element_to_object(&mut self.balance, &type_var, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
}
}
pub async fn load_balance_snapshot(&mut self, mut client: Value, mut messageHash: Value, mut type_var: Value, mut isPortfolioMargin: Value) -> Value {
let mut params: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var.clone());
m
});
if is_equal(&isPortfolioMargin, &Value::Bool(true)) {
add_element_to_object(&mut params, &Value::Str("portfolioMargin".to_string()), Value::Bool(true));
}
let mut response: Value = self.fetch_balance(&[params.clone()]).await;
let __ws_arg_20 = self.safe_value(self.balance.clone(), type_var.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
{ let __be_tmp = self.extend(response.clone(), &[__ws_arg_20]); add_element_to_object(&mut self.balance, &type_var, __be_tmp); };
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(&[]);
client.resolve(&[get_value(&self.balance, &type_var), add(&type_var, &Value::Str(":balance".to_string()))]);
}
Value::Null
}
pub async fn fetch_balance_ws(&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 type_var: Value = self.get_market_type(Value::Str("fetchBalanceWs".to_string()), Value::Null, &[params.clone()]);
if !is_equal(&type_var, &Value::Str("spot".to_string())) && !is_equal(&type_var, &Value::Str("future".to_string())) && !is_equal(&type_var, &Value::Str("delivery".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchBalanceWs only supports spot or swap markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &type_var);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchBalanceWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("returnRateLimits".to_string(), returnRateLimits.clone());
m
});
let mut method: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchBalanceWs".to_string()), Value::Str("method".to_string()), &[Value::Str("account.status".to_string())]); method = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), method.clone());
let __ws_arg_21 = self.extend(payload.clone(), &[params.clone()]);
m.insert("params".to_string(), self.sign_params(&[__ws_arg_21]));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), ternary(is_true(&(is_equal(&method, &Value::Str("account.status".to_string())))), Value::Str("handle_account_status_ws".to_string()).clone(), Value::Str("handle_balance_ws".to_string()).clone()));
m
});
return self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
Value::Null
}
pub fn handle_balance_ws(&self, mut client: Value, mut message: Value) {
let mut messageHash: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut rawBalance: Value = Value::Null;
if is_true(&Value::Bool(is_array(&get_value(&message, &Value::Str("result".to_string()))))) {
rawBalance = self.safe_list_k(message.clone(), "result", &[Value::List(vec![])]);
} else {
let mut result: Value = self.safe_dict_k(message.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
rawBalance = self.safe_list_k(result.clone(), "assets", &[Value::List(vec![])]);
}
let mut parsedBalances: Value = self.parent.parse_balance_custom(rawBalance.clone(), &[]);
client.resolve(&[parsedBalances.clone(), messageHash.clone()]);
}
pub fn handle_account_status_ws(&self, mut client: Value, mut message: Value) {
let mut messageHash: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut result: Value = self.safe_dict_k(message.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut parsedBalances: Value = self.parent.parse_balance_custom(result.clone(), &[]);
client.resolve(&[parsedBalances.clone(), messageHash.clone()]);
}
pub async fn fetch_position_ws(&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
}));
return self.fetch_positions_ws(&[Value::List(vec![symbol.clone()]), params.clone()]).await;
Value::Null
}
pub async fn fetch_positions_ws(&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 payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
symbols = self.market_symbols(&[symbols.clone(), Value::Str("swap".to_string()), Value::Bool(true), Value::Bool(true), Value::Bool(true)]);
if !is_equal(&symbols, &Value::Null) {
let mut symbolsLength: Value = get_array_length(&symbols);
if is_equal(&symbolsLength, &Value::Int(1)) {
market = self.market(get_value(&symbols, &Value::Int(0)));
add_element_to_object(&mut payload, &Value::Str("symbol".to_string()), get_value(&market, &Value::Str("id".to_string())));
}
}
let mut type_var: Value = self.get_market_type(Value::Str("fetchPositionsWs".to_string()), market.clone(), &[params.clone()]);
if is_equal(&symbols, &Value::Null) && is_true(&(is_equal(&type_var, &Value::Str("spot".to_string())))) {
type_var = Value::Str("future".to_string());
}
if !is_equal(&type_var, &Value::Str("future".to_string())) && !is_equal(&type_var, &Value::Str("delivery".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchPositionsWs only supports swap markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &type_var);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchPositionsWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
add_element_to_object(&mut payload, &Value::Str("returnRateLimits".to_string()), returnRateLimits.clone());
let mut method: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchPositionsWs".to_string()), Value::Str("method".to_string()), &[Value::Str("account.position".to_string())]); method = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), method.clone());
let __ws_arg_22 = self.extend(payload.clone(), &[params.clone()]);
m.insert("params".to_string(), self.sign_params(&[__ws_arg_22]));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_positions_ws".to_string()).clone());
m
});
let mut result: Value = self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
return self.filter_by_array_positions(result.clone(), Value::Str("symbol".to_string()), &[symbols.clone(), Value::Bool(false)]);
Value::Null
}
pub fn handle_positions_ws(&self, mut client: Value, mut message: Value) {
let mut messageHash: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut result: Value = self.safe_list_k(message.clone(), "result", &[Value::List(vec![])]);
let mut positions: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_76: bool = true;
while { if !__for_first_76 { i = add(&i, &Value::Int(1)); } __for_first_76 = false; is_less_than(&i, &get_array_length(&result)) } {
let mut parsed: Value = self.parent.parse_position_risk(get_value(&result, &i), &[]);
let mut entryPrice: Value = self.safe_string_k(parsed.clone(), "entryPrice", &[]);
if is_true(&(!is_equal(&entryPrice, &Value::Str("0".to_string())))) && is_true(&(!is_equal(&entryPrice, &Value::Str("0.0".to_string())))) && is_true(&(!is_equal(&entryPrice, &Value::Str("0.00000000".to_string())))) {
append_to_array(&mut positions, parsed.clone());
}
}
}
client.resolve(&[positions.clone(), messageHash.clone()]);
}
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 type_var: Value = Value::Null;
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.resolve_auth_type(Value::Str("watchBalance".to_string()), &[Value::Null, params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); subType = get_value(&__destr_tmp, &Value::Int(1)); params = get_value(&__destr_tmp, &Value::Int(2)); }
let __ws_arg_23 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var.clone());
m.insert("subType".to_string(), subType.clone());
m
}), &[params.clone()]);
self.authenticate(&[__ws_arg_23]).await;
let mut isPortfolioMargin: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("watchBalance".to_string()), Value::Str("papi".to_string()), Value::Str("portfolioMargin".to_string()), &[Value::Bool(false)]); isPortfolioMargin = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut url: Value = Value::Str("".to_string());
let mut urlType: Value = type_var.clone();
if is_equal(&type_var, &Value::Str("spot".to_string())) || is_equal(&type_var, &Value::Str("margin".to_string())) {
url = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &Value::Str("spot".to_string()));
} else {
if is_true(&isPortfolioMargin) {
urlType = Value::Str("papi".to_string());
} else if is_equal(&type_var, &Value::Str("option".to_string())) {
let mut demoMode: Value = self.safe_bool_k(self.options.clone(), "enableDemoTrading", &[Value::Bool(false)]);
if is_true(&(is_equal(&demoMode, &Value::Bool(true)))) || is_true(&self.isSandboxModeEnabled) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" watchBalance() does not support option markets in demo/testnet mode".to_string()))));
}
urlType = Value::Str("optionPrivate".to_string());
}
url = self.get_private_ws_url(urlType.clone(), get_value(&get_value(&self.options, &type_var), &Value::Str("listenKey".to_string())));
}
let mut client: Value = self.client(&[url.clone()]);
self.set_balance_cache(client.clone(), type_var.clone(), &[isPortfolioMargin.clone()]);
self.set_positions_cache(client.clone(), type_var.clone(), &[Value::Null, isPortfolioMargin.clone()]);
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchBalance", &[]);
let mut fetchBalanceSnapshot: Value = self.safe_bool_k(options.clone(), "fetchBalanceSnapshot", &[Value::Bool(false)]);
let mut awaitBalanceSnapshot: Value = self.safe_bool_k(options.clone(), "awaitBalanceSnapshot", &[Value::Bool(true)]);
if is_true(&(is_equal(&fetchBalanceSnapshot, &Value::Bool(true)))) && is_true(&(is_equal(&awaitBalanceSnapshot, &Value::Bool(true)))) {
crate::exchange_stubs::ws_await_flight(&client.future(&[add(&type_var, &Value::Str(":fetchBalanceSnapshot".to_string()))])).await;
}
let mut messageHash: Value = add(&type_var, &Value::Str(":balance".to_string()));
let mut message: Value = Value::Null;
return self.watch(url.clone(), messageHash.clone(), &[message.clone(), type_var.clone()]).await;
Value::Null
}
pub fn handle_balance(&mut self, mut client: Value, mut message: Value) {
let mut wallet: Value = self.safe_string_k(self.options.clone(), "wallet", &[Value::Str("wb".to_string())]); let mut subscriptions: Value = get_value(&client, &Value::Str("subscriptions".to_string()));
let mut subscriptionsKeys: Value = object_keys(&subscriptions);
let mut accountType: Value = self.get_account_type_from_subscriptions(subscriptionsKeys.clone());
let mut messageHash: Value = add(&accountType, &Value::Str(":balance".to_string()));
if is_equal(&get_value(&self.balance, &accountType), &Value::Null) {
add_element_to_object(&mut self.balance, &accountType, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
}
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.balance) }, &accountType), &Value::Str("info".to_string()), message.clone());
let mut event: Value = self.safe_string_k(message.clone(), "e", &[]);
if is_equal(&event, &Value::Str("balanceUpdate".to_string())) {
let mut currencyId: Value = self.safe_string_k(message.clone(), "a", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut account: Value = self.account();
let mut delta: Value = self.safe_string_k(message.clone(), "d", &[]);
if is_true(&(!is_equal(&accountType, &Value::Null))) && is_true(&(!is_equal(&code, &Value::Null))) && is_true(&(Value::Bool(in_op(&get_value(&self.balance, &accountType), &code)))) {
let mut previousValue: Value = get_value(&get_value(&get_value(&self.balance, &accountType), &code), &Value::Str("free".to_string()));
if !is_string(&previousValue) {
previousValue = self.number_to_string(previousValue.clone());
}
add_element_to_object(&mut account, &Value::Str("free".to_string()), crate::precise::Precise::stringAdd(&previousValue, &delta));
} else {
add_element_to_object(&mut account, &Value::Str("free".to_string()), delta.clone());
}
if is_true(&(!is_equal(&accountType, &Value::Null))) && is_true(&(!is_equal(&code, &Value::Null))) {
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.balance) }, &accountType), &code, account.clone());
}
} else {
message = self.safe_dict_k(message.clone(), "a", &[message.clone()]);
let mut B: Value = self.safe_list_k(message.clone(), "B", &[]);
if is_equal(&B, &Value::Null) {
return;
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_77: bool = true;
while { if !__for_first_77 { i = add(&i, &Value::Int(1)); } __for_first_77 = false; is_less_than(&i, &get_array_length(&B)) } {
let mut entry: Value = get_value(&B, &i);
let mut entry: Value = get_value(&B, &i);
let mut currencyId: Value = self.safe_string_k(entry.clone(), "a", &[]);
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(entry.clone(), "f", &[]));
add_element_to_object(&mut account, &Value::Str("used".to_string()), self.safe_string_k(entry.clone(), "l", &[]));
add_element_to_object(&mut account, &Value::Str("total".to_string()), self.safe_string(entry.clone(), wallet.clone(), &[]));
if is_true(&(!is_equal(&accountType, &Value::Null))) && is_true(&(!is_equal(&code, &Value::Null))) {
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.balance) }, &accountType), &code, account.clone());
}
}
}
}
let mut timestamp: Value = self.safe_integer_k(message.clone(), "E", &[]);
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.balance) }, &accountType), &Value::Str("timestamp".to_string()), timestamp.clone());
{ let __be_tmp = self.iso8601(timestamp.clone()); add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.balance) }, &accountType), &Value::Str("datetime".to_string()), __be_tmp); };
{ let __be_tmp = self.safe_balance(get_value(&self.balance, &accountType)); add_element_to_object(&mut self.balance, &accountType, __be_tmp); };
client.resolve(&[get_value(&self.balance, &accountType), messageHash.clone()]);
}
pub fn get_account_type_from_subscriptions(&self, mut subscriptions: Value) -> Value {
let mut accountType: Value = Value::Str("".to_string());
{
let mut i: Value = Value::Int(0);
let mut __for_first_78: bool = true;
while { if !__for_first_78 { i = add(&i, &Value::Int(1)); } __for_first_78 = false; is_less_than(&i, &get_array_length(&subscriptions)) } {
let mut subscription: Value = get_value(&subscriptions, &i);
let mut subscription: Value = get_value(&subscriptions, &i);
if is_true(&(is_equal(&subscription, &Value::Str("spot".to_string())))) || is_true(&(is_equal(&subscription, &Value::Str("margin".to_string())))) || is_true(&(is_equal(&subscription, &Value::Str("future".to_string())))) || is_true(&(is_equal(&subscription, &Value::Str("delivery".to_string())))) || is_true(&(is_equal(&subscription, &Value::Str("option".to_string())))) {
accountType = subscription.clone();
break;
}
}
}
return accountType;
Value::Null
}
pub fn resolve_auth_type(&self, mut methodName: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut 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 subType: Value = Value::Null;
{ let __destr_tmp = self.handle_sub_type_and_params(methodName.clone(), &[market.clone(), params.clone()]); subType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if !is_equal(&type_var, &Value::Str("option".to_string())) && !is_equal(&type_var, &Value::Str("stock".to_string())) {
if is_true(&self.parent.is_linear(type_var.clone(), &[subType.clone()])) {
type_var = Value::Str("future".to_string());
} else if is_true(&self.parent.is_inverse(type_var.clone(), &[subType.clone()])) {
type_var = Value::Str("delivery".to_string());
}
}
return Value::List(vec![type_var.clone(), subType.clone(), params.clone()]);
Value::Null
}
pub fn get_market_type(&self, mut method: Value, mut market: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(method.clone(), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.handle_sub_type_and_params(method.clone(), &[market.clone(), params.clone()]); subType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&self.parent.is_linear(type_var.clone(), &[subType.clone()])) {
type_var = Value::Str("future".to_string());
} else if is_true(&self.parent.is_inverse(type_var.clone(), &[subType.clone()])) {
type_var = Value::Str("delivery".to_string());
}
return type_var;
Value::Null
}
pub async fn create_order_ws(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut marketType: Value = self.get_market_type(Value::Str("createOrderWs".to_string()), market.clone(), &[params.clone()]);
if !is_equal(&marketType, &Value::Str("spot".to_string())) && !is_equal(&marketType, &Value::Str("future".to_string())) && !is_equal(&marketType, &Value::Str("delivery".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" createOrderWs only supports spot or swap markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &marketType);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut sor: Value = self.safe_bool2(params.clone(), Value::Str("sor".to_string()), Value::Str("SOR".to_string()), &[Value::Bool(false)]);
params = self.omit(params.clone(), Value::Str("sor".to_string()), &[Value::Str("SOR".to_string())]);
let mut triggerPrice: Value = self.safe_string2(params.clone(), Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), &[]);
let mut stopLossPrice: Value = self.safe_string_k(params.clone(), "stopLossPrice", &[triggerPrice.clone()]);
let mut takeProfitPrice: Value = self.safe_string_k(params.clone(), "takeProfitPrice", &[]);
let mut trailingDelta: Value = self.safe_string_k(params.clone(), "trailingDelta", &[]);
let mut trailingPercent: Value = self.safe_string_n(params.clone(), Value::List(vec![Value::Str("trailingPercent".to_string()), Value::Str("callbackRate".to_string()), Value::Str("trailingDelta".to_string())]), &[]);
let mut isTrailingPercentOrder: bool = !is_equal(&trailingPercent, &Value::Null);
let mut isStopLoss: bool = !is_equal(&stopLossPrice, &Value::Null) || !is_equal(&trailingDelta, &Value::Null);
let mut isTakeProfit: bool = !is_equal(&takeProfitPrice, &Value::Null);
let mut isTriggerOrder: bool = !is_equal(&triggerPrice, &Value::Null);
let mut isConditional: bool = is_true(&isTriggerOrder) || is_true(&isTrailingPercentOrder) || is_true(&isStopLoss) || is_true(&isTakeProfit);
let mut payload: Value = self.parent.create_order_request(symbol.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params.clone()]);
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrderWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
add_element_to_object(&mut payload, &Value::Str("returnRateLimits".to_string()), returnRateLimits.clone());
let mut test: Value = self.safe_bool_k(params.clone(), "test", &[Value::Bool(false)]);
params = self.omit(params.clone(), Value::Str("test".to_string()), &[]);
if is_true(&(is_equal(&get_value(&market, &Value::Str("linear".to_string())), &Value::Bool(true)))) && is_true(&(is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)))) && is_true(&isConditional) {
add_element_to_object(&mut payload, &Value::Str("algoType".to_string()), Value::Str("CONDITIONAL".to_string()));
}
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), Value::Str("order.place".to_string()));
let __ws_arg_24 = self.extend(payload.clone(), &[params.clone()]);
m.insert("params".to_string(), self.sign_params(&[__ws_arg_24]));
m
});
if is_equal(&test, &Value::Bool(true)) {
if is_equal(&sor, &Value::Bool(true)) {
add_element_to_object(&mut message, &Value::Str("method".to_string()), Value::Str("sor.order.test".to_string()));
} else {
add_element_to_object(&mut message, &Value::Str("method".to_string()), Value::Str("order.test".to_string()));
}
}
if is_true(&(is_equal(&get_value(&market, &Value::Str("linear".to_string())), &Value::Bool(true)))) && is_true(&(is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)))) && is_true(&isConditional) {
add_element_to_object(&mut message, &Value::Str("method".to_string()), Value::Str("algoOrder.place".to_string()));
}
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_order_ws".to_string()).clone());
m
});
return self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
Value::Null
}
pub fn handle_order_ws(&self, mut client: Value, mut message: Value) {
let mut messageHash: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut result: Value = self.safe_dict_k(message.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut order: Value = self.parse_order(result.clone(), &[]);
client.resolve(&[order.clone(), messageHash.clone()]);
}
pub fn handle_orders_ws(&self, mut client: Value, mut message: Value) {
let mut messageHash: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut result: Value = self.safe_list_k(message.clone(), "result", &[Value::List(vec![])]);
let mut orders: Value = self.parse_orders(result.clone(), &[]);
client.resolve(&[orders.clone(), messageHash.clone()]);
}
pub async fn edit_order_ws(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut marketType: Value = self.get_market_type(Value::Str("editOrderWs".to_string()), market.clone(), &[params.clone()]);
if !is_equal(&marketType, &Value::Str("spot".to_string())) && !is_equal(&marketType, &Value::Str("future".to_string())) && !is_equal(&marketType, &Value::Str("delivery".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" editOrderWs only supports spot or swap markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &marketType);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut isSwap: Value = Value::Bool(is_equal(&marketType, &Value::Str("future".to_string())) || is_equal(&marketType, &Value::Str("delivery".to_string())));
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_equal(&marketType, &Value::Str("spot".to_string())) {
payload = self.parent.edit_spot_order_request(id.clone(), symbol.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params.clone()]);
} else {
payload = self.parent.edit_contract_order_request(id.clone(), symbol.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params.clone()]);
}
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("editOrderWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
add_element_to_object(&mut payload, &Value::Str("returnRateLimits".to_string()), returnRateLimits.clone());
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), ternary(is_true(&(isSwap)), Value::Str("order.modify".to_string()), Value::Str("order.cancelReplace".to_string())));
let __ws_arg_25 = self.extend(payload.clone(), &[params.clone()]);
m.insert("params".to_string(), self.sign_params(&[__ws_arg_25]));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_edit_order_ws".to_string()).clone());
m
});
return self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
Value::Null
}
pub fn handle_edit_order_ws(&self, mut client: Value, mut message: Value) {
let mut messageHash: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut result: Value = self.safe_dict_k(message.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut newSpotOrder: Value = self.safe_dict_k(result.clone(), "newOrderResponse", &[]);
let mut order: Value = Value::Null;
if !is_equal(&newSpotOrder, &Value::Null) {
order = self.parse_order(newSpotOrder.clone(), &[]);
} else {
order = self.parse_order(result.clone(), &[]);
}
client.resolve(&[order.clone(), messageHash.clone()]);
}
pub async fn cancel_order_ws(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" cancelOrderWs requires a symbol".to_string()))));
}
let mut market: Value = self.market(symbol.clone());
let mut type_var: Value = self.get_market_type(Value::Str("cancelOrderWs".to_string()), market.clone(), &[params.clone()]);
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &type_var);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("cancelOrderWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.market_id(symbol.clone()));
m.insert("returnRateLimits".to_string(), returnRateLimits.clone());
m
});
let mut isConditional: Value = self.safe_bool_n(params.clone(), Value::List(vec![Value::Str("stop".to_string()), Value::Str("trigger".to_string()), Value::Str("conditional".to_string())]), &[]);
let mut clientOrderId: Value = self.safe_string_n(params.clone(), Value::List(vec![Value::Str("clientAlgoId".to_string()), Value::Str("origClientOrderId".to_string()), Value::Str("clientOrderId".to_string())]), &[]);
let mut shouldUseAlgoOrder: Value = Value::Bool(is_true(&(is_equal(&get_value(&market, &Value::Str("linear".to_string())), &Value::Bool(true)))) && is_true(&(is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)))) && is_true(&(is_equal(&isConditional, &Value::Bool(true)))));
if !is_equal(&clientOrderId, &Value::Null) {
if is_equal(&shouldUseAlgoOrder, &Value::Bool(true)) {
add_element_to_object(&mut payload, &Value::Str("clientAlgoId".to_string()), clientOrderId.clone());
} else {
add_element_to_object(&mut payload, &Value::Str("origClientOrderId".to_string()), clientOrderId.clone());
}
} else {
if is_equal(&shouldUseAlgoOrder, &Value::Bool(true)) {
add_element_to_object(&mut payload, &Value::Str("algoId".to_string()), self.number_to_string(id.clone()));
} else {
add_element_to_object(&mut payload, &Value::Str("orderId".to_string()), self.number_to_string(id.clone()));
}
}
params = self.omit(params.clone(), Value::List(vec![Value::Str("origClientOrderId".to_string()), Value::Str("clientOrderId".to_string()), Value::Str("stop".to_string()), Value::Str("trigger".to_string()), Value::Str("conditional".to_string())]), &[]);
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), Value::Str("order.cancel".to_string()));
let __ws_arg_26 = self.extend(payload.clone(), &[params.clone()]);
m.insert("params".to_string(), self.sign_params(&[__ws_arg_26]));
m
});
if is_equal(&shouldUseAlgoOrder, &Value::Bool(true)) {
add_element_to_object(&mut message, &Value::Str("method".to_string()), Value::Str("algoOrder.cancel".to_string()));
}
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_order_ws".to_string()).clone());
m
});
return self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
Value::Null
}
pub async fn cancel_all_orders_ws(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelAllOrdersWs() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut type_var: Value = self.get_market_type(Value::Str("cancelAllOrdersWs".to_string()), market.clone(), &[params.clone()]);
if !is_equal(&type_var, &Value::Str("spot".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" cancelAllOrdersWs only supports spot markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &type_var);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("cancelAllOrdersWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.market_id(symbol.clone()));
m.insert("returnRateLimits".to_string(), returnRateLimits.clone());
m
});
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), Value::Str("openOrders.cancelAll".to_string()));
let __ws_arg_27 = self.extend(payload.clone(), &[params.clone()]);
m.insert("params".to_string(), self.sign_params(&[__ws_arg_27]));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_orders_ws".to_string()).clone());
m
});
return self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
Value::Null
}
pub async fn fetch_order_ws(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" cancelOrderWs requires a symbol".to_string()))));
}
let mut market: Value = self.market(symbol.clone());
let mut type_var: Value = self.get_market_type(Value::Str("fetchOrderWs".to_string()), market.clone(), &[params.clone()]);
if !is_equal(&type_var, &Value::Str("spot".to_string())) && !is_equal(&type_var, &Value::Str("future".to_string())) && !is_equal(&type_var, &Value::Str("delivery".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchOrderWs only supports spot or swap markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &type_var);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOrderWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.market_id(symbol.clone()));
m.insert("returnRateLimits".to_string(), returnRateLimits.clone());
m
});
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("origClientOrderId".to_string()), Value::Str("clientOrderId".to_string()), &[]);
if !is_equal(&clientOrderId, &Value::Null) {
add_element_to_object(&mut payload, &Value::Str("origClientOrderId".to_string()), clientOrderId.clone());
} else {
add_element_to_object(&mut payload, &Value::Str("orderId".to_string()), self.number_to_string(id.clone()));
}
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), Value::Str("order.status".to_string()));
let __ws_arg_28 = self.extend(payload.clone(), &[params.clone()]);
m.insert("params".to_string(), self.sign_params(&[__ws_arg_28]));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_order_ws".to_string()).clone());
m
});
return self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
Value::Null
}
pub async fn fetch_orders_ws(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchOrdersWs requires a symbol".to_string()))));
}
let mut market: Value = self.market(symbol.clone());
let mut type_var: Value = self.get_market_type(Value::Str("fetchOrdersWs".to_string()), market.clone(), &[params.clone()]);
if !is_equal(&type_var, &Value::Str("spot".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchOrdersWs only supports spot markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &type_var);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOrdersWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.market_id(symbol.clone()));
m.insert("returnRateLimits".to_string(), returnRateLimits.clone());
m
});
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), Value::Str("allOrders".to_string()));
let __ws_arg_29 = self.extend(payload.clone(), &[params.clone()]);
m.insert("params".to_string(), self.sign_params(&[__ws_arg_29]));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_orders_ws".to_string()).clone());
m
});
let mut orders: Value = self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
return self.filter_by_symbol_since_limit(orders.clone(), &[symbol.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub async fn fetch_closed_orders_ws(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut orders: Value = self.fetch_orders_ws(&[symbol.clone(), since.clone(), limit.clone(), params.clone()]).await;
let mut closedOrders: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_79: bool = true;
while { if !__for_first_79 { i = add(&i, &Value::Int(1)); } __for_first_79 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut order: Value = get_value(&orders, &i);
let mut order: Value = get_value(&orders, &i);
if is_equal(&get_value(&order, &Value::Str("status".to_string())), &Value::Str("closed".to_string())) {
append_to_array(&mut closedOrders, order.clone());
}
}
}
return closedOrders;
Value::Null
}
pub async fn fetch_open_orders_ws(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut type_var: Value = self.get_market_type(Value::Str("fetchOpenOrdersWs".to_string()), market.clone(), &[params.clone()]);
if !is_equal(&type_var, &Value::Str("spot".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchOpenOrdersWs only supports spot markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &type_var);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOpenOrdersWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("returnRateLimits".to_string(), returnRateLimits.clone());
m
});
if !is_equal(&symbol, &Value::Null) {
add_element_to_object(&mut payload, &Value::Str("symbol".to_string()), self.market_id(symbol.clone()));
}
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), Value::Str("openOrders.status".to_string()));
let __ws_arg_30 = self.extend(payload.clone(), &[params.clone()]);
m.insert("params".to_string(), self.sign_params(&[__ws_arg_30]));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_orders_ws".to_string()).clone());
m
});
let mut orders: Value = self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
return self.filter_by_symbol_since_limit(orders.clone(), &[symbol.clone(), since.clone(), limit.clone()]);
Value::Null
}
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 stock: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrders".to_string()), Value::Str("stock".to_string()), &[Value::Bool(false)]); stock = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&stock) {
let __ws_arg_31 = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("stock".to_string()));
m
})]);
self.authenticate(&[__ws_arg_31]).await;
let mut stockOptions: Value = self.safe_dict_k(self.options.clone(), "stock", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut stockListenKey: Value = self.safe_string_k(stockOptions.clone(), "listenKey", &[]);
if is_equal(&stockListenKey, &Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" watchOrders() failed to initialize stock listenKey".to_string()))));
}
let mut stockUrl: Value = self.get_stock_ws_url(&[Value::Str("user".to_string())]);
let mut stockStreamName: Value = add(&stockListenKey, &Value::Str("@orderReport".to_string()));
let mut stockRequestId: Value = self.request_id(stockUrl.clone());
let mut stockMessageHash: Value = Value::Str("orders".to_string());
if !is_equal(&symbol, &Value::Null) {
stockMessageHash = add(&Value::Str("orders:".to_string()), &self.symbol(symbol.clone()));
}
let mut stockRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("SUBSCRIBE".to_string()));
m.insert("params".to_string(), Value::List(vec![stockStreamName.clone()]));
m.insert("id".to_string(), stockRequestId.clone());
m
});
let mut stockQuery: Value = self.omit(params.clone(), Value::List(vec![Value::Str("stock".to_string()), Value::Str("name".to_string()), Value::Str("callerMethodName".to_string()), Value::Str("type".to_string()), Value::Str("subType".to_string()), Value::Str("symbol".to_string()), Value::Str("timeframe".to_string())]), &[]);
let mut stockSubscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), stockRequestId.clone());
m
});
let __ws_arg_32 = self.extend(stockRequest.clone(), &[stockQuery.clone()]);
let mut stockOrders: Value = self.watch(stockUrl.clone(), stockMessageHash.clone(), &[__ws_arg_32, stockMessageHash.clone(), stockSubscribe.clone()]).await;
if is_true(&self.newUpdates) {
limit = stockOrders.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_symbol_since_limit(stockOrders.clone(), &[symbol.clone(), since.clone(), limit.clone(), Value::Bool(true)]);
}
let mut messageHash: Value = Value::Str("orders".to_string());
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
symbol = get_value(&market, &Value::Str("symbol".to_string()));
messageHash = add(&messageHash, &add(&Value::Str(":".to_string()), &symbol));
}
let mut type_var: Value = Value::Null;
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.resolve_auth_type(Value::Str("watchOrders".to_string()), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); subType = get_value(&__destr_tmp, &Value::Int(1)); params = get_value(&__destr_tmp, &Value::Int(2)); }
params = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("subType".to_string(), subType.clone());
m
})]); self.authenticate(&[params.clone()]).await;
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("watchOrders".to_string()), &[params.clone()]); marginMode = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut urlType: Value = type_var.clone();
if is_true(&(is_equal(&type_var, &Value::Str("margin".to_string())))) || is_true(&(is_true(&(is_equal(&type_var, &Value::Str("spot".to_string())))) && is_true(&(!is_equal(&marginMode, &Value::Null))))) {
urlType = Value::Str("spot".to_string()); }
let mut isPortfolioMargin: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("watchOrders".to_string()), Value::Str("papi".to_string()), Value::Str("portfolioMargin".to_string()), &[Value::Bool(false)]); isPortfolioMargin = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut url: Value = Value::Str("".to_string());
if is_equal(&type_var, &Value::Str("spot".to_string())) || is_equal(&type_var, &Value::Str("margin".to_string())) {
url = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &Value::Str("spot".to_string()));
} else {
if is_true(&isPortfolioMargin) {
urlType = Value::Str("papi".to_string());
} else if is_equal(&type_var, &Value::Str("option".to_string())) {
let mut demoMode: Value = self.safe_bool_k(self.options.clone(), "enableDemoTrading", &[Value::Bool(false)]);
if is_true(&(is_equal(&demoMode, &Value::Bool(true)))) || is_true(&self.isSandboxModeEnabled) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" watchOrders() does not support option markets in demo/testnet mode".to_string()))));
}
urlType = Value::Str("optionPrivate".to_string());
}
url = self.get_private_ws_url(urlType.clone(), get_value(&get_value(&self.options, &type_var), &Value::Str("listenKey".to_string())));
}
let mut client: Value = self.client(&[url.clone()]);
self.set_balance_cache(client.clone(), type_var.clone(), &[isPortfolioMargin.clone()]);
self.set_positions_cache(client.clone(), type_var.clone(), &[Value::Null, isPortfolioMargin.clone()]);
let mut message: Value = Value::Null;
let mut orders: Value = self.watch(url.clone(), messageHash.clone(), &[message.clone(), type_var.clone()]).await;
if is_true(&self.newUpdates) {
limit = orders.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_symbol_since_limit(orders.clone(), &[symbol.clone(), since.clone(), limit.clone(), Value::Bool(true)]);
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);
let mut event: Value = self.safe_string_k(order.clone(), "e", &[]);
if is_equal(&event, &Value::Str("orderReport".to_string())) {
let mut baseAssetCode: Value = self.safe_string_k(order.clone(), "b", &[]);
let mut stockBaseSymbol: Value = baseAssetCode.clone();
if is_true(&(!is_equal(&stockBaseSymbol, &Value::Null))) && is_true(&(is_equal(&get_index_of(&stockBaseSymbol, &Value::Str("EQ_".to_string())), &Value::Int(0)))) {
stockBaseSymbol = slice(&stockBaseSymbol, &Value::Int(3), &Value::Null);
}
if is_equal(&stockBaseSymbol, &Value::Null) {
stockBaseSymbol = self.safe_string_k(order.clone(), "symbol", &[]);
}
let mut stockQuote: Value = self.safe_string_k(order.clone(), "q", &[Value::Str("USDC".to_string())]);
let mut stockSymbol: Value = self.get_stock_unified_symbol(stockBaseSymbol.clone(), &[stockQuote.clone()]);
let mut stockRawStatus: Value = self.safe_string_lower(order.clone(), Value::Str("s".to_string()), &[]);
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accepted".to_string(), Value::Str("open".to_string()));
m.insert("new".to_string(), Value::Str("open".to_string()));
m.insert("partially_filled".to_string(), Value::Str("open".to_string()));
m.insert("filled".to_string(), Value::Str("closed".to_string()));
m.insert("canceled".to_string(), Value::Str("canceled".to_string()));
m.insert("rejected".to_string(), Value::Str("rejected".to_string()));
m.insert("expired".to_string(), Value::Str("expired".to_string()));
m
});
let mut stockStatus: Value = self.safe_string(statuses.clone(), stockRawStatus.clone(), &[stockRawStatus.clone()]);
let mut stockAmount: Value = self.safe_string_k(order.clone(), "Q", &[]);
let mut stockFilled: Value = self.safe_string_k(order.clone(), "fq", &[]);
let mut stockRemaining: Value = Value::Null;
if is_true(&(!is_equal(&stockAmount, &Value::Null))) && is_true(&(!is_equal(&stockFilled, &Value::Null))) {
stockRemaining = crate::precise::Precise::stringSub(&stockAmount, &stockFilled);
}
let mut stockTimestamp: Value = self.safe_integer_k(order.clone(), "T", &[]);
let mut stockLastUpdateTimestamp: Value = self.safe_integer_k(order.clone(), "U", &[stockTimestamp.clone()]);
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("symbol".to_string(), stockSymbol.clone());
m.insert("id".to_string(), self.safe_string_k(order.clone(), "i", &[]));
m.insert("timestamp".to_string(), stockTimestamp.clone());
m.insert("datetime".to_string(), self.iso8601(stockTimestamp.clone()));
m.insert("lastUpdateTimestamp".to_string(), stockLastUpdateTimestamp.clone());
m.insert("type".to_string(), self.parent.parse_order_type_by_market(self.safe_string_lower(order.clone(), Value::Str("o".to_string()), &[]), Value::Str("spot".to_string())));
m.insert("timeInForce".to_string(), Value::Null);
m.insert("postOnly".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_lower(order.clone(), Value::Str("S".to_string()), &[]));
m.insert("price".to_string(), self.safe_string_k(order.clone(), "p", &[]));
m.insert("stopPrice".to_string(), Value::Null);
m.insert("triggerPrice".to_string(), Value::Null);
m.insert("amount".to_string(), stockAmount.clone());
m.insert("cost".to_string(), self.safe_string_k(order.clone(), "FN", &[]));
m.insert("average".to_string(), Value::Null);
m.insert("filled".to_string(), stockFilled.clone());
m.insert("remaining".to_string(), stockRemaining.clone());
m.insert("status".to_string(), stockStatus.clone());
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[]);
}
let mut executionType: Value = self.safe_string_k(order.clone(), "x", &[]);
let mut marketId: Value = self.safe_string_k(order.clone(), "s", &[]);
let mut marketType: Value = ternary(is_true(&(Value::Bool(in_op(&order, &Value::Str("ps".to_string()))))), Value::Str("contract".to_string()), Value::Str("spot".to_string()));
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[Value::Null, Value::Null, marketType.clone()]);
let mut timestamp: Value = self.safe_integer_k(order.clone(), "O", &[]);
let mut T: Value = self.safe_integer_k(order.clone(), "T", &[]);
let mut lastTradeTimestamp: Value = Value::Null;
if is_equal(&executionType, &Value::Str("NEW".to_string())) || is_equal(&executionType, &Value::Str("AMENDMENT".to_string())) || is_equal(&executionType, &Value::Str("CANCELED".to_string())) {
if is_equal(×tamp, &Value::Null) {
timestamp = T.clone();
}
} else if is_equal(&executionType, &Value::Str("TRADE".to_string())) {
lastTradeTimestamp = T.clone();
}
let mut lastUpdateTimestamp: Value = T.clone();
let mut fee: Value = Value::Null;
let mut feeCost: Value = self.safe_string_k(order.clone(), "n", &[]);
if is_true(&(!is_equal(&feeCost, &Value::Null))) && is_true(&(crate::precise::Precise::stringGt(&feeCost, &Value::Str("0".to_string())))) {
let mut feeCurrencyId: Value = self.safe_string_k(order.clone(), "N", &[]);
let mut feeCurrency: Value = self.safe_currency_code(feeCurrencyId.clone(), &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost.clone());
m.insert("currency".to_string(), feeCurrency.clone());
m
});
}
let mut rawStatus: Value = self.safe_string_k(order.clone(), "X", &[]);
let mut status: Value = self.parent.parse_order_status(rawStatus.clone());
let mut clientOrderId: Value = self.safe_string2(order.clone(), Value::Str("C".to_string()), Value::Str("caid".to_string()), &[]);
if is_true(&(is_equal(&clientOrderId, &Value::Null))) || is_true(&(is_equal(&get_array_length(&clientOrderId), &Value::Int(0)))) {
clientOrderId = self.safe_string_k(order.clone(), "c", &[]);
}
let mut stopPrice: Value = self.safe_string_n(order.clone(), Value::List(vec![Value::Str("P".to_string()), Value::Str("sp".to_string()), Value::Str("tp".to_string())]), &[]);
let mut timeInForce: Value = self.safe_string_k(order.clone(), "f", &[]);
if is_equal(&timeInForce, &Value::Str("GTX".to_string())) {
timeInForce = Value::Str("PO".to_string());
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("id".to_string(), self.safe_string2(order.clone(), Value::Str("i".to_string()), Value::Str("aid".to_string()), &[]));
m.insert("clientOrderId".to_string(), clientOrderId.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("lastTradeTimestamp".to_string(), lastTradeTimestamp.clone());
m.insert("lastUpdateTimestamp".to_string(), lastUpdateTimestamp.clone());
m.insert("type".to_string(), self.parent.parse_order_type_by_market(self.safe_string_lower(order.clone(), Value::Str("o".to_string()), &[]), marketType.clone()));
m.insert("timeInForce".to_string(), timeInForce.clone());
m.insert("postOnly".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), self.safe_bool_k(order.clone(), "R", &[]));
m.insert("side".to_string(), self.safe_string_lower(order.clone(), Value::Str("S".to_string()), &[]));
m.insert("price".to_string(), self.safe_string_k(order.clone(), "p", &[]));
m.insert("stopPrice".to_string(), stopPrice.clone());
m.insert("triggerPrice".to_string(), stopPrice.clone());
m.insert("amount".to_string(), self.safe_string_k(order.clone(), "q", &[]));
m.insert("cost".to_string(), self.safe_string_k(order.clone(), "Z", &[]));
m.insert("average".to_string(), self.safe_string_k(order.clone(), "ap", &[]));
m.insert("filled".to_string(), self.safe_string_k(order.clone(), "z", &[]));
m.insert("remaining".to_string(), Value::Null);
m.insert("status".to_string(), status.clone());
m.insert("fee".to_string(), fee.clone());
m.insert("trades".to_string(), Value::Null);
m
}), &[]);
Value::Null
}
pub fn handle_order_update(&mut self, mut client: Value, mut message: Value) {
let mut e: Value = self.safe_string_k(message.clone(), "e", &[]);
if is_equal(&e, &Value::Str("orderReport".to_string())) {
self.handle_order(client.clone(), message.clone());
return;
}
if is_true(&(is_equal(&e, &Value::Str("ORDER_TRADE_UPDATE".to_string())))) || is_true(&(is_equal(&e, &Value::Str("ALGO_UPDATE".to_string())))) {
let mut oField: Value = self.safe_value_k(message.clone(), "o", &[]);
if is_true(&Value::Bool(is_array(&oField))) {
self.handle_options_order_update(client.clone(), message.clone());
return;
}
message = self.safe_dict_k(message.clone(), "o", &[message.clone()]);
}
self.handle_my_trade(client.clone(), message.clone());
self.handle_order(client.clone(), message.clone());
self.handle_my_liquidation(client.clone(), message.clone());
}
pub fn handle_stock_price(&mut self, mut client: Value, mut message: Value) {
let mut rates: Value = self.safe_list_k(message.clone(), "rates", &[Value::List(vec![])]);
let mut tickers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_80: bool = true;
while { if !__for_first_80 { i = add(&i, &Value::Int(1)); } __for_first_80 = false; is_less_than(&i, &get_array_length(&rates)) } {
let mut rate: Value = self.safe_dict(rates.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut stockSymbol: Value = self.safe_string_k(rate.clone(), "s", &[]);
let mut symbol: Value = self.get_stock_unified_symbol(stockSymbol.clone(), &[Value::Str("USDC".to_string())]);
if is_equal(&symbol, &Value::Null) {
continue;
}
let mut timestamp: Value = self.safe_integer_k(rate.clone(), "t", &[]);
let mut parsed: Value = self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("last".to_string(), self.safe_string_k(rate.clone(), "p", &[]));
m.insert("close".to_string(), self.safe_string_k(rate.clone(), "p", &[]));
m.insert("previousClose".to_string(), self.safe_string_k(rate.clone(), "pc", &[]));
m.insert("info".to_string(), rate.clone());
m
}), &[]);
add_element_to_object(&mut self.tickers, &symbol, parsed.clone());
add_element_to_object(&mut tickers, &symbol, parsed.clone());
client.resolve(&[parsed.clone(), add(&Value::Str("stock:price:".to_string()), &symbol)]);
}
}
client.resolve(&[tickers.clone(), Value::Str("stock:price".to_string())]);
}
pub fn handle_stock_quote(&mut self, mut client: Value, mut message: Value) {
let mut stockSymbol: Value = self.safe_string_k(message.clone(), "s", &[]);
let mut symbol: Value = self.get_stock_unified_symbol(stockSymbol.clone(), &[Value::Str("USDC".to_string())]);
if is_equal(&symbol, &Value::Null) {
return;
}
let mut timestamp: Value = self.safe_integer2(message.clone(), Value::Str("E".to_string()), Value::Str("T".to_string()), &[]);
let mut parsed: Value = self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("bid".to_string(), self.safe_string_k(message.clone(), "bp", &[]));
m.insert("ask".to_string(), self.safe_string_k(message.clone(), "ap", &[]));
m.insert("bidVolume".to_string(), self.safe_string_k(message.clone(), "bs", &[]));
m.insert("askVolume".to_string(), self.safe_string_k(message.clone(), "as", &[]));
m.insert("info".to_string(), message.clone());
m
}), &[]);
add_element_to_object(&mut self.bidsasks, &symbol, parsed.clone());
client.resolve(&[parsed.clone(), add(&Value::Str("stock:quote:".to_string()), &symbol)]);
}
pub fn handle_options_order_update(&mut self, mut client: Value, mut message: Value) {
let mut orders: Value = self.safe_list_k(message.clone(), "o", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_82: bool = true;
while { if !__for_first_82 { i = add(&i, &Value::Int(1)); } __for_first_82 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut order: Value = get_value(&orders, &i);
let mut order: Value = get_value(&orders, &i);
let mut fills: Value = self.safe_list_k(order.clone(), "fi", &[Value::List(vec![])]);
let mut rawQty: Value = self.safe_string_k(order.clone(), "q", &[Value::Str("0".to_string())]);
let mut side: Value = Value::Str("BUY".to_string());
if is_true(&crate::precise::Precise::stringLt(&rawQty, &Value::Str("0".to_string()))) {
side = Value::Str("SELL".to_string());
}
let mut absQty: Value = crate::precise::Precise::stringAbs(&rawQty);
let mut executionType: Value = Value::Str("NEW".to_string());
if is_greater_than(&get_array_length(&fills), &Value::Int(0)) {
executionType = Value::Str("TRADE".to_string());
}
let mut normalizedOrder: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("s".to_string(), self.safe_string_k(order.clone(), "s", &[]));
m.insert("i".to_string(), self.safe_string_k(order.clone(), "oid", &[]));
m.insert("c".to_string(), self.safe_string_k(order.clone(), "c", &[]));
m.insert("S".to_string(), side.clone());
m.insert("o".to_string(), self.safe_string_k(order.clone(), "oty", &[]));
m.insert("f".to_string(), self.safe_string_k(order.clone(), "tif", &[]));
m.insert("q".to_string(), absQty.clone());
m.insert("p".to_string(), self.safe_string_k(order.clone(), "p", &[]));
m.insert("X".to_string(), self.safe_string_k(order.clone(), "S", &[]));
m.insert("x".to_string(), executionType.clone());
m.insert("z".to_string(), self.safe_string_k(order.clone(), "e", &[]));
m.insert("Z".to_string(), self.safe_string_k(order.clone(), "ec", &[]));
m.insert("n".to_string(), self.safe_string_k(order.clone(), "f", &[]));
m.insert("T".to_string(), self.safe_integer_k(order.clone(), "t", &[]));
m.insert("O".to_string(), self.safe_integer_k(order.clone(), "T", &[]));
m
});
self.handle_order(client.clone(), normalizedOrder.clone());
{
let mut j: Value = Value::Int(0);
let mut __for_first_81: bool = true;
while { if !__for_first_81 { j = add(&j, &Value::Int(1)); } __for_first_81 = false; is_less_than(&j, &get_array_length(&fills)) } {
let mut fill: Value = get_value(&fills, &j);
let mut fill: Value = get_value(&fills, &j);
let mut isMaker: Value = Value::Bool(is_equal(&self.safe_string_k(fill.clone(), "m", &[]), &Value::Str("MAKER".to_string())));
let mut normalizedTrade: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("x".to_string(), Value::Str("TRADE".to_string()));
m.insert("s".to_string(), self.safe_string_k(order.clone(), "s", &[]));
m.insert("t".to_string(), self.safe_string_k(fill.clone(), "t", &[]));
m.insert("L".to_string(), self.safe_string_k(fill.clone(), "p", &[]));
m.insert("l".to_string(), self.safe_string_k(fill.clone(), "q", &[]));
m.insert("T".to_string(), self.safe_integer_k(fill.clone(), "T", &[]));
m.insert("m".to_string(), isMaker.clone());
m.insert("n".to_string(), self.safe_string_k(fill.clone(), "f", &[]));
m.insert("i".to_string(), self.safe_string_k(order.clone(), "oid", &[]));
m.insert("S".to_string(), side.clone());
m.insert("o".to_string(), self.safe_string_k(order.clone(), "oty", &[]));
m
});
self.handle_my_trade(client.clone(), normalizedTrade.clone());
}
}
}
}
}
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 market: Value = Value::Null;
let mut messageHash: Value = Value::Str("".to_string());
symbols = self.market_symbols(&[symbols.clone()]);
if !is_true(&self.is_empty(symbols.clone())) {
market = self.get_market_from_symbols(&[symbols.clone()]);
if is_equal(&symbols, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" watchPositions() symbols is required".to_string()))));
}
messageHash = add(&Value::Str("::".to_string()), &join(&symbols, &Value::Str(",".to_string())));
}
let mut type_var: Value = Value::Null;
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.resolve_auth_type(Value::Str("watchPositions".to_string()), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); subType = get_value(&__destr_tmp, &Value::Int(1)); params = get_value(&__destr_tmp, &Value::Int(2)); }
if is_equal(&type_var, &Value::Str("spot".to_string())) || is_equal(&type_var, &Value::Str("margin".to_string())) {
type_var = ternary(is_true(&(is_equal(&subType, &Value::Str("inverse".to_string())))), Value::Str("delivery".to_string()), Value::Str("future".to_string()));
}
let mut marketTypeObject: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut marketTypeObject, &Value::Str("type".to_string()), type_var.clone());
add_element_to_object(&mut marketTypeObject, &Value::Str("subType".to_string()), subType.clone());
let __ws_arg_33 = self.extend(marketTypeObject.clone(), &[params.clone()]);
self.authenticate(&[__ws_arg_33]).await;
messageHash = add(&add(&type_var, &Value::Str(":positions".to_string())), &messageHash);
let mut isPortfolioMargin: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("watchPositions".to_string()), Value::Str("papi".to_string()), Value::Str("portfolioMargin".to_string()), &[Value::Bool(false)]); isPortfolioMargin = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut urlType: Value = type_var.clone();
if is_true(&isPortfolioMargin) {
urlType = Value::Str("papi".to_string());
} else if is_equal(&type_var, &Value::Str("option".to_string())) {
let mut demoMode: Value = self.safe_bool_k(self.options.clone(), "enableDemoTrading", &[Value::Bool(false)]);
if is_true(&(is_equal(&demoMode, &Value::Bool(true)))) || is_true(&self.isSandboxModeEnabled) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" watchPositions() does not support option markets in demo/testnet mode".to_string()))));
}
urlType = Value::Str("optionPrivate".to_string());
}
let mut url: Value = self.get_private_ws_url(urlType.clone(), get_value(&get_value(&self.options, &type_var), &Value::Str("listenKey".to_string())));
let mut client: Value = self.client(&[url.clone()]);
self.set_balance_cache(client.clone(), type_var.clone(), &[isPortfolioMargin.clone()]);
self.set_positions_cache(client.clone(), type_var.clone(), &[symbols.clone(), isPortfolioMargin.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.safe_value(self.positions.clone(), type_var.clone(), &[]);
if is_true(&(is_equal(&fetchPositionsSnapshot, &Value::Bool(true)))) && is_true(&(is_equal(&awaitPositionsSnapshot, &Value::Bool(true)))) && is_true(&(is_equal(&cache, &Value::Null))) {
let mut snapshot: Value = crate::exchange_stubs::ws_await_flight(&client.future(&[add(&type_var, &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 newPositions: Value = self.watch(url.clone(), messageHash.clone(), &[Value::Null, type_var.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
}
pub fn set_positions_cache(&mut self, mut client: Value, mut type_var: Value, optional_args: &[Value]) {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut isPortfolioMargin = get_arg(optional_args, 1, Value::Bool(false));
if is_equal(&type_var, &Value::Str("spot".to_string())) {
return;
}
if is_equal(&self.positions, &Value::Null) {
self.positions = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
if is_true(&Value::Bool(in_op(&self.positions, &type_var))) {
return;
}
let mut fetchPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".to_string()), Value::Str("fetchPositionsSnapshot".to_string()), &[Value::Bool(false)]);
if is_equal(&fetchPositionsSnapshot, &Value::Bool(true)) {
let mut messageHash: Value = add(&type_var, &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(), type_var.clone(), isPortfolioMargin.clone()]);
}
} else {
add_element_to_object(&mut self.positions, &type_var, ArrayCacheBySymbolBySide::new(Value::Null));
}
}
pub async fn load_positions_snapshot(&mut self, mut client: Value, mut messageHash: Value, mut type_var: Value, mut isPortfolioMargin: Value) -> Value {
let mut params: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var.clone());
m
});
if is_equal(&isPortfolioMargin, &Value::Bool(true)) {
add_element_to_object(&mut params, &Value::Str("portfolioMargin".to_string()), Value::Bool(true));
}
let mut positions: Value = self.fetch_positions(&[Value::Null, params.clone()]).await;
add_element_to_object(&mut self.positions, &type_var, ArrayCacheBySymbolBySide::new(Value::Null));
let mut cache: Value = get_value(&self.positions, &type_var);
{
let mut i: Value = Value::Int(0);
let mut __for_first_83: bool = true;
while { if !__for_first_83 { i = add(&i, &Value::Int(1)); } __for_first_83 = 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());
}
}
}
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(), add(&type_var, &Value::Str(":position".to_string()))]);
}
Value::Null
}
pub fn handle_positions(&mut self, mut client: Value, mut message: Value) {
let mut subscriptions: Value = get_value(&client, &Value::Str("subscriptions".to_string()));
let mut subscriptionsKeys: Value = object_keys(&subscriptions);
let mut accountType: Value = self.get_account_type_from_subscriptions(subscriptionsKeys.clone());
if is_equal(&self.positions, &Value::Null) {
self.positions = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
if !is_true(&(Value::Bool(in_op(&self.positions, &accountType)))) {
add_element_to_object(&mut self.positions, &accountType, ArrayCacheBySymbolBySide::new(Value::Null));
}
let mut cache: Value = get_value(&self.positions, &accountType);
let mut data: Value = self.safe_dict_k(message.clone(), "a", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawPositions: Value = self.safe_list_k(data.clone(), "P", &[Value::List(vec![])]);
let mut newPositions: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_84: bool = true;
while { if !__for_first_84 { i = add(&i, &Value::Int(1)); } __for_first_84 = false; is_less_than(&i, &get_array_length(&rawPositions)) } {
let mut rawPosition: Value = get_value(&rawPositions, &i);
let mut rawPosition: Value = get_value(&rawPositions, &i);
let mut position: Value = self.parse_ws_position(rawPosition.clone(), &[]);
let mut timestamp: Value = self.safe_integer_k(message.clone(), "E", &[]);
add_element_to_object(&mut position, &Value::Str("timestamp".to_string()), timestamp.clone());
add_element_to_object(&mut position, &Value::Str("datetime".to_string()), self.iso8601(timestamp.clone()));
append_to_array(&mut newPositions, position.clone());
cache.append(position.clone());
}
}
let mut messageHashes: Value = self.find_message_hashes(client.clone(), add(&accountType, &Value::Str(":positions::".to_string())));
{
let mut i: Value = Value::Int(0);
let mut __for_first_85: bool = true;
while { if !__for_first_85 { i = add(&i, &Value::Int(1)); } __for_first_85 = 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(newPositions.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(&[newPositions.clone(), add(&accountType, &Value::Str(":positions".to_string()))]);
}
pub fn parse_ws_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Value = self.safe_string_k(position.clone(), "s", &[]);
let mut contracts: Value = self.safe_string_k(position.clone(), "pa", &[]);
let mut contractsAbs: Value = crate::precise::Precise::stringAbs(&self.safe_string_k(position.clone(), "pa", &[]));
let mut positionSide: Value = self.safe_string_lower(position.clone(), Value::Str("ps".to_string()), &[]);
let mut hedged: Value = Value::Bool(true);
if is_equal(&positionSide, &Value::Str("both".to_string())) {
hedged = Value::Bool(false);
if !is_true(&crate::precise::Precise::stringEq(&contracts, &Value::Str("0".to_string()))) {
if is_true(&crate::precise::Precise::stringLt(&contracts, &Value::Str("0".to_string()))) {
positionSide = Value::Str("short".to_string());
} else {
positionSide = Value::Str("long".to_string());
}
}
}
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), Value::Null);
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[Value::Null, Value::Null, Value::Str("swap".to_string())]));
m.insert("notional".to_string(), Value::Null);
m.insert("marginMode".to_string(), self.safe_string_k(position.clone(), "mt", &[]));
m.insert("liquidationPrice".to_string(), Value::Null);
m.insert("entryPrice".to_string(), self.safe_number_k(position.clone(), "ep", &[]));
m.insert("unrealizedPnl".to_string(), self.safe_number_k(position.clone(), "up", &[]));
m.insert("percentage".to_string(), Value::Null);
m.insert("contracts".to_string(), self.parse_number(contractsAbs.clone(), &[]));
m.insert("contractSize".to_string(), Value::Null);
m.insert("markPrice".to_string(), Value::Null);
m.insert("side".to_string(), positionSide.clone());
m.insert("hedged".to_string(), hedged.clone());
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("collateral".to_string(), Value::Null);
m.insert("initialMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("leverage".to_string(), Value::Null);
m.insert("marginRatio".to_string(), Value::Null);
m
}));
Value::Null
}
pub fn parse_ws_options_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Value = self.safe_string_k(position.clone(), "s", &[]);
let mut contracts: Value = self.safe_string_k(position.clone(), "c", &[]);
let mut contractsAbs: Value = crate::precise::Precise::stringAbs(&contracts);
let mut side: Value = Value::Null;
if !is_equal(&contracts, &Value::Null) {
if is_true(&crate::precise::Precise::stringLt(&contracts, &Value::Str("0".to_string()))) {
side = Value::Str("short".to_string());
} else if is_true(&crate::precise::Precise::stringGt(&contracts, &Value::Str("0".to_string()))) {
side = Value::Str("long".to_string());
}
}
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), Value::Null);
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[market.clone(), Value::Null, Value::Str("option".to_string())]));
m.insert("notional".to_string(), self.safe_string_k(position.clone(), "p", &[]));
m.insert("marginMode".to_string(), Value::Null);
m.insert("liquidationPrice".to_string(), Value::Null);
m.insert("entryPrice".to_string(), self.safe_number_k(position.clone(), "a", &[]));
m.insert("unrealizedPnl".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("contracts".to_string(), self.parse_number(contractsAbs.clone(), &[]));
m.insert("contractSize".to_string(), Value::Null);
m.insert("markPrice".to_string(), Value::Null);
m.insert("side".to_string(), side.clone());
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("collateral".to_string(), Value::Null);
m.insert("initialMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("leverage".to_string(), Value::Null);
m.insert("marginRatio".to_string(), Value::Null);
m
}));
Value::Null
}
pub async fn fetch_my_trades_ws(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchMyTradesWs requires a symbol".to_string()))));
}
let mut market: Value = self.market(symbol.clone());
let mut type_var: Value = self.get_market_type(Value::Str("fetchMyTradesWs".to_string()), market.clone(), &[params.clone()]);
if !is_equal(&type_var, &Value::Str("spot".to_string())) && !is_equal(&type_var, &Value::Str("future".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&add(&add(&self.id, &Value::Str(" fetchMyTradesWs does not support ".to_string())), &type_var), &Value::Str(" markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &type_var);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchMyTradesWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.market_id(symbol.clone()));
m.insert("returnRateLimits".to_string(), returnRateLimits.clone());
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut payload, &Value::Str("startTime".to_string()), since.clone());
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut payload, &Value::Str("limit".to_string()), limit.clone());
}
let mut fromId: Value = self.safe_integer_k(params.clone(), "fromId", &[]);
if !is_equal(&fromId, &Value::Null) && !is_equal(&since, &Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchMyTradesWs does not support fetching by both fromId and since parameters at the same time".to_string()))));
}
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), Value::Str("myTrades".to_string()));
let __ws_arg_34 = self.extend(payload.clone(), &[params.clone()]);
m.insert("params".to_string(), self.sign_params(&[__ws_arg_34]));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_trades_ws".to_string()).clone());
m
});
let mut trades: Value = self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
return self.filter_by_symbol_since_limit(trades.clone(), &[symbol.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub async fn fetch_trades_ws(&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 type_var: Value = self.get_market_type(Value::Str("fetchTradesWs".to_string()), market.clone(), &[params.clone()]);
if !is_equal(&type_var, &Value::Str("spot".to_string())) && !is_equal(&type_var, &Value::Str("future".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&add(&add(&self.id, &Value::Str(" fetchTradesWs does not support ".to_string())), &type_var), &Value::Str(" markets".to_string()))));
}
let mut url: Value = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &type_var);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = to_string_val(&requestId);
let mut returnRateLimits: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchTradesWs".to_string()), Value::Str("returnRateLimits".to_string()), &[Value::Bool(false)]); returnRateLimits = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.market_id(symbol.clone()));
m.insert("returnRateLimits".to_string(), returnRateLimits.clone());
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut payload, &Value::Str("limit".to_string()), limit.clone());
}
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), messageHash.clone());
m.insert("method".to_string(), Value::Str("trades.historical".to_string()));
m.insert("params".to_string(), self.extend(payload.clone(), &[params.clone()]));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_trades_ws".to_string()).clone());
m
});
let mut trades: Value = self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;
return self.filter_by_since_limit(trades.clone(), &[since.clone(), limit.clone()]);
Value::Null
}
pub fn handle_trades_ws(&self, mut client: Value, mut message: Value) {
let mut messageHash: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut result: Value = self.safe_list_k(message.clone(), "result", &[Value::List(vec![])]);
let mut trades: Value = self.parse_trades(result.clone(), &[]);
client.resolve(&[trades.clone(), messageHash.clone()]);
}
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 type_var: Value = Value::Null;
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
let mut marketResolved: Value = self.market(symbol.clone());
market = marketResolved.clone();
symbol = get_value(&market, &Value::Str("symbol".to_string()));
}
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.resolve_auth_type(Value::Str("watchMyTrades".to_string()), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); subType = get_value(&__destr_tmp, &Value::Int(1)); params = get_value(&__destr_tmp, &Value::Int(2)); }
let mut messageHash: Value = Value::Str("myTrades".to_string());
if is_true(&(!is_equal(&symbol, &Value::Null))) && is_true(&(!is_equal(&market, &Value::Null))) {
symbol = self.symbol(symbol.clone());
messageHash = add(&messageHash, &add(&Value::Str(":".to_string()), &symbol));
params = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), get_value(&market, &Value::Str("type".to_string())));
m.insert("symbol".to_string(), symbol.clone());
m
})]);
}
let __ws_arg_35 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var.clone());
m.insert("subType".to_string(), subType.clone());
m
}), &[params.clone()]);
self.authenticate(&[__ws_arg_35]).await;
let mut urlType: Value = type_var.clone(); if is_equal(&type_var, &Value::Str("margin".to_string())) {
urlType = Value::Str("spot".to_string()); }
let mut isPortfolioMargin: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("watchMyTrades".to_string()), Value::Str("papi".to_string()), Value::Str("portfolioMargin".to_string()), &[Value::Bool(false)]); isPortfolioMargin = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut url: Value = Value::Str("".to_string());
if is_equal(&type_var, &Value::Str("spot".to_string())) || is_equal(&type_var, &Value::Str("margin".to_string())) {
url = get_value(&get_value(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("ws".to_string())), &Value::Str("ws-api".to_string())), &Value::Str("spot".to_string()));
} else {
if is_true(&isPortfolioMargin) {
urlType = Value::Str("papi".to_string());
} else if is_equal(&type_var, &Value::Str("option".to_string())) {
let mut demoMode: Value = self.safe_bool_k(self.options.clone(), "enableDemoTrading", &[Value::Bool(false)]);
if is_true(&(is_equal(&demoMode, &Value::Bool(true)))) || is_true(&self.isSandboxModeEnabled) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" watchMyTrades() does not support option markets in demo/testnet mode".to_string()))));
}
urlType = Value::Str("optionPrivate".to_string());
}
url = self.get_private_ws_url(urlType.clone(), get_value(&get_value(&self.options, &type_var), &Value::Str("listenKey".to_string())));
}
let mut client: Value = self.client(&[url.clone()]);
self.set_balance_cache(client.clone(), type_var.clone(), &[isPortfolioMargin.clone()]);
self.set_positions_cache(client.clone(), type_var.clone(), &[Value::Null, isPortfolioMargin.clone()]);
let mut message: Value = Value::Null;
let mut trades: Value = self.watch(url.clone(), messageHash.clone(), &[message.clone(), type_var.clone()]).await;
if is_true(&self.newUpdates) {
limit = trades.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_symbol_since_limit(trades.clone(), &[symbol.clone(), since.clone(), limit.clone(), Value::Bool(true)]);
Value::Null
}
pub fn handle_my_trade(&mut self, mut client: Value, mut message: Value) {
let mut messageHash: Value = Value::Str("myTrades".to_string());
let mut executionType: Value = self.safe_string_k(message.clone(), "x", &[]);
if is_equal(&executionType, &Value::Str("TRADE".to_string())) {
let mut trade: Value = self.parse_ws_trade(message.clone(), &[]);
let mut orderId: Value = self.safe_string_k(trade.clone(), "order", &[]);
let mut tradeFee: Value = self.safe_dict_k(trade.clone(), "fee", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
tradeFee = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), &[tradeFee.clone()]);
let mut symbol: Value = self.safe_string_k(trade.clone(), "symbol", &[]);
if !is_equal(&orderId, &Value::Null) && !is_equal(&tradeFee, &Value::Null) && !is_equal(&symbol, &Value::Null) {
let mut cachedOrders: Value = self.orders.clone();
if !is_equal(&cachedOrders, &Value::Null) {
let mut orders: Value = self.safe_value(cachedOrders.hashmap(), symbol.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut order: Value = self.safe_value(orders.clone(), orderId.clone(), &[]);
if !is_equal(&order, &Value::Null) {
let mut fees: Value = self.safe_value_k(order.clone(), "fees", &[]);
let mut fee: Value = self.safe_value_k(order.clone(), "fee", &[]);
if !is_true(&self.is_empty(fees.clone())) {
let mut insertNewFeeCurrency: bool = true;
{
let mut i: Value = Value::Int(0);
let mut __for_first_86: bool = true;
while { if !__for_first_86 { i = add(&i, &Value::Int(1)); } __for_first_86 = false; is_less_than(&i, &get_array_length(&fees)) } {
let mut orderFee: Value = get_value(&fees, &i);
let mut orderFee: Value = get_value(&fees, &i);
if is_equal(&get_value(&orderFee, &Value::Str("currency".to_string())), &get_value(&tradeFee, &Value::Str("currency".to_string()))) {
let mut feeCost: Value = self.sum(&[get_value(&tradeFee, &Value::Str("cost".to_string())), get_value(&orderFee, &Value::Str("cost".to_string()))]);
let mut feeCostString: Value = self.currency_to_precision(get_value(&tradeFee, &Value::Str("currency".to_string())), feeCost.clone(), &[]);
if is_equal(&feeCostString, &Value::Null) {
feeCostString = Value::Str("0".to_string());
}
add_element_to_object(get_value_mut(get_value_mut(&mut order, &Value::Str("fees".to_string())), &i), &Value::Str("cost".to_string()), crate::runtime::parse_float(&feeCostString));
insertNewFeeCurrency = false;
break;
}
}
}
if is_true(&insertNewFeeCurrency) {
crate::runtime::append_to_object_array(&mut order, &Value::Str("fees".to_string()), tradeFee.clone());
}
} else if !is_equal(&fee, &Value::Null) {
if is_equal(&get_value(&fee, &Value::Str("currency".to_string())), &get_value(&tradeFee, &Value::Str("currency".to_string()))) {
let mut feeCost: Value = self.sum(&[get_value(&fee, &Value::Str("cost".to_string())), get_value(&tradeFee, &Value::Str("cost".to_string()))]);
let mut feeCostString: Value = self.currency_to_precision(get_value(&tradeFee, &Value::Str("currency".to_string())), feeCost.clone(), &[]);
if is_equal(&feeCostString, &Value::Null) {
feeCostString = Value::Str("0".to_string());
}
add_element_to_object(get_value_mut(&mut order, &Value::Str("fee".to_string())), &Value::Str("cost".to_string()), crate::runtime::parse_float(&feeCostString));
} else if is_equal(&get_value(&fee, &Value::Str("currency".to_string())), &Value::Null) {
add_element_to_object(&mut order, &Value::Str("fee".to_string()), tradeFee.clone());
} else {
add_element_to_object(&mut order, &Value::Str("fees".to_string()), Value::List(vec![fee.clone(), tradeFee.clone()]));
add_element_to_object(&mut order, &Value::Str("fee".to_string()), Value::Null);
}
} else {
add_element_to_object(&mut order, &Value::Str("fee".to_string()), tradeFee.clone());
}
let mut orderTrades: Value = self.safe_list_k(order.clone(), "trades", &[Value::List(vec![])]);
append_to_array(&mut orderTrades, trade.clone());
add_element_to_object(&mut order, &Value::Str("trades".to_string()), orderTrades.clone());
add_element_to_object(&mut orders, &orderId, order.clone());
}
}
}
if is_equal(&self.myTrades, &Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCacheBySymbolById::new(limit.clone());
}
let mut myTrades: Value = self.myTrades.clone();
myTrades.append(trade.clone());
client.resolve(&[self.myTrades.clone(), messageHash.clone()]);
let mut messageHashSymbol: Value = add(&add(&messageHash, &Value::Str(":".to_string())), &symbol);
client.resolve(&[self.myTrades.clone(), messageHashSymbol.clone()]);
}
}
pub fn handle_order(&mut self, mut client: Value, mut message: Value) {
let mut parsed: Value = self.parse_ws_order(message.clone(), &[]);
let mut symbol: Value = self.safe_string_k(parsed.clone(), "symbol", &[]);
let mut orderId: Value = self.safe_string_k(parsed.clone(), "id", &[]);
if !is_equal(&symbol, &Value::Null) {
if is_equal(&self.orders, &Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCacheBySymbolById::new(limit.clone());
}
let mut cachedOrders: Value = self.orders.clone();
let mut orders: Value = self.safe_value(cachedOrders.hashmap(), symbol.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut order: Value = self.safe_value(orders.clone(), orderId.clone(), &[]);
if !is_equal(&order, &Value::Null) {
let mut fee: Value = self.safe_value_k(order.clone(), "fee", &[]);
if !is_equal(&fee, &Value::Null) {
add_element_to_object(&mut parsed, &Value::Str("fee".to_string()), fee.clone());
}
let mut fees: Value = self.safe_value_k(order.clone(), "fees", &[]);
if !is_equal(&fees, &Value::Null) {
add_element_to_object(&mut parsed, &Value::Str("fees".to_string()), fees.clone());
}
add_element_to_object(&mut parsed, &Value::Str("trades".to_string()), self.safe_value_k(order.clone(), "trades", &[]));
let mut timestamp: Value = self.safe_integer_k(parsed.clone(), "timestamp", &[]);
if is_equal(×tamp, &Value::Null) {
add_element_to_object(&mut parsed, &Value::Str("timestamp".to_string()), self.safe_integer_k(order.clone(), "timestamp", &[]));
add_element_to_object(&mut parsed, &Value::Str("datetime".to_string()), self.safe_string_k(order.clone(), "datetime", &[]));
}
}
cachedOrders.append(parsed.clone());
let mut messageHash: Value = Value::Str("orders".to_string());
let mut symbolSpecificMessageHash: Value = add(&Value::Str("orders:".to_string()), &symbol);
client.resolve(&[cachedOrders.clone(), messageHash.clone()]);
client.resolve(&[cachedOrders.clone(), symbolSpecificMessageHash.clone()]);
}
}
pub fn handle_acount_update(&mut self, mut client: Value, mut message: Value) {
self.handle_balance(client.clone(), message.clone());
self.handle_positions(client.clone(), message.clone());
}
pub fn handle_options_account_update(&mut self, mut client: Value, mut message: Value) {
let mut accountType: Value = Value::Str("option".to_string());
if is_equal(&get_value(&self.balance, &accountType), &Value::Null) {
add_element_to_object(&mut self.balance, &accountType, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
}
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.balance) }, &accountType), &Value::Str("info".to_string()), message.clone());
if is_equal(&accountType, &Value::Null) {
return;
}
let mut B: Value = self.safe_list_k(message.clone(), "B", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_87: bool = true;
while { if !__for_first_87 { i = add(&i, &Value::Int(1)); } __for_first_87 = false; is_less_than(&i, &get_array_length(&B)) } {
let mut entry: Value = get_value(&B, &i);
let mut entry: Value = get_value(&B, &i);
let mut currencyId: Value = self.safe_string_k(entry.clone(), "a", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
if !is_equal(&code, &Value::Null) {
let mut account: Value = self.account();
add_element_to_object(&mut account, &Value::Str("total".to_string()), self.safe_string_k(entry.clone(), "b", &[]));
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.balance) }, &accountType), &code, account.clone());
}
}
}
let mut timestamp: Value = self.safe_integer_k(message.clone(), "E", &[]);
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.balance) }, &accountType), &Value::Str("timestamp".to_string()), timestamp.clone());
{ let __be_tmp = self.iso8601(timestamp.clone()); add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.balance) }, &accountType), &Value::Str("datetime".to_string()), __be_tmp); };
{ let __be_tmp = self.safe_balance(get_value(&self.balance, &accountType)); add_element_to_object(&mut self.balance, &accountType, __be_tmp); };
client.resolve(&[get_value(&self.balance, &accountType), add(&accountType, &Value::Str(":balance".to_string()))]);
if is_equal(&self.positions, &Value::Null) {
self.positions = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
if !is_true(&(Value::Bool(in_op(&self.positions, &accountType)))) {
add_element_to_object(&mut self.positions, &accountType, ArrayCacheBySymbolBySide::new(Value::Null));
}
let mut cache: Value = get_value(&self.positions, &accountType);
let mut P: Value = self.safe_list_k(message.clone(), "P", &[Value::List(vec![])]);
let mut newPositions: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_88: bool = true;
while { if !__for_first_88 { i = add(&i, &Value::Int(1)); } __for_first_88 = false; is_less_than(&i, &get_array_length(&P)) } {
let mut rawPosition: Value = get_value(&P, &i);
let mut rawPosition: Value = get_value(&P, &i);
let mut position: Value = self.parse_ws_options_position(rawPosition.clone(), &[]);
add_element_to_object(&mut position, &Value::Str("timestamp".to_string()), timestamp.clone());
add_element_to_object(&mut position, &Value::Str("datetime".to_string()), self.iso8601(timestamp.clone()));
append_to_array(&mut newPositions, position.clone());
cache.append(position.clone());
}
}
let mut messageHashes: Value = self.find_message_hashes(client.clone(), add(&accountType, &Value::Str(":positions::".to_string())));
{
let mut i: Value = Value::Int(0);
let mut __for_first_89: bool = true;
while { if !__for_first_89 { i = add(&i, &Value::Int(1)); } __for_first_89 = 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(newPositions.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(&[newPositions.clone(), add(&accountType, &Value::Str(":positions".to_string()))]);
}
pub fn handle_ws_error(&self, mut client: Value, mut message: Value) {
let mut id: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut rejected: bool = false;
let mut error: Value = self.safe_dict_k(message.clone(), "error", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut code: Value = self.safe_integer_k(error.clone(), "code", &[]);
let mut msg: Value = self.safe_string_k(error.clone(), "msg", &[]);
let mut codeValue: Value = ternary(is_true(&(is_equal(&code, &Value::Null))), Value::Int(0), code.clone());
let _try_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let __ws_arg_36 = self.json(error.clone());
self.handle_errors(codeValue.clone(), msg.clone(), get_value(&client, &Value::Str("url".to_string())), Value::Str("".to_string()), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), __ws_arg_36, error.clone(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
#[allow(unreachable_code)] { Value::Null }}));
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
rejected = true;
client.reject(&[e.clone(), id.clone()]);
let mut subscriptionKeys: Value = object_keys(&get_value(&client, &Value::Str("subscriptions".to_string())));
{
let mut i: Value = Value::Int(0);
let mut __for_first_90: bool = true;
while { if !__for_first_90 { i = add(&i, &Value::Int(1)); } __for_first_90 = false; is_less_than(&i, &get_array_length(&subscriptionKeys)) } {
let mut subscriptionHash: Value = get_value(&subscriptionKeys, &i);
let mut subscriptionHash: Value = get_value(&subscriptionKeys, &i);
let mut subscriptionId: Value = self.safe_string(get_value(&get_value(&client, &Value::Str("subscriptions".to_string())), &subscriptionHash), Value::Str("id".to_string()), &[]);
let mut subscription: Value = self.safe_string(get_value(&get_value(&client, &Value::Str("subscriptions".to_string())), &subscriptionHash), Value::Str("subscription".to_string()), &[]);
if is_equal(&id, &subscriptionId) {
client.reject(&[e.clone(), subscriptionHash.clone()]);
if !is_equal(&subscription, &Value::Null) {
remove(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &subscription);
}
}
}
}
}
if !is_true(&rejected) {
client.reject(&[message.clone(), id.clone()]);
}
let mut codeString: Value = self.safe_string_k(error.clone(), "code", &[]);
if is_true(&(!is_equal(&codeString, &Value::Null))) && is_true(&(is_equal(&get_value(&codeString, &Value::Int(0)), &Value::Str("5".to_string())))) {
client.reset(message.clone());
}
}
pub fn handle_event_stream_terminated(&self, mut client: Value, mut message: Value) {
let mut event: Value = self.safe_string_k(message.clone(), "e", &[]);
let mut subscriptions: Value = get_value(&client, &Value::Str("subscriptions".to_string()));
let mut subscriptionsKeys: Value = object_keys(&subscriptions);
let mut accountType: Value = self.get_account_type_from_subscriptions(subscriptionsKeys.clone());
if is_equal(&event, &Value::Str("eventStreamTerminated".to_string())) {
remove(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &accountType);
client.reject(&[message.clone(), accountType.clone()]);
}
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
let mut streamWrapper: Value = self.safe_string_k(message.clone(), "stream", &[]);
if !is_equal(&streamWrapper, &Value::Null) {
message = self.safe_dict_k(message.clone(), "data", &[message.clone()]);
}
let mut eventMsg: Value = self.safe_dict_k(message.clone(), "event", &[]);
if !is_equal(&eventMsg, &Value::Null) {
message = eventMsg.clone();
}
let mut eventData: Value = self.safe_dict_k(message.clone(), "data", &[]);
if !is_equal(&eventData, &Value::Null) {
message = eventData.clone();
}
let mut status: Value = self.safe_string_k(message.clone(), "status", &[]);
let mut error: Value = self.safe_value_k(message.clone(), "error", &[]);
if is_true(&(!is_equal(&error, &Value::Null))) || is_true(&(!is_equal(&status, &Value::Null) && !is_equal(&status, &Value::Str("200".to_string())))) {
self.handle_ws_error(client.clone(), message.clone());
return;
}
let mut id: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut subscriptions: Value = self.safe_value(get_value(&client, &Value::Str("subscriptions".to_string())), id.clone(), &[]);
let mut method: Value = self.safe_value_k(subscriptions.clone(), "method", &[]);
if !is_equal(&method, &Value::Null) {
self.dispatch_ws_handler(&method, &[client.clone(), message.clone()]);
return;
}
let mut methods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("depthUpdate".to_string(), Value::Str("handle_order_book".to_string()).clone());
m.insert("trade".to_string(), Value::Str("handle_trade".to_string()).clone());
m.insert("aggTrade".to_string(), Value::Str("handle_trade".to_string()).clone());
m.insert("price".to_string(), Value::Str("handle_stock_price".to_string()).clone());
m.insert("quote".to_string(), Value::Str("handle_stock_quote".to_string()).clone());
m.insert("optionTrade".to_string(), Value::Str("handle_trade".to_string()).clone());
m.insert("markPrice".to_string(), Value::Str("handle_mark_prices".to_string()).clone());
m.insert("kline".to_string(), Value::Str("handle_ohlcv".to_string()).clone());
m.insert("markPrice_kline".to_string(), Value::Str("handle_ohlcv".to_string()).clone());
m.insert("indexPrice_kline".to_string(), Value::Str("handle_ohlcv".to_string()).clone());
m.insert("1hTicker@arr".to_string(), Value::Str("handle_tickers".to_string()).clone());
m.insert("4hTicker@arr".to_string(), Value::Str("handle_tickers".to_string()).clone());
m.insert("1dTicker@arr".to_string(), Value::Str("handle_tickers".to_string()).clone());
m.insert("24hrTicker@arr".to_string(), Value::Str("handle_tickers".to_string()).clone());
m.insert("24hrMiniTicker@arr".to_string(), Value::Str("handle_tickers".to_string()).clone());
m.insert("1hTicker".to_string(), Value::Str("handle_tickers".to_string()).clone());
m.insert("4hTicker".to_string(), Value::Str("handle_tickers".to_string()).clone());
m.insert("1dTicker".to_string(), Value::Str("handle_tickers".to_string()).clone());
m.insert("24hrTicker".to_string(), Value::Str("handle_tickers".to_string()).clone());
m.insert("24hrMiniTicker".to_string(), Value::Str("handle_tickers".to_string()).clone());
m.insert("markPriceUpdate".to_string(), Value::Str("handle_mark_prices".to_string()).clone());
m.insert("markPriceUpdate@arr".to_string(), Value::Str("handle_mark_prices".to_string()).clone());
m.insert("markPrice@arr".to_string(), Value::Str("handle_mark_prices".to_string()).clone());
m.insert("bookTicker".to_string(), Value::Str("handle_bids_asks".to_string()).clone());
m.insert("outboundAccountPosition".to_string(), Value::Str("handle_balance".to_string()).clone());
m.insert("balanceUpdate".to_string(), Value::Str("handle_balance".to_string()).clone());
m.insert("ACCOUNT_UPDATE".to_string(), Value::Str("handle_acount_update".to_string()).clone());
m.insert("BALANCE_POSITION_UPDATE".to_string(), Value::Str("handle_options_account_update".to_string()).clone());
m.insert("executionReport".to_string(), Value::Str("handle_order_update".to_string()).clone());
m.insert("orderReport".to_string(), Value::Str("handle_order_update".to_string()).clone());
m.insert("ORDER_TRADE_UPDATE".to_string(), Value::Str("handle_order_update".to_string()).clone());
m.insert("ALGO_UPDATE".to_string(), Value::Str("handle_order_update".to_string()).clone());
m.insert("forceOrder".to_string(), Value::Str("handle_liquidation".to_string()).clone());
m.insert("eventStreamTerminated".to_string(), Value::Str("handle_event_stream_terminated".to_string()).clone());
m.insert("externalLockUpdate".to_string(), Value::Str("handle_balance".to_string()).clone());
m
});
let mut event: Value = self.safe_string_k(message.clone(), "e", &[]);
if is_true(&Value::Bool(is_array(&message))) {
let mut arrayMessage: Value = get_value(&message, &Value::Int(0));
event = add(&self.safe_string_k(arrayMessage.clone(), "e", &[]), &Value::Str("@arr".to_string()));
}
method = self.safe_value(methods.clone(), event.clone(), &[]);
if is_equal(&method, &Value::Null) {
let mut requestId: Value = self.safe_string_k(message.clone(), "id", &[]);
if !is_equal(&requestId, &Value::Null) {
self.handle_subscription_status(client.clone(), message.clone());
return;
}
if is_equal(&event, &Value::Null) && is_true(&(Value::Bool(in_op(&message, &Value::Str("a".to_string()))))) && is_true(&(Value::Bool(in_op(&message, &Value::Str("b".to_string()))))) {
self.handle_bids_asks(client.clone(), message.clone());
}
} else {
self.dispatch_ws_handler(&method, &[client.clone(), message.clone()]);
}
}
}