// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
use crate::pro::*;
pub struct KucoinCore {
pub parent: crate::exchanges::kucoin::KucoinCore,
}
impl KucoinCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::kucoin::KucoinCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = KucoinCore::describe(self);
self.initialize_properties(described);
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for KucoinCore {
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 KucoinCore {
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_uta" => self.authenticate_uta().await,
"get_cache_index" => self.get_cache_index(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"get_current_position" => self.get_current_position(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_message_hash" => self.get_message_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"get_my_trades_message_hash_suffix" => self.get_my_trades_message_hash_suffix(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_uta_url" => self.get_uta_url().await,
"handle_error_message" => self.handle_error_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"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_system_status" => self.handle_system_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"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)).await,
"load_position_snapshot" => self.load_position_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,
"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)).await,
"negotiate" => self.negotiate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"negotiate_helper" => self.negotiate_helper(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"parse_ws_bid_ask" => self.parse_ws_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_funding_rate" => self.parse_ws_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_order" => self.parse_ws_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_trade" => self.parse_ws_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_uta_order" => self.parse_ws_uta_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_uta_position" => self.parse_ws_uta_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_uta_ticker" => self.parse_ws_uta_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_uta_trade" => self.parse_ws_uta_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"ping" => self.ping(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"request_id" => self.request_id(),
"subscribe" => self.subscribe(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"subscribe_multiple" => self.subscribe_multiple(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"subscribe_private_uta" => self.subscribe_private_uta(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"subscribe_public_multiple_uta" => self.subscribe_public_multiple_uta(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"subscribe_public_uta" => self.subscribe_public_uta(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"un_subscribe" => self.un_subscribe(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"un_subscribe_multiple" => self.un_subscribe_multiple(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"un_watch_funding_rate" => self.un_watch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_mark_price" => self.un_watch_mark_price(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_ohlcv" => self.un_watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_order_book" => self.un_watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_order_book_for_symbols" => self.un_watch_order_book_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_ticker" => self.un_watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_trades" => self.un_watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_trades_for_symbols" => self.un_watch_trades_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_balance" => self.watch_balance(&args[..]).await,
"watch_bids_asks" => self.watch_bids_asks(&args[..]).await,
"watch_funding_rate" => self.watch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_mark_price" => self.watch_mark_price(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_multi_helper" => self.watch_multi_helper(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"watch_my_trades" => self.watch_my_trades(&args[..]).await,
"watch_ohlcv" => self.watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book_for_symbols" => self.watch_order_book_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_position" => self.watch_position(&args[..]).await,
"watch_positions" => self.watch_positions(&args[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_tickers" => self.watch_tickers(&args[..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_trades_for_symbols" => self.watch_trades_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_uta_tickers" => self.watch_uta_tickers(&args[..]).await,
// Go-style inheritance: an un-overridden method dispatches to the parent core.
_ => crate::exchange_generated::ExchangeBase::call_dynamic(&mut self.parent, method, args).await,
}
})
}
}
impl KucoinCore {
/// Synchronous WS handler dispatch — routes a handler-name string (from the
/// venue's handle_message dispatch table) to the real handler method.
#[allow(dead_code, unreachable_patterns, clippy::all)]
pub fn dispatch_ws_handler(&mut self, __name: &crate::Value, args: &[crate::Value]) -> crate::Value {
let __n = match __name { crate::Value::Str(s) => s.as_ref(), _ => return crate::Value::Null };
match __n {
"authenticate_uta" => { crate::exchange_stubs::enqueue_spawn("authenticate_uta", args.to_vec()); crate::Value::Null },
"get_cache_index" => self.get_cache_index(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"get_current_position" => self.get_current_position(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_message_hash" => self.get_message_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"get_my_trades_message_hash_suffix" => self.get_my_trades_message_hash_suffix(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_uta_url" => { crate::exchange_stubs::enqueue_spawn("get_uta_url", args.to_vec()); crate::Value::Null },
"handle_balance" => { self.handle_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_bid_ask" => { self.handle_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_bid_asks" => { self.handle_bid_asks(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_contract_ticker" => { self.handle_contract_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_delta" => { self.handle_delta(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_error_message" => self.handle_error_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_my_trade" => { self.handle_my_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_ohlcv" => { self.handle_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order" => { self.handle_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book" => { self.handle_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book_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_pong" => { self.handle_pong(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_position" => { self.handle_position(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_subject" => { self.handle_subject(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_subscription_status" => { self.handle_subscription_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_system_status" => self.handle_system_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_ticker" => { self.handle_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); 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_uta_balance" => { self.handle_uta_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_uta_funding_rate" => { self.handle_uta_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_uta_my_trade" => { self.handle_uta_my_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_uta_ohlcv" => { self.handle_uta_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_uta_order" => { self.handle_uta_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_uta_order_book" => { self.handle_uta_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_uta_position" => { self.handle_uta_position(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_uta_ticker" => { self.handle_uta_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_uta_trade" => { self.handle_uta_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"load_balance_snapshot" => { crate::exchange_stubs::enqueue_spawn("load_balance_snapshot", args.to_vec()); crate::Value::Null },
"load_position_snapshot" => { crate::exchange_stubs::enqueue_spawn("load_position_snapshot", args.to_vec()); crate::Value::Null },
"load_positions_snapshot" => { crate::exchange_stubs::enqueue_spawn("load_positions_snapshot", args.to_vec()); crate::Value::Null },
"negotiate" => { crate::exchange_stubs::enqueue_spawn("negotiate", args.to_vec()); crate::Value::Null },
"negotiate_helper" => { crate::exchange_stubs::enqueue_spawn("negotiate_helper", args.to_vec()); crate::Value::Null },
"parse_ws_bid_ask" => self.parse_ws_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_funding_rate" => self.parse_ws_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_order" => self.parse_ws_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_trade" => self.parse_ws_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_uta_order" => self.parse_ws_uta_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_uta_position" => self.parse_ws_uta_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_uta_ticker" => self.parse_ws_uta_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_uta_trade" => self.parse_ws_uta_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"ping" => self.ping(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"request_id" => self.request_id(),
"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)); crate::Value::Null },
"set_position_cache" => { self.set_position_cache(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); 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)); crate::Value::Null },
"subscribe" => { crate::exchange_stubs::enqueue_spawn("subscribe", args.to_vec()); crate::Value::Null },
"subscribe_multiple" => { crate::exchange_stubs::enqueue_spawn("subscribe_multiple", args.to_vec()); crate::Value::Null },
"subscribe_private_uta" => { crate::exchange_stubs::enqueue_spawn("subscribe_private_uta", args.to_vec()); crate::Value::Null },
"subscribe_public_multiple_uta" => { crate::exchange_stubs::enqueue_spawn("subscribe_public_multiple_uta", args.to_vec()); crate::Value::Null },
"subscribe_public_uta" => { crate::exchange_stubs::enqueue_spawn("subscribe_public_uta", args.to_vec()); crate::Value::Null },
"un_subscribe" => { crate::exchange_stubs::enqueue_spawn("un_subscribe", args.to_vec()); crate::Value::Null },
"un_subscribe_multiple" => { crate::exchange_stubs::enqueue_spawn("un_subscribe_multiple", args.to_vec()); crate::Value::Null },
"un_watch_funding_rate" => { crate::exchange_stubs::enqueue_spawn("un_watch_funding_rate", args.to_vec()); crate::Value::Null },
"un_watch_mark_price" => { crate::exchange_stubs::enqueue_spawn("un_watch_mark_price", args.to_vec()); crate::Value::Null },
"un_watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("un_watch_ohlcv", args.to_vec()); crate::Value::Null },
"un_watch_order_book" => { crate::exchange_stubs::enqueue_spawn("un_watch_order_book", args.to_vec()); crate::Value::Null },
"un_watch_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_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_funding_rate" => { crate::exchange_stubs::enqueue_spawn("watch_funding_rate", args.to_vec()); crate::Value::Null },
"watch_mark_price" => { crate::exchange_stubs::enqueue_spawn("watch_mark_price", args.to_vec()); crate::Value::Null },
"watch_multi_helper" => { crate::exchange_stubs::enqueue_spawn("watch_multi_helper", args.to_vec()); crate::Value::Null },
"watch_my_trades" => { crate::exchange_stubs::enqueue_spawn("watch_my_trades", args.to_vec()); crate::Value::Null },
"watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("watch_ohlcv", args.to_vec()); crate::Value::Null },
"watch_order_book" => { crate::exchange_stubs::enqueue_spawn("watch_order_book", args.to_vec()); crate::Value::Null },
"watch_order_book_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_position" => { crate::exchange_stubs::enqueue_spawn("watch_position", args.to_vec()); crate::Value::Null },
"watch_positions" => { crate::exchange_stubs::enqueue_spawn("watch_positions", args.to_vec()); crate::Value::Null },
"watch_ticker" => { crate::exchange_stubs::enqueue_spawn("watch_ticker", args.to_vec()); crate::Value::Null },
"watch_tickers" => { crate::exchange_stubs::enqueue_spawn("watch_tickers", args.to_vec()); crate::Value::Null },
"watch_trades" => { crate::exchange_stubs::enqueue_spawn("watch_trades", args.to_vec()); crate::Value::Null },
"watch_trades_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_trades_for_symbols", args.to_vec()); crate::Value::Null },
"watch_uta_tickers" => { crate::exchange_stubs::enqueue_spawn("watch_uta_tickers", args.to_vec()); crate::Value::Null },
_ => crate::Value::Null,
}
}
}
impl std::ops::Deref for KucoinCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for KucoinCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl KucoinCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.parent.describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Bool(true));
m.insert("createOrderWs".to_string(), Value::Bool(false));
m.insert("editOrderWs".to_string(), Value::Bool(false));
m.insert("fetchOpenOrdersWs".to_string(), Value::Bool(false));
m.insert("fetchOrderWs".to_string(), Value::Bool(false));
m.insert("cancelOrderWs".to_string(), Value::Bool(false));
m.insert("cancelOrdersWs".to_string(), Value::Bool(false));
m.insert("cancelAllOrdersWs".to_string(), Value::Bool(false));
m.insert("watchBidsAsks".to_string(), Value::Bool(true));
m.insert("watchFundingRate".to_string(), Value::Bool(true));
m.insert("watchMarkPrice".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchPosition".to_string(), Value::Bool(true));
m.insert("watchPositions".to_string(), Value::Bool(true));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m.insert("watchTradesForSymbols".to_string(), Value::Bool(true));
m.insert("watchOrderBookForSymbols".to_string(), Value::Bool(true));
m.insert("watchBalance".to_string(), Value::Bool(true));
m.insert("watchOHLCV".to_string(), Value::Bool(true));
m.insert("unWatchFundingRate".to_string(), Value::Bool(true));
m.insert("unWatchMarkPrice".to_string(), Value::Bool(true));
m.insert("unWatchTicker".to_string(), Value::Bool(true));
m.insert("unWatchOHLCV".to_string(), Value::Bool(true));
m.insert("unWatchOrderBook".to_string(), Value::Bool(true));
m.insert("unWatchTrades".to_string(), Value::Bool(true));
m.insert("unWatchTradesForSymbols".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("wss://x-push-spot.kucoin.com".into()));
m.insert("futures".to_string(), Value::Str("wss://x-push-futures.kucoin.com".into()));
m.insert("private".to_string(), Value::Str("wss://wsapi-push.kucoin.com".into()));
m
}));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("utaToken".to_string(), Value::Null);
m.insert("utaTokenLastUpdate".to_string(), Value::Int(0));
m.insert("utaTokenRefreshInterval".to_string(), (match (&((match (&((match (&(Value::Int(1000)), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(24))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }));
m.insert("tradesLimit".to_string(), Value::Int(1000));
m.insert("watchTicker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spotMethod".to_string(), Value::Str("/market/snapshot".into()));
m
}));
m.insert("watchOrderBook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("snapshotDelay".to_string(), Value::Int(5));
m.insert("snapshotMaxRetries".to_string(), Value::Int(3));
m.insert("utaDepth".to_string(), Value::Str("increment".into()));
m.insert("spotMethod".to_string(), Value::Str("/market/level2".into()));
m.insert("contractMethod".to_string(), Value::Str("/contractMarket/level2".into()));
m
}));
m.insert("watchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spotMethod".to_string(), Value::Str("/spotMarket/tradeOrders".into()));
m
}));
m.insert("watchBalance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fetchBalanceSnapshot".to_string(), Value::Bool(true));
m.insert("awaitBalanceSnapshot".to_string(), Value::Bool(true));
m
}));
m.insert("watchPosition".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fetchPositionSnapshot".to_string(), Value::Bool(true));
m.insert("awaitPositionSnapshot".to_string(), Value::Bool(true));
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
}));
m.insert("streaming".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ping".to_string(), Value::Str("ping".into()).clone());
m
}));
m
})]);
Value::Null
}
pub async fn negotiate(&mut self, mut privateChannel: Value, optional_args: &[Value]) -> Value {
let mut isFuturesMethod = get_arg(optional_args, 0, Value::Bool(false));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut connectId: Value = (if (is_equal(&privateChannel, &Value::Bool(true))) { Value::Str("private".into()) } else { Value::Str("public".into()) });
if is_true(&isFuturesMethod) {
connectId = Value::Str(format!("{}{}", connectId, Value::Str("Futures".into())).into());
}
let mut urls: Value = self.safe_dict_k(self.options.clone(), "urls", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut future: Value = self.safe_value(urls.clone(), connectId.clone(), &[]);
if (future != Value::Null) {
return future;
}
// we store an awaitable to the url
// so that multiple calls don't asynchronously
// fetch different urls and overwrite each other
if let Value::Dict(__d) = &mut urls { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&connectId), self.call_dynamic("negotiate_helper", vec![privateChannel, connectId.clone(), params]).await); }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("urls".into(), urls.clone()); }
future = urls.as_map().and_then(|__m| connectId.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
return future;
Value::Null
}
pub async fn negotiate_helper(&mut self, mut privateChannel: Value, mut connectId: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = Value::Null;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
if (connectId.as_str() == Some("private")) {
response = self.parent.private_post_bullet_private(&[params.clone()]).await;
} else if (connectId.as_str() == Some("public")) {
response = self.parent.public_post_bullet_public(&[params.clone()]).await;
} else if (connectId.as_str() == Some("privateFutures")) {
response = self.parent.futures_private_post_bullet_private(&[params.clone()]).await;
} else {
response = self.parent.futures_public_post_bullet_public(&[params]).await;
}
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut instanceServers: Value = self.safe_list_k(data.clone(), "instanceServers", &[Value::from(vec![])]);
let mut firstInstanceServer: Value = self.safe_dict(instanceServers, Value::Int(0), &[]);
let mut pingInterval: Value = self.safe_integer_k(firstInstanceServer.clone(), "pingInterval", &[]);
let mut endpoint: Value = self.safe_string_k(firstInstanceServer, "endpoint", &[]);
let mut token: Value = self.safe_string_k(data, "token", &[]);
let mut result: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", endpoint, Value::Str("?".into())).into()), self.urlencode(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("token".to_string(), token);
m.insert("privateChannel".to_string(), privateChannel);
m.insert("connectId".to_string(), connectId.clone());
m
}), &[])).into());
let mut client: Value = self.client(&[result.clone()]);
crate::set_value(&mut client, &Value::Str("keepAlive".into()), pingInterval);
return result;
#[allow(unreachable_code)] { Value::Null }})).await;
match _try_result { Ok(__try_ok) => { if !matches!(__try_ok, Value::Null) { return __try_ok; } return Value::Null; } Err(_try_err) => { let e: Value = panic_to_value(_try_err);
let mut future: Value = self.safe_value(self.options.as_map().and_then(|__m| __m.get("urls")).cloned().unwrap_or(Value::Null), connectId.clone(), &[]);
future.reject(&[e]);
remove(&mut crate::value::get_value_k(&self.options, "urls"), &connectId);
} }
return Value::Null;
Value::Null
}
pub fn request_id(&mut self) -> Value {
self.lock_id(&[]);
let mut requestId: Value = self.sum(&[self.safe_integer_k(self.options.clone(), "requestId", &[Value::Int(0)]), Value::Int(1)]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("requestId".into(), requestId.clone()); }
self.unlock_id(&[]);
return requestId;
Value::Null
}
pub async fn subscribe(&mut self, mut url: Value, mut messageHash: Value, mut subscriptionHash: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut subscription = get_arg(optional_args, 1, Value::Null);
let mut requestId: Value = to_string_val(&self.request_id());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("type".to_string(), Value::Str("subscribe".into()));
m.insert("topic".to_string(), subscriptionHash.clone());
m.insert("response".to_string(), Value::Bool(true));
m
});
let mut message: Value = self.extend(request, &[params]);
let mut client: Value = self.client(&[url.clone()]);
if !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &subscriptionHash)) {
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &requestId, subscriptionHash.clone());
}
return self.watch(url, messageHash, &[message, subscriptionHash, subscription]).await;
Value::Null
}
pub async fn subscribe_public_uta(&mut self, mut messageHash: Value, mut channel: Value, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut subscription = get_arg(optional_args, 1, Value::Null);
let mut requestId: Value = to_string_val(&self.request_id());
let mut market: Value = self.market(symbol);
let mut urlType: Value = (if (market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { Value::Str("futures".into()) } else { Value::Str("spot".into()) });
let mut tradeType: Value = to_upper(&urlType);
let mut action: Value = Value::Str("subscribe".into());
if (subscription != Value::Null) {
let mut unsubscribe: Value = self.safe_bool_k(subscription.clone(), "unsubscribe", &[Value::Bool(false)]);
action = (if (unsubscribe.as_bool() == Some(true)) { Value::Str("unsubscribe".into()) } else { action.clone() });
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("action".to_string(), action);
m.insert("channel".to_string(), channel);
m.insert("tradeType".to_string(), tradeType);
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut message: Value = self.extend(request, &[params]);
let mut url: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), urlType, &[]);
let mut client: Value = self.client(&[url.clone()]);
if !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash)) {
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &requestId, messageHash.clone());
}
return self.watch(url, messageHash.clone(), &[message, messageHash.clone(), subscription]).await;
Value::Null
}
pub async fn subscribe_private_uta(&mut self, mut messageHashes: Value, mut subscribeHash: Value, mut channel: 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
}));
let mut subscription = get_arg(optional_args, 2, Value::Null);
self.check_required_credentials(&[]);
let mut requestId: Value = to_string_val(&self.request_id());
let mut action: Value = Value::Str("subscribe".into());
if (subscription != Value::Null) {
let mut unsubscribe: Value = self.safe_bool_k(subscription.clone(), "unsubscribe", &[Value::Bool(false)]);
action = (if (unsubscribe.as_bool() == Some(true)) { Value::Str("unsubscribe".into()) } else { action.clone() });
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("action".to_string(), action);
m.insert("channel".to_string(), channel);
m
});
if (symbol != Value::Null) {
let mut market: Value = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let mut message: Value = self.extend(request, &[params]);
let mut url: Value = self.get_uta_url().await;
let mut client: Value = self.client(&[url.clone()]);
if !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &subscribeHash)) {
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &requestId, subscribeHash.clone());
}
return self.watch_multiple(url, messageHashes, &[message, Value::from(vec![subscribeHash]), subscription]).await;
Value::Null
}
pub async fn get_uta_url(&mut self) -> Value {
let mut utaToken: Value = self.authenticate_uta().await;
return Value::Str(format!("{}{}", add(&crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "private"), &Value::Str("?token=".into())), utaToken).into());
Value::Null
}
pub async fn authenticate_uta(&mut self) -> Value {
self.check_required_credentials(&[]);
let mut utaToken: Option<String> = self.safe_string_k(self.options.clone(), "utaToken", &[]).as_str().map(str::to_owned);
let mut lastUpdate: Value = self.safe_integer_k(self.options.clone(), "utaTokenLastUpdate", &[Value::Int(0)]);
let mut refreshInterval: Value = (match (&((match (&((match (&(Value::Int(1000)), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(24))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }); // 24 hours
refreshInterval = self.safe_integer_k(self.options.clone(), "utaTokenRefreshInterval", &[refreshInterval.clone()]);
let mut now: Value = self.milliseconds();
let mut expired: bool = ((match (&(now), &(lastUpdate)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })).as_f64().unwrap_or(f64::NAN) >= refreshInterval.as_f64().unwrap_or(f64::NAN);
let mut messageHash: Value = Value::Str("utaToken".into());
let mut url: Value = crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "private");
let mut client: Value = self.client(&[url]);
if (utaToken.is_none()) || expired {
if (in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
// wait the existing future if it's already being fetched by another call
crate::exchange_stubs::ws_await_flight(&client.future(&[messageHash.clone()])).await;
} else {
// fetch new token and store the future to the .futures to prevent concurrent fetches
client.future(&[messageHash.clone()]);
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut response: Value = self.parent.private_post_bullet_private(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("version".to_string(), Value::Str("v2".into()));
m
})]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut utaTokenString: Value = self.safe_string_k(data, "token", &[]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("utaTokenLastUpdate".into(), now); }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("utaToken".into(), utaTokenString.clone()); }
client.resolve(&[utaTokenString, messageHash.clone()]);
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("utaToken".into(), Value::Null); }
client.reject(&[e, messageHash]);
}
}
}
return self.safe_string_k(self.options.clone(), "utaToken", &[]);
Value::Null
}
pub async fn un_subscribe(&mut self, mut url: Value, mut messageHash: Value, mut topic: Value, mut subscriptionHash: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut subscription = get_arg(optional_args, 1, Value::Null);
return self.un_subscribe_multiple(url, Value::from(vec![messageHash]), topic, Value::from(vec![subscriptionHash]), &[params, subscription]).await;
Value::Null
}
pub async fn subscribe_multiple(&mut self, mut url: Value, mut messageHashes: Value, mut topic: Value, mut subscriptionHashes: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut subscription = get_arg(optional_args, 1, Value::Null);
let mut requestId: Value = to_string_val(&self.request_id());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("type".to_string(), Value::Str("subscribe".into()));
m.insert("topic".to_string(), topic);
m.insert("response".to_string(), Value::Bool(true));
m
});
let mut message: Value = self.extend(request, &[params]);
let mut client: Value = self.client(&[url.clone()]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_436: bool = true;
while { if !__for_first_436 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_436 = false; i.as_f64().unwrap_or(f64::NAN) < ((subscriptionHashes.len() as i64) as f64) } {
let mut subscriptionHash: Value = subscriptionHashes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &subscriptionHash)) {
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &requestId, subscriptionHash.clone());
}
}
}
return self.watch_multiple(url, messageHashes, &[message, subscriptionHashes, subscription]).await;
Value::Null
}
pub async fn un_subscribe_multiple(&mut self, mut url: Value, mut messageHashes: Value, mut topic: Value, mut subscriptionHashes: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut subscription = get_arg(optional_args, 1, Value::Null);
let mut requestId: Value = to_string_val(&self.request_id());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("type".to_string(), Value::Str("unsubscribe".into()));
m.insert("topic".to_string(), topic);
m.insert("response".to_string(), Value::Bool(true));
m
});
let mut message: Value = self.extend(request, &[params]);
if (subscription != Value::Null) {
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&requestId), requestId.clone()); }
}
let mut client: Value = self.client(&[url.clone()]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_437: bool = true;
while { if !__for_first_437 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_437 = false; i.as_f64().unwrap_or(f64::NAN) < ((subscriptionHashes.len() as i64) as f64) } {
let mut subscriptionHash: Value = subscriptionHashes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &subscriptionHash)) {
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &requestId, subscriptionHash.clone());
}
}
}
return self.watch_multiple(url, messageHashes, &[message, subscriptionHashes, subscription]).await;
Value::Null
}
/*
* @method
* @name kucoin#watchTicker
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://www.kucoin.com/docs-new/3470063w0
* @see https://www.kucoin.com/docs-new/3470081w0
* @see https://www.kucoin.com/docs-new/3470222w0
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.uta] set to true for the unified trading account (uta), default is false
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbol).into());
let mut uta: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchTicker".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&uta) {
messageHash = Value::Str(format!("{}{}", Value::Str("uta:".into()), messageHash).into());
let mut channel: Value = Value::Str("ticker".into());
return self.subscribe_public_uta(messageHash.clone(), channel, symbol, &[params.clone()]).await;
}
let mut isFuturesMethod: Value = market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null);
let mut url: Value = self.negotiate(Value::Bool(false), &[isFuturesMethod.clone()]).await;
let mut method: Value = Value::Str("/market/snapshot".into());
if (isFuturesMethod.as_bool() == Some(true)) {
method = Value::Str("/contractMarket/ticker".into());
} else {
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchTicker".into()), Value::Str("spotMethod".into()), &[method.clone()]); method = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
}
let mut topic: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", method, Value::Str(":".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
return self.subscribe(url, messageHash, topic, &[params]).await;
Value::Null
}
/*
* @method
* @name kucoin#unWatchTicker
* @description unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://www.kucoin.com/docs-new/3470063w0
* @see https://www.kucoin.com/docs-new/3470081w0
* @see https://www.kucoin.com/docs-new/3470222w0
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.uta] set to true for the unified trading account (uta), default is false
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn un_watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut isFuturesMethod: Value = market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null);
let mut uta: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("unWatchTicker".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbols".to_string(), Value::from(vec![symbol.clone()]));
m.insert("topic".to_string(), Value::Str("ticker".into()));
m.insert("unsubscribe".to_string(), Value::Bool(true));
m
});
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbol).into());
if is_true(&uta) {
subMessageHash = Value::Str(format!("{}{}", Value::Str("uta:".into()), subMessageHash).into());
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("subMessageHashes".into(), Value::from(vec![subMessageHash.clone()])); }
let mut utaMessageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("messageHashes".into(), Value::from(vec![utaMessageHash.clone()])); }
return self.subscribe_public_uta(utaMessageHash, Value::Str("ticker".into()), symbol, &[params.clone(), subscription.clone()]).await;
} else {
let mut url: Value = self.negotiate(Value::Bool(false), &[isFuturesMethod.clone()]).await;
let mut method: Value = Value::Str("/market/snapshot".into());
if (isFuturesMethod.as_bool() == Some(true)) {
method = Value::Str("/contractMarket/ticker".into());
} else {
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchTicker".into()), Value::Str("spotMethod".into()), &[method.clone()]); method = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
}
let mut topic: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", method, Value::Str(":".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
// we have to add the topic to the messageHashes and subMessageHashes
// because handleSubscriptionStatus needs them to remove the subscription from the client
// without them subscription would never be removed and re-subscribe would fail because of duplicate subscriptionHash
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("messageHashes".into(), Value::from(vec![messageHash.clone(), topic.clone()])); }
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("subMessageHashes".into(), Value::from(vec![subMessageHash.clone(), topic.clone()])); }
return self.un_subscribe(url, messageHash, topic, subMessageHash, &[params, subscription]).await;
}
Value::Null
}
/*
* @method
* @name kucoin#watchTickers
* @see https://www.kucoin.com/docs-new/3470063w0
* @see https://www.kucoin.com/docs-new/3470064w0
* @see https://www.kucoin.com/docs-new/3470081w0
* @see https://www.kucoin.com/docs-new/3470222w0
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
* @param {string[]} symbols unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.method] *spot markets only* either '/market/snapshot' or '/market/ticker' default is '/market/ticker'
* @param {boolean} [params.uta] set to true for the unified trading account (uta), default is false
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(true), Value::Bool(true)]);
let mut firstMarket: Value = self.get_market_from_symbols(&[symbols.clone()]);
let mut marketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchTickers".into()), &[firstMarket, params.clone()]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut uta: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchTickers".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut isFuturesMethod: Value = Value::Bool((marketType.as_str() != Some("spot")) && (marketType.as_str() != Some("margin")));
if (matches!(&isFuturesMethod, Value::Bool(true)) || is_true(&uta)) && (symbols == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" watchTickers() requires a list of symbols for ".into())).into()), marketType).into()), Value::Str(" markets and unified trading account (uta)".into()))));
}
let mut messageHash: Value = Value::Str("tickers".into());
let mut method: Value = Value::Str("/market/ticker".into());
if matches!(&isFuturesMethod, Value::Bool(true)) {
method = Value::Str("/contractMarket/ticker".into());
} else {
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("watchTickers".into()), Value::Str("method".into()), Value::Str("spotMethod".into()), &[method.clone()]); method = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
}
let mut messageHashes: Value = Value::from(vec![]);
let mut topics: Value = Value::from(vec![]);
if (symbols != Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_438: bool = true;
while { if !__for_first_438 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_438 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
append_to_array(&mut messageHashes, Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbol).into()));
let mut market: Value = self.market(symbol);
append_to_array(&mut topics, Value::Str(format!("{}{}", Value::Str(format!("{}{}", method, Value::Str(":".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
}
}
}
let mut url: Value = self.negotiate(Value::Bool(false), &[isFuturesMethod]).await;
let mut tickers: Value = Value::Null;
if (symbols == Value::Null) {
let mut allTopic: Value = Value::Str(format!("{}{}", method, Value::Str(":all".into())).into());
tickers = self.subscribe(url.clone(), messageHash, allTopic, &[params.clone()]).await;
if is_true(&self.newUpdates) {
return tickers;
}
} else {
let mut marketIds: Value = self.market_ids(&[symbols.clone()]);
let mut symbolsTopic: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", method, Value::Str(":".into())).into()), join(&marketIds, &Value::Str(",".into()))).into());
tickers = self.subscribe_multiple(url, messageHashes, symbolsTopic, topics, &[params]).await;
if is_true(&self.newUpdates) {
let mut newDict: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut newDict, &tickers.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), tickers.clone());
return newDict;
}
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".into()), &[symbols]);
Value::Null
}
pub async fn subscribe_public_multiple_uta(&mut self, mut messageHashes: Value, mut channel: Value, mut symbols: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut subscription = get_arg(optional_args, 1, Value::Null);
let mut requestId: Value = to_string_val(&self.request_id());
let mut market: Value = self.get_market_from_symbols(&[symbols.clone()]);
let mut isContract: bool = is_equal(&market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null), &Value::Bool(true));
let mut urlType: Value = (if isContract { Value::Str("futures".into()) } else { Value::Str("spot".into()) });
let mut tradeType: Value = to_upper(&urlType);
let mut action: Value = Value::Str("subscribe".into());
if (subscription != Value::Null) {
let mut unsubscribe: Value = self.safe_bool_k(subscription.clone(), "unsubscribe", &[Value::Bool(false)]);
action = (if (unsubscribe.as_bool() == Some(true)) { Value::Str("unsubscribe".into()) } else { action.clone() });
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("action".to_string(), action);
m.insert("channel".to_string(), channel.clone());
m.insert("tradeType".to_string(), tradeType);
m.insert("symbols".to_string(), self.market_ids(&[symbols.clone()]));
m
});
let mut message: Value = self.extend(request, &[params]);
let mut url: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), urlType, &[]);
let mut client: Value = self.client(&[url.clone()]);
let mut messageHashWithSymbols: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", channel, Value::Str(":".into())).into()), join(&symbols, &Value::Str(",".into()))).into());
if !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHashWithSymbols)) {
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &requestId, messageHashWithSymbols.clone());
}
return self.watch_multiple(url, messageHashes.clone(), &[message, messageHashes.clone(), subscription]).await;
Value::Null
}
pub async fn watch_uta_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(true)]);
let mut messageHash: Value = Value::Str("uta:ticker".into());
let mut messageHashes: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_439: bool = true;
while { if !__for_first_439 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_439 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = self.safe_string(symbols.clone(), i.clone(), &[]);
let mut market: Value = self.market(symbol);
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str(":".into())).into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into());
append_to_array(&mut messageHashes, subMessageHash);
}
}
let mut tickers: Value = self.subscribe_public_multiple_uta(messageHashes, Value::Str("ticker".into()), symbols.clone(), &[params]).await;
if is_true(&self.newUpdates) {
return tickers;
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".into()), &[symbols]);
Value::Null
}
pub fn handle_ticker(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// market/snapshot
//
// updates come in every 2 sec unless there
// were no changes since the previous update
//
// {
// "data": {
// "sequence": "1545896669291",
// "data": {
// "trading": true,
// "symbol": "KCS-BTC",
// "buy": 0.00011,
// "sell": 0.00012,
// "sort": 100,
// "volValue": 3.13851792584, // total
// "baseCurrency": "KCS",
// "market": "BTC",
// "quoteCurrency": "BTC",
// "symbolCode": "KCS-BTC",
// "datetime": 1548388122031,
// "high": 0.00013,
// "vol": 27514.34842,
// "low": 0.0001,
// "changePrice": -1.0e-5,
// "changeRate": -0.0769,
// "lastTradedPrice": 0.00012,
// "board": 0,
// "mark": 0
// }
// },
// "subject": "trade.snapshot",
// "topic": "/market/snapshot:KCS-BTC",
// "type": "message"
// }
//
// market/ticker
//
// {
// "type": "message",
// "topic": "/market/ticker:BTC-USDT",
// "subject": "trade.ticker",
// "data": {
// "bestAsk": "62163",
// "bestAskSize": "0.99011388",
// "bestBid": "62162.9",
// "bestBidSize": "0.04794181",
// "price": "62162.9",
// "sequence": "1621383371852",
// "size": "0.00832274",
// "time": 1634641987564
// }
// }
//
// futures
// {
// "subject": "ticker",
// "topic": "/contractMarket/ticker:XBTUSDM",
// "data": {
// "symbol": "XBTUSDM", //Market of the symbol
// "sequence": 45, //Sequence number which is used to judge the continuity of the pushed messages
// "side": "sell", //Transaction side of the last traded taker order
// "price": "3600.0", //Filled price
// "size": 16, //Filled quantity
// "tradeId": "5c9dcf4170744d6f5a3d32fb", //Order ID
// "bestBidSize": 795, //Best bid size
// "bestBidPrice": "3200.0", //Best bid
// "bestAskPrice": "3600.0", //Best ask size
// "bestAskSize": 284, //Best ask
// "ts": 1553846081210004941 //Filled time - nanosecond
// }
// }
//
let mut topic: Value = (match __pro_message.get("topic").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if Value::Int(topic.as_str().and_then(|__s| __s.find("contractMarket")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) < ((0i64) as f64) {
let mut market: Value = Value::Null;
if (topic != Value::Null) {
let mut parts: Value = split(&topic, &Value::Str(":".into()));
let mut first: Value = self.safe_string(parts, Value::Int(1), &[]);
let mut marketId: Value = Value::Null;
if (first.as_str() == Some("all")) {
marketId = (match __pro_message.get("subject").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
} else {
marketId = first;
}
market = self.safe_market(&[marketId, market.clone(), Value::Str("-".into())]);
}
let mut data: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut rawTicker: Value = self.safe_dict_k(data.clone(), "data", &[data.clone()]);
let mut ticker: Value = self.parent.parse_spot_or_uta_ticker(rawTicker, &[market]);
let mut symbol: Value = ticker.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut self.tickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker.clone()); }
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbol).into());
client.resolve(&[ticker.clone(), messageHash]);
// watchTickers
let mut allTickers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if let Value::Dict(__d) = &mut allTickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker); }
client.resolve(&[allTickers, Value::Str("tickers".into())]);
} else {
self.handle_contract_ticker(client, message);
}
}
pub fn handle_contract_ticker(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// ticker (v1)
//
// {
// "subject": "ticker",
// "topic": "/contractMarket/ticker:XBTUSDM",
// "data": {
// "symbol": "XBTUSDM", //Market of the symbol
// "sequence": 45, //Sequence number which is used to judge the continuity of the pushed messages
// "side": "sell", //Transaction side of the last traded taker order
// "price": "3600.0", //Filled price
// "size": 16, //Filled quantity
// "tradeId": "5c9dcf4170744d6f5a3d32fb", //Order ID
// "bestBidSize": 795, //Best bid size
// "bestBidPrice": "3200.0", //Best bid
// "bestAskPrice": "3600.0", //Best ask size
// "bestAskSize": 284, //Best ask
// "ts": 1553846081210004941 //Filled time - nanosecond
// }
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "symbol", &[]);
let mut market: Value = self.safe_market(&[marketId, Value::Null, Value::Str("-".into())]);
let mut ticker: Value = self.parse_ticker(data, &[market.clone()]);
add_element_to_object(&mut self.tickers, &market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), ticker.clone());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker:".into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into());
client.resolve(&[ticker, messageHash]);
}
pub fn handle_uta_ticker(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// watchTicker
// {
// "T": "ticker.SPOT",
// "P": "1774100940787520626",
// "d": {
// "A": "0.5972689",
// "B": "23.3114947",
// "E": 20310552932,
// "M": "1774100940780000000",
// "S": "SELL",
// "a": "2155.55",
// "b": "2155.54",
// "l": "2155.54",
// "q": "0.0001529",
// "s": "ETH-USDT"
// }
// }
//
// watchMarkPrice
// {
// "T": "mark-price",
// "P": "1782834987171570181",
// "d": {
// "s": "ETHUSDTM",
// "mp": "1569.15",
// "ip": "1569.87",
// "oi": "50541824",
// "ts": 1782834987000
// }
// }
//
let mut data: Value = (match message.get("d") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut ticker: Value = self.parse_ws_uta_ticker(data, &[market.clone()]);
add_element_to_object(&mut self.tickers, &market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), ticker.clone());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("uta:ticker:".into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into());
client.resolve(&[ticker, messageHash]);
}
pub fn parse_ws_uta_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut symbol: Value = self.safe_string_k(market.clone(), "symbol", &[]);
market = self.safe_market(&[symbol.clone(), market.clone()]);
let mut timestamp: Value = self.safe_integer_k(ticker.clone(), "ts", &[]);
if (timestamp == Value::Null) {
timestamp = self.safe_integer_product_k(ticker.clone(), "M", Value::Float(0.000001), &[]);
}
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), self.safe_string_k(ticker.clone(), "a", &[]));
m.insert("bidVolume".to_string(), self.safe_string_k(ticker.clone(), "A", &[]));
m.insert("ask".to_string(), self.safe_string_k(ticker.clone(), "b", &[]));
m.insert("askVolume".to_string(), self.safe_string_k(ticker.clone(), "B", &[]));
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), Value::Null);
m.insert("last".to_string(), self.safe_string_k(ticker.clone(), "l", &[]));
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("markPrice".to_string(), self.safe_string_k(ticker.clone(), "mp", &[]));
m.insert("indexPrice".to_string(), self.safe_string_k(ticker.clone(), "ip", &[]));
m.insert("info".to_string(), ticker);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name kucoin#watchBidsAsks
* @see https://www.kucoin.com/docs-new/3470067w0
* @see https://www.kucoin.com/docs-new/3470080w0
* @description watches best bid & ask for symbols
* @param {string[]} symbols unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(true), Value::Bool(false)]);
let mut firstMarket: Value = self.get_market_from_symbols(&[symbols.clone()]);
let mut isFuturesMethod: Value = Value::Bool(is_equal(&firstMarket.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null), &Value::Bool(true)));
let mut channelName: Value = Value::Str("/spotMarket/level1:".into());
if matches!(&isFuturesMethod, Value::Bool(true)) {
channelName = Value::Str("/contractMarket/tickerV2:".into());
}
let mut ticker: Value = self.watch_multi_helper(Value::Str("watchBidsAsks".into()), channelName, isFuturesMethod, &[symbols.clone(), params]).await;
if is_true(&self.newUpdates) {
let mut tickers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut tickers, &crate::value::get_value_k(&ticker, "symbol"), ticker.clone());
return tickers;
}
return self.filter_by_array(self.bidsasks.clone(), Value::Str("symbol".into()), &[symbols]);
Value::Null
}
pub async fn watch_multi_helper(&mut self, mut methodName: Value, mut channelName: Value, mut isFuturesChannel: 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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(true), Value::Bool(false)]);
let mut length: f64 = ((symbols.len() as i64) as f64);
if length > ((100i64) as f64) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), methodName).into()), Value::Str("() accepts a maximum of 100 symbols".into()))));
}
let mut messageHashes: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_440: bool = true;
while { if !__for_first_440 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_440 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol);
append_to_array(&mut messageHashes, Value::Str(format!("{}{}", Value::Str("bidask@".into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into()));
}
}
let mut url: Value = self.negotiate(Value::Bool(false), &[isFuturesChannel]).await;
let mut marketIds: Value = self.market_ids(&[symbols]);
let mut joined: Value = join(&marketIds, &Value::Str(",".into()));
let mut requestId: Value = to_string_val(&self.request_id());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId);
m.insert("type".to_string(), Value::Str("subscribe".into()));
m.insert("topic".to_string(), Value::Str(format!("{}{}", channelName, joined).into()));
m.insert("response".to_string(), Value::Bool(true));
m
});
let mut message: Value = self.extend(request, &[params]);
return self.watch_multiple(url, messageHashes.clone(), &[message, messageHashes.clone()]).await;
Value::Null
}
pub fn handle_bid_ask(&mut self, mut client: Value, mut message: Value) {
//
// arrives one symbol dict
//
// {
// topic: '/spotMarket/level1:ETH-USDT',
// type: 'message',
// data: {
// asks: [ '3347.42', '2.0778387' ],
// bids: [ '3347.41', '6.0411697' ],
// timestamp: 1712231142085
// },
// subject: 'level1'
// }
//
// futures
// {
// "subject": "tickerV2",
// "topic": "/contractMarket/tickerV2:XBTUSDM",
// "data": {
// "symbol": "XBTUSDM", //Market of the symbol
// "bestBidSize": 795, // Best bid size
// "bestBidPrice": 3200.0, // Best bid
// "bestAskPrice": 3600.0, // Best ask
// "bestAskSize": 284, // Best ask size
// "ts": 1553846081210004941 // Filled time - nanosecond
// }
// }
//
let mut parsedTicker: Value = self.parse_ws_bid_ask(message, &[]);
let mut symbol: Value = parsedTicker.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut self.bidsasks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), parsedTicker.clone()); }
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("bidask@".into()), symbol).into());
client.resolve(&[parsedTicker, messageHash]);
}
pub fn parse_ws_bid_ask(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut topic: Value = self.safe_string_k(ticker.clone(), "topic", &[]);
if Value::Int(topic.as_str().and_then(|__s| __s.find("contractMarket")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) < ((0i64) as f64) {
let mut parts: Value = split(&topic, &Value::Str(":".into()));
let mut marketId: Value = parts.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut symbol: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut data: Value = self.safe_dict_k(ticker.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ask: Value = self.safe_list_k(data.clone(), "asks", &[Value::from(vec![])]);
let mut bid: Value = self.safe_list_k(data.clone(), "bids", &[Value::from(vec![])]);
let mut timestamp: Value = self.safe_integer_k(data.clone(), "timestamp", &[]);
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("ask".to_string(), self.safe_number(ask.clone(), Value::Int(0), &[]));
m.insert("askVolume".to_string(), self.safe_number(ask, Value::Int(1), &[]));
m.insert("bid".to_string(), self.safe_number(bid.clone(), Value::Int(0), &[]));
m.insert("bidVolume".to_string(), self.safe_number(bid, Value::Int(1), &[]));
m.insert("info".to_string(), ticker.clone());
m
}), &[market.clone()]);
} else {
// futures
let mut data: Value = self.safe_dict_k(ticker.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketId: Value = self.safe_string_k(data.clone(), "symbol", &[]);
market = self.safe_market(&[marketId, market.clone()]);
let mut symbol: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut timestamp: Value = self.safe_integer_product_k(data.clone(), "ts", Value::Float(0.000001), &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("ask".to_string(), self.safe_number_k(data.clone(), "bestAskPrice", &[]));
m.insert("askVolume".to_string(), self.safe_number_k(data.clone(), "bestAskSize", &[]));
m.insert("bid".to_string(), self.safe_number_k(data.clone(), "bestBidPrice", &[]));
m.insert("bidVolume".to_string(), self.safe_number_k(data, "bestBidSize", &[]));
m.insert("info".to_string(), ticker);
m
}), &[market]);
}
Value::Null
}
/*
* @method
* @name kucoin#watchOHLCV
* @description watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://www.kucoin.com/docs-new/3470071w0
* @see https://www.kucoin.com/docs-new/3470086w0
* @see https://www.kucoin.com/docs-new/3470223w0
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.uta] set to true for the unified trading account (uta), default is false
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn watch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut period: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("candles:".into()), symbol).into()), Value::Str(":".into())).into()), timeframe).into());
let mut uta: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOHLCV".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut ohlcv: Value = Value::Null;
if is_true(&uta) {
let mut channel: Value = Value::Str("kline".into());
messageHash = Value::Str(format!("{}{}", Value::Str("uta:".into()), messageHash).into());
let mut extendedParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("interval".to_string(), period.clone());
m
});
params = self.extend(extendedParams.clone(), &[params.clone()]);
let __ws_arg_0 = self.extend(extendedParams, &[params.clone()]);
ohlcv = self.subscribe_public_uta(messageHash.clone(), channel, symbol.clone(), &[__ws_arg_0]).await;
} else {
let mut isFuturesMethod: Value = market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null);
let mut url: Value = self.negotiate(Value::Bool(false), &[isFuturesMethod.clone()]).await;
let mut channelName: Value = Value::Str("/market/candles:".into());
if (isFuturesMethod.as_bool() == Some(true)) {
channelName = Value::Str("/contractMarket/limitCandle:".into());
}
let mut topic: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", channelName, market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str("_".into())).into()), period).into());
ohlcv = self.subscribe(url, messageHash, topic, &[params]).await;
}
if is_true(&self.newUpdates) {
limit = ohlcv.get_limit(symbol, limit.clone());
}
return self.filter_by_since_limit(ohlcv, &[since, limit, Value::Int(0), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name kucoin#unWatchOHLCV
* @description unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://www.kucoin.com/docs-new/3470071w0
* @see https://www.kucoin.com/docs-new/3470086w0
* @see https://www.kucoin.com/docs-new/3470223w0
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.uta] set to true for the unified trading account (uta), default is false
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn un_watch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut uta: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("unWatchOHLCV".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut period: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
let mut symbolAndTimeframe: Value = Value::from(vec![symbol.clone(), timeframe.clone()]);
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbols".to_string(), Value::from(vec![symbol.clone()]));
m.insert("symbolsAndTimeframes".to_string(), Value::from(vec![symbolAndTimeframe]));
m.insert("topic".to_string(), Value::Str("ohlcv".into()));
m.insert("unsubscribe".to_string(), Value::Bool(true));
m
});
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("candles:".into()), symbol).into()), Value::Str(":".into())).into()), timeframe).into());
if is_true(&uta) {
subMessageHash = Value::Str(format!("{}{}", Value::Str("uta:".into()), subMessageHash).into());
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("subMessageHashes".into(), Value::from(vec![subMessageHash.clone()])); }
let mut utaMessageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("messageHashes".into(), Value::from(vec![utaMessageHash.clone()])); }
let mut extendedParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("interval".to_string(), period.clone());
m
});
let __ws_arg_1 = self.extend(extendedParams, &[params.clone()]);
return self.subscribe_public_uta(utaMessageHash, Value::Str("kline".into()), symbol, &[__ws_arg_1, subscription.clone()]).await;
} else {
let mut isFuturesMethod: Value = market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null);
let mut url: Value = self.negotiate(Value::Bool(false), &[isFuturesMethod.clone()]).await;
let mut channelName: Value = Value::Str("/market/candles:".into());
if (isFuturesMethod.as_bool() == Some(true)) {
channelName = Value::Str("/contractMarket/limitCandle:".into());
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let mut topic: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", channelName, market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str("_".into())).into()), period).into());
// we have to add the topic to the messageHashes and subMessageHashes
// because handleSubscriptionStatus needs them to remove the subscription from the client
// without them subscription would never be removed and re-subscribe would fail because of duplicate subscriptionHash
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("messageHashes".into(), Value::from(vec![messageHash.clone(), topic.clone()])); }
if let Value::Dict(__d) = &mut subscription { std::sync::Arc::make_mut(__d).insert("subMessageHashes".into(), Value::from(vec![subMessageHash, topic.clone()])); }
return self.un_subscribe(url, messageHash.clone(), topic, messageHash.clone(), &[params, subscription]).await;
}
Value::Null
}
pub fn handle_ohlcv(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "data": {
// "symbol": "BTC-USDT",
// "candles": [
// "1624881240",
// "34138.8",
// "34121.6",
// "34138.8",
// "34097.9",
// "3.06097133",
// "104430.955068564"
// ],
// "time": 1624881284466023700
// },
// "subject": "trade.candles.update",
// "topic": "/market/candles:BTC-USDT_1min",
// "type": "message"
// }
//
// futures
// {
// "topic":"/contractMarket/limitCandle:LTCUSDTM_1min",
// "type":"message",
// "data":{
// "symbol":"LTCUSDTM",
// "candles":[
// "1715470980",
// "81.38",
// "81.38",
// "81.38",
// "81.38",
// "61.0", - Note value 5 is incorrect and will be fixed in subsequent versions of kucoin
// "61"
// ],
// "time":1715470994801
// },
// "subject":"candle.stick"
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "symbol", &[]);
let mut candles: Value = self.safe_list_k(data, "candles", &[Value::from(vec![])]);
let mut topic: Value = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut parts: Value = split(&topic, &Value::Str("_".into()));
let mut interval: Value = self.safe_string(parts, Value::Int(1), &[]);
// use a reverse lookup in a static map instead
let mut timeframe: Value = self.find_timeframe(interval, &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("candles:".into()), symbol).into()), Value::Str(":".into())).into()), timeframe).into());
{ let __be_tmp = self.safe_dict(self.ohlcvs.clone(), symbol.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); if let Value::Dict(__d) = &mut self.ohlcvs { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
let mut stored: Value = self.safe_value(get_value(&self.ohlcvs, &symbol), timeframe.clone(), &[]);
if (stored == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "OHLCVLimit", &[Value::Int(1000)]);
stored = ArrayCacheByTimestamp::new(limit);
add_element_to_object(get_value_mut(&mut self.ohlcvs, &symbol), &timeframe, stored.clone());
}
let mut isContractMarket: bool = Value::Int(topic.as_str().and_then(|__s| __s.find("contractMarket")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64);
let mut baseVolumeIndex: Value = (if isContractMarket { Value::Int(6) } else { Value::Int(5) }); // Note value 5 is incorrect and will be fixed in subsequent versions of kucoin
let mut parsed: Value = Value::from(vec![self.safe_timestamp(candles.clone(), Value::Int(0), &[]), self.safe_number(candles.clone(), Value::Int(1), &[]), self.safe_number(candles.clone(), Value::Int(3), &[]), self.safe_number(candles.clone(), Value::Int(4), &[]), self.safe_number(candles.clone(), Value::Int(2), &[]), self.safe_number(candles, baseVolumeIndex, &[])]);
stored.append(parsed);
client.resolve(&[stored, messageHash]);
}
pub fn handle_uta_ohlcv(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "T": "kline.SPOT",
// "P": "1774621652314890314",
// "d": {
// "a": "195333.419819132",
// "s": "ETH-USDT",
// "C": 1774621680,
// "c": "1973.4",
// "S": false,
// "v": "98.941095",
// "h": "1974.97",
// "i": "1min",
// "l": "1973.4",
// "O": 1774621620,
// "o": "1974.34"
// }
// }
//
let mut data: Value = (match message.get("d") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut interval: Value = self.safe_string_k(data.clone(), "i", &[]);
let mut timeframe: Value = self.find_timeframe(interval, &[]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("uta:candles:".into()), symbol).into()), Value::Str(":".into())).into()), timeframe).into());
{ let __be_tmp = self.safe_dict(self.ohlcvs.clone(), symbol.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); if let Value::Dict(__d) = &mut self.ohlcvs { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
let mut stored: Value = self.safe_value(get_value(&self.ohlcvs, &symbol), timeframe.clone(), &[]);
if (stored == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "OHLCVLimit", &[Value::Int(1000)]);
stored = ArrayCacheByTimestamp::new(limit);
add_element_to_object(get_value_mut(&mut self.ohlcvs, &symbol), &timeframe, stored.clone());
}
let mut parsed: Value = Value::from(vec![self.safe_integer_product_k(data.clone(), "O", Value::Int(1000), &[]), self.safe_number_k(data.clone(), "o", &[]), self.safe_number_k(data.clone(), "h", &[]), self.safe_number_k(data.clone(), "l", &[]), self.safe_number_k(data.clone(), "c", &[]), self.safe_number_k(data, "v", &[])]);
stored.append(parsed);
client.resolve(&[stored, messageHash]);
}
/*
* @method
* @name kucoin#watchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://www.kucoin.com/docs-new/3470072w0
* @see https://www.kucoin.com/docs-new/3470084w0
* @see https://www.kucoin.com/docs-new/3470224w0
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.uta] set to true for the unified trading account (uta), default is false
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut uta: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchTrades".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&uta) {
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("uta:trades:".into()), symbol).into());
let mut channel: Value = Value::Str("trade".into());
let mut trades: Value = self.subscribe_public_uta(messageHash, channel, symbol.clone(), &[params.clone()]).await;
if is_true(&self.newUpdates) {
let mut first: Value = self.safe_dict(trades.clone(), Value::Int(0), &[]);
let mut tradeSymbol: Value = self.safe_string_k(first, "symbol", &[]);
limit = trades.get_limit(tradeSymbol, limit.clone());
}
return self.filter_by_since_limit(trades, &[since.clone(), limit.clone(), Value::Str("timestamp".into()), Value::Bool(true)]);
}
return self.watch_trades_for_symbols(Value::from(vec![symbol]), &[since, limit, params]).await;
Value::Null
}
/*
* @method
* @name kucoin#watchTradesForSymbols
* @description get the list of most recent trades for a particular symbol
* @see https://www.kucoin.com/docs-new/3470072w0
* @see https://www.kucoin.com/docs-new/3470084w0
* @param {string[]} symbols
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_trades_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
}));
let mut symbolsLength: f64 = ((symbols.len() as i64) as f64);
if (symbolsLength == 0.0) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchTradesForSymbols() requires a non-empty array of symbols".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(true)]);
let mut firstMarket: Value = self.get_market_from_symbols(&[symbols.clone()]);
let mut isFuturesMethod: Value = Value::Bool(is_equal(&firstMarket.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null), &Value::Bool(true)));
let mut marketIds: Value = self.market_ids(&[symbols.clone()]);
let mut url: Value = self.negotiate(Value::Bool(false), &[isFuturesMethod.clone()]).await;
let mut messageHashes: Value = Value::from(vec![]);
let mut subscriptionHashes: Value = Value::from(vec![]);
let mut channelName: Value = Value::Str("/market/match:".into());
if matches!(&isFuturesMethod, Value::Bool(true)) {
channelName = Value::Str("/contractMarket/execution:".into());
}
let mut topic: Value = Value::Str(format!("{}{}", channelName, join(&marketIds, &Value::Str(",".into()))).into());
{
let mut i: Value = Value::Int(0);
let mut __for_first_441: bool = true;
while { if !__for_first_441 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_441 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
append_to_array(&mut messageHashes, Value::Str(format!("{}{}", Value::Str("trades:".into()), symbol).into()));
let mut marketId: Value = marketIds.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
append_to_array(&mut subscriptionHashes, Value::Str(format!("{}{}", channelName, marketId).into()));
}
}
let mut trades: Value = self.subscribe_multiple(url, messageHashes, topic, subscriptionHashes, &[params]).await;
if is_true(&self.newUpdates) {
let mut first: Value = self.safe_dict(trades.clone(), Value::Int(0), &[]);
let mut tradeSymbol: Value = self.safe_string_k(first, "symbol", &[]);
limit = trades.get_limit(tradeSymbol, limit.clone());
}
return self.filter_by_since_limit(trades, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name kucoin#unWatchTradesForSymbols
* @description unWatches trades stream
* @see https://www.kucoin.com/docs-new/3470072w0
* @see https://www.kucoin.com/docs-new/3470084w0
* @param {string} symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn 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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(true)]);
let mut marketIds: Value = self.market_ids(&[symbols.clone()]);
let mut firstMarket: Value = self.get_market_from_symbols(&[symbols.clone()]);
let mut isFuturesMethod: Value = Value::Bool(is_equal(&firstMarket.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null), &Value::Bool(true)));
let mut url: Value = self.negotiate(Value::Bool(false), &[isFuturesMethod.clone()]).await;
let mut messageHashes: Value = Value::from(vec![]);
let mut subscriptionHashes: Value = Value::from(vec![]);
let mut channelName: Value = Value::Str("/market/match:".into());
if matches!(&isFuturesMethod, Value::Bool(true)) {
channelName = Value::Str("/contractMarket/execution:".into());
}
let mut topic: Value = Value::Str(format!("{}{}", channelName, join(&marketIds, &Value::Str(",".into()))).into());
{
let mut i: Value = Value::Int(0);
let mut __for_first_442: bool = true;
while { if !__for_first_442 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_442 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
append_to_array(&mut messageHashes, Value::Str(format!("{}{}", Value::Str("unsubscribe:trades:".into()), symbol).into()));
append_to_array(&mut subscriptionHashes, Value::Str(format!("{}{}", Value::Str("trades:".into()), symbol).into()));
}
}
// we have to add the topic to the messageHashes and subMessageHashes
// because handleSubscriptionStatus needs them to remove the subscription from the client
// without them subscription would never be removed and re-subscribe would fail because of duplicate subscriptionHash
append_to_array(&mut messageHashes, topic.clone());
append_to_array(&mut subscriptionHashes, topic.clone());
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("messageHashes".to_string(), messageHashes.clone());
m.insert("subMessageHashes".to_string(), subscriptionHashes);
m.insert("topic".to_string(), Value::Str("trades".into()));
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("symbols".to_string(), symbols);
m
});
return self.un_subscribe_multiple(url, messageHashes.clone(), topic, messageHashes.clone(), &[params, subscription]).await;
Value::Null
}
/*
* @method
* @name kucoin#unWatchTrades
* @description unWatches trades stream
* @see https://www.kucoin.com/docs-new/3470072w0
* @see https://www.kucoin.com/docs-new/3470084w0
* @see https://www.kucoin.com/docs-new/3470224w0
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.uta] set to true for the unified trading account (uta), default is false
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn un_watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut uta: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchTrades".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&uta) {
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str("uta:trades:".into()), symbol).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let mut channel: Value = Value::Str("trade".into());
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("messageHashes".to_string(), Value::from(vec![messageHash.clone()]));
m.insert("subMessageHashes".to_string(), Value::from(vec![subMessageHash]));
m.insert("topic".to_string(), Value::Str("trades".into()));
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("symbols".to_string(), Value::from(vec![symbol.clone()]));
m
});
return self.subscribe_public_uta(messageHash, channel, symbol.clone(), &[params.clone(), subscription]).await;
}
return self.un_watch_trades_for_symbols(Value::from(vec![symbol]), &[params]).await;
Value::Null
}
pub fn handle_trade(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "data": {
// "sequence": "1568787654360",
// "symbol": "BTC-USDT",
// "side": "buy",
// "size": "0.00536577",
// "price": "9345",
// "takerOrderId": "5e356c4a9f1a790008f8d921",
// "time": "1580559434436443257",
// "type": "match",
// "makerOrderId": "5e356bffedf0010008fa5d7f",
// "tradeId": "5e356c4aeefabd62c62a1ece"
// },
// "subject": "trade.l3match",
// "topic": "/market/match:BTC-USDT",
// "type": "message"
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "symbol", &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut trade: Value = self.parse_trade(data, &[market]);
let mut symbol: Value = trade.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("trades:".into()), symbol).into());
if !(in_op(&self.trades, &symbol)) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
let mut stored = ArrayCache::new(limit);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), stored); }
}
let mut cache: Value = get_value(&self.trades, &symbol);
cache.append(trade);
client.resolve(&[cache, messageHash]);
}
pub fn handle_uta_trade(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "T": "trade.SPOT",
// "P": "1774618231151398133",
// "d": {
// "E": "20745928670070784",
// "M": "1774618231141000000",
// "S": "buy",
// "p": "1995.49",
// "q": "0.3142324",
// "s": "ETH-USDT",
// "ti": "20745928670070784"
// }
// }
//
let mut data: Value = (match message.get("d") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "symbol", &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut trade: Value = self.parse_ws_uta_trade(data, &[market]);
let mut symbol: Value = trade.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("uta:trades:".into()), symbol).into());
if !(in_op(&self.trades, &symbol)) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
let mut stored = ArrayCache::new(limit);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), stored); }
}
let mut cache: Value = get_value(&self.trades, &symbol);
cache.append(trade);
client.resolve(&[cache, messageHash]);
}
pub fn parse_ws_uta_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
// trades
// {
// "E": "20745928670070784",
// "M": "1774618231141000000",
// "S": "buy",
// "p": "1995.49",
// "q": "0.3142324",
// "s": "ETH-USDT",
// "ti": "20745928670070784"
// }
//
// myTrades
// {
// "E": "1774977429843000000",
// "S": "SELL",
// "p": "0.09211",
// "q": "10",
// "s": "DOGE-USDT",
// "lR": "TAKER",
// "oT": "MARKET",
// "oi": "428507829452754944",
// "ti": 20801647764195330
// }
//
let mut marketId: Value = self.safe_string_k(trade.clone(), "s", &[]);
market = self.safe_market(&[marketId, market.clone()]);
let mut timestamp: Value = self.safe_integer_product2(trade.clone(), Value::Str("M".into()), Value::Str("E".into()), Value::Float(0.000001), &[]);
let mut fee: Value = Value::Null;
let mut feeCost: Value = self.safe_string_k(trade.clone(), "f", &[]);
if (feeCost != Value::Null) {
let mut feeCurrencyId: Value = self.safe_string_k(trade.clone(), "fC", &[]);
let mut feeCurrencyCode: Value = self.safe_currency_code(feeCurrencyId, &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost);
m.insert("currency".to_string(), feeCurrencyCode);
m
});
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "ti", &[]));
m.insert("order".to_string(), self.safe_string_k(trade.clone(), "oi", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), self.safe_string_lower_k(trade.clone(), "oT", &[]));
m.insert("side".to_string(), self.safe_string_lower_k(trade.clone(), "S", &[]));
m.insert("takerOrMaker".to_string(), self.safe_string_lower_k(trade.clone(), "lR", &[]));
m.insert("price".to_string(), self.safe_string_k(trade.clone(), "p", &[]));
m.insert("amount".to_string(), self.safe_string_k(trade, "q", &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name kucoin#watchOrderBook
* @see https://www.kucoin.com/docs-new/3470069w0 // spot level 5
* @see https://www.kucoin.com/docs-new/3470070w0 // spot level 50
* @see https://www.kucoin.com/docs-new/3470068w0 // spot incremental
* @see https://www.kucoin.com/docs-new/3470083w0 // futures level 5
* @see https://www.kucoin.com/docs-new/3470097w0 // futures level 50
* @see https://www.kucoin.com/docs-new/3470082w0 // futures incremental
* @see https://www.kucoin.com/docs-new/3470221w0 // uta
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.uta] set to true for the unified trading account (uta), default is false
* @param {string} [params.method] either '/market/level2' or '/spotMarket/level2Depth5' or '/spotMarket/level2Depth50' default is '/market/level2'
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
//
// https://docs.kucoin.com/#level-2-market-data
// cache the ws level2 stream, fetch the REST snapshot, then replay only the cached deltas whose
// sequence follows the snapshot; price 0 → skip (bump sequence), size 0 → remove the price level
//
let mut uta: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrderBook".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&uta) {
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut depth: Value = Value::Str("increment".into()); // '1', '5', '50' or 'increment'
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrderBook".into()), Value::Str("utaDepth".into()), &[depth.clone()]); depth = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("uta:orderbook:".into()), symbol).into()), Value::Str(":depth:".into())).into()), depth).into());
let mut channel: Value = Value::Str("obu".into());
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (depth.as_str() == Some("increment")) {
subscription = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_order_book_subscription".into()).clone());
m.insert("symbols".to_string(), Value::from(vec![symbol.clone()]));
m.insert("limit".to_string(), limit.clone());
m
});
}
params = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("depth".to_string(), depth);
m
})]);
let mut orderbook: Value = self.subscribe_public_uta(messageHash, channel, symbol.clone(), &[params.clone(), subscription]).await;
return orderbook.limit();
}
return self.watch_order_book_for_symbols(Value::from(vec![symbol]), &[limit, params]).await;
Value::Null
}
/*
* @method
* @name kucoin#unWatchOrderBook
* @see https://www.kucoin.com/docs-new/3470069w0 // spot level 5
* @see https://www.kucoin.com/docs-new/3470070w0 // spot level 50
* @see https://www.kucoin.com/docs-new/3470068w0 // spot incremental
* @see https://www.kucoin.com/docs-new/3470083w0 // futures level 5
* @see https://www.kucoin.com/docs-new/3470097w0 // futures level 50
* @see https://www.kucoin.com/docs-new/3470082w0 // futures incremental
* @see https://www.kucoin.com/docs-new/3470221w0 // uta
* @description unWatches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.uta] set to true for the unified trading account (uta), default is false
* @param {string} [params.method] either '/market/level2' or '/spotMarket/level2Depth5' or '/spotMarket/level2Depth50' default is '/market/level2'
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn un_watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut uta: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("unWatchOrderBook".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&uta) {
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut depth: Value = Value::Str("increment".into()); // '1', '5', '50' or 'increment'
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrderBook".into()), Value::Str("utaDepth".into()), &[depth.clone()]); depth = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
params = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("depth".to_string(), depth.clone());
m
})]);
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("uta:orderbook:".into()), symbol).into()), Value::Str(":depth:".into())).into()), depth).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let mut channel: Value = Value::Str("obu".into());
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("messageHashes".to_string(), Value::from(vec![messageHash.clone()]));
m.insert("subMessageHashes".to_string(), Value::from(vec![subMessageHash]));
m.insert("topic".to_string(), Value::Str("orderbook".into()));
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("symbols".to_string(), Value::from(vec![symbol.clone()]));
m
});
return self.subscribe_public_uta(messageHash, channel, symbol.clone(), &[params.clone(), subscription]).await;
}
return self.un_watch_order_book_for_symbols(Value::from(vec![symbol]), &[params]).await;
Value::Null
}
/*
* @method
* @name kucoin#watchOrderBookForSymbols
* @see https://www.kucoin.com/docs-new/3470069w0 // spot level 5
* @see https://www.kucoin.com/docs-new/3470070w0 // spot level 50
* @see https://www.kucoin.com/docs-new/3470068w0 // spot incremental
* @see https://www.kucoin.com/docs-new/3470083w0 // futures level 5
* @see https://www.kucoin.com/docs-new/3470097w0 // futures level 50
* @see https://www.kucoin.com/docs-new/3470082w0 // futures incremental
* @see https://www.kucoin.com/docs-new/3470221w0 // uta
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @param {string[]} symbols unified array of symbols
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn watch_order_book_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
}));
let mut symbolsLength: f64 = ((symbols.len() as i64) as f64);
if (symbolsLength == 0.0) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchOrderBookForSymbols() requires a non-empty array of symbols".into()))));
}
if (limit != Value::Null) {
if (limit.as_f64() != Some(20.0)) && (limit.as_f64() != Some(100.0)) && (limit.as_f64() != Some(50.0)) && (limit.as_f64() != Some(5.0)) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" watchOrderBook 'limit' argument must be undefined, 5, 20, 50 or 100".into()))));
}
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut marketIds: Value = self.market_ids(&[symbols.clone()]);
let mut firstMarket: Value = self.get_market_from_symbols(&[symbols.clone()]);
let mut isFuturesMethod: Value = Value::Bool(is_equal(&firstMarket.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null), &Value::Bool(true)));
let mut url: Value = self.negotiate(Value::Bool(false), &[isFuturesMethod.clone()]).await;
let mut method: Value = (if matches!(&isFuturesMethod, Value::Bool(true)) { Value::Str("/contractMarket/level2".into()) } else { Value::Str("/market/level2".into()) });
let mut optionName: Value = (if matches!(&isFuturesMethod, Value::Bool(true)) { Value::Str("contractMethod".into()) } else { Value::Str("spotMethod".into()) });
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("watchOrderBook".into()), optionName, Value::Str("method".into()), &[method.clone()]); method = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if Value::Int(method.as_str().and_then(|__s| __s.find("Depth")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) < ((0i64) as f64) {
if (limit.as_f64() == Some(5.0)) || (limit.as_f64() == Some(50.0)) {
if !(matches!(&isFuturesMethod, Value::Bool(true))) {
method = Value::Str("/spotMarket/level2".into());
}
method = Value::Str(format!("{}{}", method, Value::Str(format!("{}{}", Value::Str("Depth".into()), to_string_val(&limit)).into())).into());
}
}
let mut topic: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", method, Value::Str(":".into())).into()), join(&marketIds, &Value::Str(",".into()))).into());
let mut messageHashes: Value = Value::from(vec![]);
let mut subscriptionHashes: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_443: bool = true;
while { if !__for_first_443 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_443 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
append_to_array(&mut messageHashes, Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbol).into()));
let mut marketId: Value = marketIds.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
append_to_array(&mut subscriptionHashes, Value::Str(format!("{}{}", Value::Str(format!("{}{}", method, Value::Str(":".into())).into()), marketId).into()));
}
}
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (method.as_str() == Some("/market/level2")) || (method.as_str() == Some("/contractMarket/level2")) {
subscription = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("handle_order_book_subscription".into()).clone());
m.insert("symbols".to_string(), symbols);
m.insert("limit".to_string(), limit.clone());
m
});
}
let mut orderbook: Value = self.subscribe_multiple(url, messageHashes, topic, subscriptionHashes, &[params, subscription]).await;
return orderbook.limit();
Value::Null
}
/*
* @method
* @name kucoin#unWatchOrderBookForSymbols
* @see https://www.kucoin.com/docs-new/3470069w0 // spot level 5
* @see https://www.kucoin.com/docs-new/3470070w0 // spot level 50
* @see https://www.kucoin.com/docs-new/3470068w0 // spot incremental
* @see https://www.kucoin.com/docs-new/3470083w0 // futures level 5
* @see https://www.kucoin.com/docs-new/3470097w0 // futures level 50
* @see https://www.kucoin.com/docs-new/3470082w0 // futures incremental
* @description unWatches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @param {string[]} symbols unified array of symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.method] either '/market/level2' or '/spotMarket/level2Depth5' or '/spotMarket/level2Depth50' or '/contractMarket/level2' or '/contractMarket/level2Depth5' or '/contractMarket/level2Depth50' default is '/market/level2' for spot and '/contractMarket/level2' for futures
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
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
}));
let mut limit: Value = self.safe_integer_k(params.clone(), "limit", &[]);
params = self.omit(params.clone(), Value::Str("limit".into()), &[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(true)]);
let mut marketIds: Value = self.market_ids(&[symbols.clone()]);
let mut firstMarket: Value = self.get_market_from_symbols(&[symbols.clone()]);
let mut isFuturesMethod: Value = Value::Bool(is_equal(&firstMarket.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null), &Value::Bool(true)));
let mut url: Value = self.negotiate(Value::Bool(false), &[isFuturesMethod.clone()]).await;
let mut method: Value = (if matches!(&isFuturesMethod, Value::Bool(true)) { Value::Str("/contractMarket/level2".into()) } else { Value::Str("/market/level2".into()) });
let mut optionName: Value = (if matches!(&isFuturesMethod, Value::Bool(true)) { Value::Str("contractMethod".into()) } else { Value::Str("spotMethod".into()) });
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("watchOrderBook".into()), optionName, Value::Str("method".into()), &[method.clone()]); method = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if Value::Int(method.as_str().and_then(|__s| __s.find("Depth")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) < ((0i64) as f64) {
if (limit.as_f64() == Some(5.0)) || (limit.as_f64() == Some(50.0)) {
if !(matches!(&isFuturesMethod, Value::Bool(true))) {
method = Value::Str("/spotMarket/level2".into());
}
method = Value::Str(format!("{}{}", method, Value::Str(format!("{}{}", Value::Str("Depth".into()), to_string_val(&limit)).into())).into());
}
}
let mut topic: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", method, Value::Str(":".into())).into()), join(&marketIds, &Value::Str(",".into()))).into());
let mut messageHashes: Value = Value::from(vec![]);
let mut subscriptionHashes: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_444: bool = true;
while { if !__for_first_444 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_444 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
append_to_array(&mut messageHashes, Value::Str(format!("{}{}", Value::Str("unsubscribe:orderbook:".into()), symbol).into()));
append_to_array(&mut subscriptionHashes, Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbol).into()));
}
}
// we have to add the topic to the messageHashes and subMessageHashes
// because handleSubscriptionStatus needs them to remove the subscription from the client
// without them subscription would never be removed and re-subscribe would fail because of duplicate subscriptionHash
append_to_array(&mut messageHashes, topic.clone());
append_to_array(&mut subscriptionHashes, topic.clone());
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("messageHashes".to_string(), messageHashes.clone());
m.insert("symbols".to_string(), symbols);
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("topic".to_string(), Value::Str("orderbook".into()));
m.insert("subMessageHashes".to_string(), subscriptionHashes);
m
});
return self.un_subscribe_multiple(url, messageHashes.clone(), topic, messageHashes.clone(), &[params, subscription]).await;
Value::Null
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// initial snapshot is fetched with ccxt's fetchOrderBook
// the feed does not include a snapshot, just the deltas
//
// {
// "type":"message",
// "topic":"/market/level2:BTC-USDT",
// "subject":"trade.l2update",
// "data":{
// "sequenceStart":1545896669105,
// "sequenceEnd":1545896669106,
// "symbol":"BTC-USDT",
// "changes": {
// "asks": [["6","1","1545896669105"]], // price, size, sequence
// "bids": [["4","1","1545896669106"]]
// }
// }
// }
//
// {
// "topic": "/spotMarket/level2Depth5:BTC-USDT",
// "type": "message",
// "data": {
// "asks": [
// [
// "42815.6",
// "1.24016245"
// ]
// ],
// "bids": [
// [
// "42815.5",
// "0.08652716"
// ]
// ],
// "timestamp": 1707204474018
// },
// "subject": "level2"
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Null });
let mut topic: Value = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut topicParts: Value = split(&topic, &Value::Str(":".into()));
let mut topicSymbol: Value = self.safe_string(topicParts.clone(), Value::Int(1), &[]);
let mut topicChannel: Value = self.safe_string(topicParts, Value::Int(0), &[]);
let mut marketId: Value = self.safe_string_k(data.clone(), "symbol", &[topicSymbol.clone()]);
let mut symbol: Value = self.safe_symbol(marketId, &[Value::Null, Value::Str("-".into())]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbol).into());
// let orderbook = this.safeDict (this.orderbooks, symbol);
if Value::Int(topic.as_str().and_then(|__s| __s.find("Depth")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
if !(in_op(&self.orderbooks, &symbol)) {
{ let __be_tmp = self.order_book(&[]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
} else {
let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
orderbook.reset0();
}
add_element_to_object(get_value_mut(&mut self.orderbooks, &symbol), &Value::Str("symbol".into()), symbol.clone());
} else {
if !(in_op(&self.orderbooks, &symbol)) {
{ let __be_tmp = self.order_book(&[]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
}
let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
let mut nonce: Value = self.safe_integer_k(orderbook.clone(), "nonce", &[]);
let mut deltaEnd: Value = self.safe_integer2(data.clone(), Value::Str("sequenceEnd".into()), Value::Str("timestamp".into()), &[]);
if (nonce == Value::Null) {
let mut cacheLength: Value = Value::Int(get_value(&orderbook, &Value::Str("cache".into())).len() as i64);
let mut subscriptions: Value = object_keys(&get_value(&client, &Value::Str("subscriptions".into())));
let mut subscription: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_445: bool = true;
while { if !__for_first_445 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_445 = false; i.as_f64().unwrap_or(f64::NAN) < ((subscriptions.len() as i64) as f64) } {
let mut key: Value = subscriptions.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if (get_index_of(&key, &topicSymbol).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64)) && (get_index_of(&key, &topicChannel).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64)) {
subscription = get_value(&get_value(&client, &Value::Str("subscriptions".into())), &key);
break;
}
}
}
let mut limit: Value = self.safe_integer_k(subscription, "limit", &[]);
let mut snapshotDelay: Value = self.handle_option(Value::Str("watchOrderBook".into()), Value::Str("snapshotDelay".into()), &[Value::Int(5)]);
if is_equal(&cacheLength, &snapshotDelay) {
self.spawn(&[Value::Str("load_order_book".into()).clone(), client.clone(), messageHash.clone(), symbol.clone(), limit, Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
crate::runtime::append_to_object_array(&mut orderbook, &Value::Str("cache".into()), data.clone());
return;
} else if nonce.as_f64().unwrap_or(f64::NAN) >= deltaEnd.as_f64().unwrap_or(f64::NAN) {
return;
}
}
self.handle_delta(get_value(&self.orderbooks, &symbol), data);
client.resolve(&[get_value(&self.orderbooks, &symbol), messageHash]);
}
pub fn handle_uta_order_book(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// snapshot
// {
// "T": "obu.SPOT",
// "dp": "50",
// "t": "snapshot",
// "P": "1774624848680504909",
// "d": {
// "C": 20452522782,
// "M": "1774624848673000000",
// "O": 20452522782,
// "a": [ [ "66532.5", "0.46243848" ] ],
// "b": [ [ "66532.4", "0.09489" ] ],
// "s": "ETH-USDT"
// }
// }
//
let mut type_var: Option<String> = (match message.get("t") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
let mut data: Value = (match message.get("d") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = self.safe_integer_product_k(data.clone(), "M", Value::Float(0.000001), &[]);
if !(in_op(&self.orderbooks, &symbol)) {
{ let __be_tmp = self.order_book(&[]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
}
let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
let mut depth: Value = (match message.get("dp") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("uta:orderbook:".into()), symbol).into()), Value::Str(":depth:".into())).into()), depth).into());
if (type_var.as_deref() == Some("snapshot")) {
let mut parsed: Value = self.parse_order_book(data.clone(), symbol.clone(), &[timestamp, Value::Str("b".into()), Value::Str("a".into()), Value::Int(0), Value::Int(1)]);
add_element_to_object(&mut parsed, &Value::Str("nonce".into()), self.safe_integer_k(data.clone(), "O", &[]));
orderbook.reset(parsed);
if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), orderbook.clone()); }
} else {
let mut nonce: Value = self.safe_integer_k(orderbook.clone(), "nonce", &[]);
let mut deltaEnd: Value = self.safe_integer_k(data.clone(), "C", &[]);
if (nonce == Value::Null) {
let mut cacheLength: Value = Value::Int(get_value(&orderbook, &Value::Str("cache".into())).len() as i64);
let mut subscription: Value = self.safe_dict(get_value(&client, &Value::Str("subscriptions".into())), messageHash.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut limit: Value = self.safe_integer_k(subscription, "limit", &[]);
let mut snapshotDelay: Value = self.handle_option(Value::Str("watchOrderBook".into()), Value::Str("snapshotDelay".into()), &[Value::Int(5)]);
let mut utaParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("uta".to_string(), Value::Bool(true));
m
});
if is_equal(&cacheLength, &snapshotDelay) {
self.spawn(&[Value::Str("load_order_book".into()).clone(), client.clone(), messageHash.clone(), symbol.clone(), limit, utaParams]);
}
crate::runtime::append_to_object_array(&mut orderbook, &Value::Str("cache".into()), data.clone());
return;
} else if nonce.as_f64().unwrap_or(f64::NAN) >= deltaEnd.as_f64().unwrap_or(f64::NAN) {
return;
}
}
self.handle_delta(get_value(&self.orderbooks, &symbol), data);
client.resolve(&[get_value(&self.orderbooks, &symbol), messageHash]);
}
pub fn get_cache_index(&self, mut orderbook: Value, mut cache: Value) -> Value {
let mut firstDelta: Value = self.safe_dict(cache.clone(), Value::Int(0), &[]);
let mut nonce: Value = self.safe_integer_k(orderbook, "nonce", &[]);
let mut firstDeltaStart: Value = self.safe_integer_n(firstDelta, Value::from(vec![Value::Str("sequenceStart".into()), Value::Str("sequence".into()), Value::Str("O".into())]), &[]);
if (nonce == Value::Null) || (firstDeltaStart == Value::Null) {
return Value::Int(-1);
}
if nonce.as_f64().unwrap_or(f64::NAN) < (match (&(firstDeltaStart), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }).as_f64().unwrap_or(f64::NAN) {
return Value::Int(-1);
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_446: bool = true;
while { if !__for_first_446 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_446 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&cache).as_f64().unwrap_or(f64::NAN) } {
let mut delta: Value = get_value(&cache, &i);
let mut delta: Value = get_value(&cache, &i);
let mut deltaStart: Value = self.safe_integer_n(delta.clone(), Value::from(vec![Value::Str("sequenceStart".into()), Value::Str("sequence".into()), Value::Str("O".into())]), &[]);
let mut deltaEnd: Value = self.safe_integer_n(delta, Value::from(vec![Value::Str("sequenceEnd".into()), Value::Str("sequence".into()), Value::Str("C".into())]), &[]); // todo check
if (deltaStart == Value::Null) || (deltaEnd == Value::Null) {
continue;
}
if (nonce.as_f64().unwrap_or(f64::NAN) >= (match (&(deltaStart), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }).as_f64().unwrap_or(f64::NAN)) && (nonce.as_f64().unwrap_or(f64::NAN) < deltaEnd.as_f64().unwrap_or(f64::NAN)) {
return i;
}
}
}
return get_array_length(&cache);
Value::Null
}
pub fn handle_delta(&self, mut orderbook: Value, mut delta: Value) {
let mut timestamp: Value = self.safe_integer_product_k(delta.clone(), "M", Value::Float(0.000001), &[]);
if (timestamp == Value::Null) {
timestamp = self.safe_integer2(delta.clone(), Value::Str("time".into()), Value::Str("timestamp".into()), &[]);
}
add_element_to_object(&mut orderbook, &Value::Str("nonce".into()), self.safe_integer_n(delta.clone(), Value::from(vec![Value::Str("sequenceEnd".into()), Value::Str("sequence".into()), Value::Str("C".into())]), &[timestamp.clone()]));
add_element_to_object(&mut orderbook, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut orderbook, &Value::Str("datetime".into()), self.iso8601(timestamp));
let mut change: Value = self.safe_string_k(delta.clone(), "change", &[]);
let mut changes: Value = self.safe_dict_k(delta.clone(), "changes", &[delta.clone()]);
let mut storedBids: Value = crate::value::get_value_k(&orderbook, "bids");
let mut storedAsks: Value = crate::value::get_value_k(&orderbook, "asks");
if (change != Value::Null) {
// handling futures orderbook update
let mut splitChange: Value = split(&change, &Value::Str(",".into()));
let mut price: Value = self.safe_number(splitChange.clone(), Value::Int(0), &[]);
let mut side: Option<String> = self.safe_string(splitChange.clone(), Value::Int(1), &[]).as_str().map(str::to_owned);
let mut quantity: Value = self.safe_number(splitChange, Value::Int(2), &[]);
let mut type_var: Value = (if (side.as_deref() == Some("buy")) { Value::Str("bids".into()) } else { Value::Str("asks".into()) });
let mut value: Value = Value::from(vec![price, quantity]);
if (type_var.as_str() == Some("bids")) {
storedBids.store_array(value.clone());
} else {
storedAsks.store_array(value);
}
} else if (changes != Value::Null) {
let mut bids: Value = self.safe_list_k(changes.clone(), "bids", &[Value::from(vec![])]);
let mut asks: Value = self.safe_list_k(changes, "asks", &[Value::from(vec![])]);
self.handle_bid_asks(storedBids.clone(), bids.clone());
self.handle_bid_asks(storedAsks.clone(), asks.clone());
} else {
let mut bids: Value = self.safe_list2(delta.clone(), Value::Str("bids".into()), Value::Str("b".into()), &[Value::from(vec![])]);
let mut asks: Value = self.safe_list2(delta, Value::Str("asks".into()), Value::Str("a".into()), &[Value::from(vec![])]);
self.handle_bid_asks(storedBids, bids);
self.handle_bid_asks(storedAsks, asks);
}
}
pub fn handle_bid_asks(&self, mut bookSide: Value, mut bidAsks: Value) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_447: bool = true;
while { if !__for_first_447 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_447 = false; i.as_f64().unwrap_or(f64::NAN) < ((bidAsks.len() as i64) as f64) } {
let mut bidAsk: Value = self.parse_order_book_bid_ask(bidAsks.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[]);
bookSide.store_array(bidAsk);
}
}
}
pub fn handle_order_book_subscription(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
let mut limit: Value = self.safe_integer_k(subscription.clone(), "limit", &[]);
let mut symbols: Value = self.safe_list_k(subscription.clone(), "symbols", &[]);
if (symbols == Value::Null) {
let mut symbol: Value = self.safe_string_k(subscription, "symbol", &[]);
{ let __be_tmp = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), limit.clone()]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_448: bool = true;
while { if !__for_first_448 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_448 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
{ let __be_tmp = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), limit.clone()]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
}
}
}
}
pub fn handle_subscription_status(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// classic
// {
// "id": "1578090438322",
// "type": "ack"
// }
//
// uta
// {
// "id": "1",
// "result": true
// }
//
let mut id: Value = (match __pro_message.get("id").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &id)) {
return;
}
let mut subscriptionHash: Value = self.safe_string(get_value(&client, &Value::Str("subscriptions".into())), id.clone(), &[]);
let mut subscription: Value = self.safe_dict(get_value(&client, &Value::Str("subscriptions".into())), subscriptionHash, &[]);
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &id);
let mut method: Value = self.safe_value_k(subscription.clone(), "method", &[]);
if (method != Value::Null) {
self.dispatch_ws_handler(&method, &[client.clone(), message, subscription.clone()]);
}
let mut isUnSub: Value = self.safe_bool_k(subscription.clone(), "unsubscribe", &[Value::Bool(false)]);
if (isUnSub.as_bool() == Some(true)) {
let mut messageHashes: Value = self.safe_list_k(subscription.clone(), "messageHashes", &[Value::from(vec![])]);
let mut subMessageHashes: Value = self.safe_list_k(subscription.clone(), "subMessageHashes", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_449: bool = true;
while { if !__for_first_449 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_449 = false; i.as_f64().unwrap_or(f64::NAN) < ((messageHashes.len() as i64) as f64) } {
let mut messageHash: Value = messageHashes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut subHash: Value = subMessageHashes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
self.clean_unsubscription(client.clone(), subHash, messageHash, &[]);
}
}
let mut topic: Option<String> = self.safe_string_k(subscription.clone(), "topic", &[]).as_str().map(str::to_owned);
if (topic.as_deref() == Some("fundingRate")) {
// todo: add fundingRate topic to cleanCache
let mut symbols: Value = self.safe_list_k(subscription.clone(), "symbols", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_450: bool = true;
while { if !__for_first_450 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_450 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if (in_op(&self.fundingRates, &symbol)) {
remove(&mut self.fundingRates, &symbol);
}
}
}
} else {
self.clean_cache(subscription);
}
}
}
pub fn handle_system_status(&self, mut client: Value, mut message: Value) -> Value {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// todo: answer the question whether handleSystemStatus should be renamed
// and unified as handleStatus for any usage pattern that
// involves system status and maintenance updates
//
// {
// "id": "1578090234088", // connectId
// "type": "welcome",
// }
//
// uta
// {
// "sessionId": "ddfb0cbd-f7a7-40c2-9129-445bbb830c54",
// "message": "welcome",
// "pingInterval": 18000
// }
//
let mut pingInterval: Value = (match __pro_message.get("pingInterval").cloned() { Some(Value::Int(__n)) => Value::Int(__n), Some(Value::Float(__f)) => Value::Int(__f as i64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
if (pingInterval != Value::Null) {
crate::set_value(&mut client, &Value::Str("keepAlive".into()), pingInterval);
}
return message;
Value::Null
}
/*
* @method
* @name kucoin#watchOrders
* @description watches information on multiple orders made by the user
* @see https://www.kucoin.com/docs-new/3470074w0 // spot regular orders
* @see https://www.kucoin.com/docs-new/3470139w0 // spot trigger orders
* @see https://www.kucoin.com/docs-new/3470090w0 // contract regular orders
* @see https://www.kucoin.com/docs-new/3470091w0 // contract trigger orders
* @see https://www.kucoin.com/docs-new/3470228w0 // uta orders
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.uta] set to true for the unified trading account (uta)
* @param {boolean} [params.trigger] trigger orders are watched if true
* @param {string} [params.type] 'spot' or 'swap' (default is 'spot' if symbol is not provided)
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn watch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut uta: Value = self.is_uta_enabled(&[]).await;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrders".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut market: Value = Value::Null;
let mut messageHash: Value = Value::Str("orders".into());
if (symbol != Value::Null) {
market = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str(":".into())).into()), symbol).into());
}
let mut orders: Value = Value::Null;
if is_true(&uta) {
params = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tradeType".to_string(), Value::Str("UNIFIED".into()));
m
})]);
messageHash = Value::Str(format!("{}{}", Value::Str("uta:".into()), messageHash).into());
let mut channel: Value = Value::Str("order".into());
if (symbol == Value::Null) {
channel = Value::Str(format!("{}{}", channel, Value::Str("All".into())).into());
}
orders = self.subscribe_private_uta(Value::from(vec![messageHash.clone()]), messageHash.clone(), channel, &[symbol.clone(), params.clone()]).await;
} else {
let mut trigger: Value = self.safe_bool2(params.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("stop".into()), Value::Str("trigger".into())]), &[]);
let mut marketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchOrders".into()), &[market, params.clone()]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut isFuturesMethod: Value = (Value::Bool((marketType.as_str() != Some("spot")) && (marketType.as_str() != Some("margin"))));
let mut url: Value = self.negotiate(Value::Bool(true), &[isFuturesMethod.clone()]).await;
let mut topic: Value = (if (trigger.as_bool() == Some(true)) { Value::Str("/spotMarket/advancedOrders".into()) } else { Value::Str("/spotMarket/tradeOrders".into()) });
if matches!(&isFuturesMethod, Value::Bool(true)) {
topic = (if (trigger.as_bool() == Some(true)) { Value::Str("/contractMarket/advancedOrders".into()) } else { Value::Str("/contractMarket/tradeOrders".into()) });
}
if (symbol == Value::Null) {
let mut suffix: Value = self.get_orders_message_hash_suffix(topic.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
messageHash = Value::Str(format!("{}{}", messageHash, suffix).into());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("privateChannel".to_string(), Value::Bool(true));
m
});
let __ws_arg_2 = self.extend(request, &[params]);
orders = self.subscribe(url, messageHash, topic, &[__ws_arg_2]).await;
}
if is_true(&self.newUpdates) {
limit = orders.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_symbol_since_limit(orders, &[symbol, since, limit, Value::Bool(true)]);
Value::Null
}
pub fn get_orders_message_hash_suffix(&self, mut topic: Value) -> Option<String> {
let mut suffix: Value = Value::Str("-spot".into());
if (topic.as_str() == Some("/spotMarket/advancedOrders")) {
suffix = Value::Str(format!("{}{}", suffix, Value::Str("-trigger".into())).into());
} else if (topic.as_str() == Some("/contractMarket/tradeOrders")) {
suffix = Value::Str("-contract".into());
} else if (topic.as_str() == Some("/contractMarket/advancedOrders")) {
suffix = Value::Str("-contract-trigger".into());
}
return suffix.as_str().map(str::to_owned);
}
pub fn parse_ws_order_status(&self, mut status: Value) -> Option<String> {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("open".to_string(), Value::Str("open".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("match".to_string(), Value::Str("open".into()));
m.insert("update".to_string(), Value::Str("open".into()));
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m.insert("cancel".to_string(), Value::Str("canceled".into()));
m.insert("TRIGGERED".to_string(), Value::Str("triggered".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub fn parse_ws_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// /spotMarket/tradeOrders
//
// {
// "symbol": "XCAD-USDT",
// "orderType": "limit",
// "side": "buy",
// "orderId": "6249167327218b000135e749",
// "type": "canceled",
// "orderTime": 1648957043065280224,
// "size": "100.452",
// "filledSize": "0",
// "price": "2.9635",
// "clientOid": "buy-XCAD-USDT-1648957043010159",
// "remainSize": "0",
// "status": "done",
// "ts": 1648957054031001037
// }
//
// /spotMarket/advancedOrders
//
// {
// "createdAt": 1589789942337,
// "orderId": "5ec244f6a8a75e0009958237",
// "orderPrice": "0.00062",
// "orderType": "stop",
// "side": "sell",
// "size": "1",
// "stop": "entry",
// "stopPrice": "0.00062",
// "symbol": "KCS-BTC",
// "tradeType": "TRADE",
// "triggerSuccess": true,
// "ts": 1589790121382281286,
// "type": "triggered"
// }
//
// futures
// {
// "symbol": "ETHUSDTM",
// "orderType": "market",
// "side": "buy",
// "canceledSize": "0",
// "orderId": "416204113500479490",
// "positionSide": "LONG",
// "liquidity": "taker",
// "marginMode": "ISOLATED",
// "type": "match",
// "feeType": "takerFee",
// "orderTime": "1772043995356345762",
// "size": "1",
// "filledSize": "1",
// "price": "0",
// "matchPrice": "2068.55",
// "matchSize": "1",
// "remainSize": "0",
// "tradeId": "1815302608109",
// "clientOid": "9f7a2be0-effe-45bd-bdc8-1614715a583a",
// "tradeType": "trade",
// "status": "match",
// "ts": 1772043995362000000
// }
//
let mut rawType: Value = self.safe_string_k(order.clone(), "type", &[]);
let mut status: Value = self.parse_ws_order_status(rawType).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut timestamp: Value = self.safe_integer2(order.clone(), Value::Str("orderTime".into()), Value::Str("createdAt".into()), &[]);
let mut marketId: Value = self.safe_string_k(order.clone(), "symbol", &[]);
market = self.safe_market(&[marketId, market.clone()]);
if (market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
timestamp = self.safe_integer_product_k(order.clone(), "orderTime", Value::Float(0.000001), &[]);
}
let mut triggerPrice: Value = self.safe_string_k(order.clone(), "stopPrice", &[]);
let mut triggerSuccess: Value = self.safe_bool_k(order.clone(), "triggerSuccess", &[]);
let mut triggerFail: bool = (triggerSuccess.as_bool() != Some(true)) && (triggerSuccess != Value::Null); // TODO: updated to triggerSuccess === False once transpiler transpiles it correctly
if (status.as_str() == Some("triggered")) && triggerFail {
status = Value::Str("canceled".into());
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("id".to_string(), self.safe_string_k(order.clone(), "orderId", &[]));
m.insert("clientOrderId".to_string(), self.safe_string_k(order.clone(), "clientOid", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("type".to_string(), self.safe_string_lower_k(order.clone(), "orderType", &[]));
m.insert("timeInForce".to_string(), Value::Null);
m.insert("postOnly".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_lower_k(order.clone(), "side", &[]));
m.insert("price".to_string(), self.safe_string2(order.clone(), Value::Str("price".into()), Value::Str("orderPrice".into()), &[]));
m.insert("stopPrice".to_string(), triggerPrice.clone());
m.insert("triggerPrice".to_string(), triggerPrice);
m.insert("amount".to_string(), self.safe_string_k(order.clone(), "size", &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("filled".to_string(), self.safe_string_k(order, "filledSize", &[]));
m.insert("remaining".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[market]);
Value::Null
}
pub fn parse_ws_uta_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "tT": "FUTURES",
// "oi": "427737326394129559",
// "ci": "",
// "os": 5,
// "eT": "CANCEL",
// "s": "DOGEUSDTM",
// "S": "SELL",
// "oT": "MARKET",
// "lR": "",
// "oS": "USER",
// "p": "",
// "ti": "",
// "q": "1",
// "qU": "UNIT",
// "fS": "0",
// "lS": "0",
// "ls": "0",
// "aP": "0",
// "f": "0",
// "fC": "USDT",
// "t": "0",
// "cR": "USER",
// "cS": "1",
// "rS": "0",
// "tD": "DOWN",
// "tP": "0.01",
// "tPT": "MP",
// "pP": "",
// "pPT": "",
// "lP": "",
// "lPT": "",
// "toi": "427737326102335488",
// "stp": "",
// "rO": true,
// "tIF": "GTC",
// "pO": false,
// "O": "1774793727626043888",
// "U": 1774794309608959200
// }
//
let mut timestamp: Value = self.safe_integer_product_k(order.clone(), "O", Value::Float(0.000001), &[]);
let mut rawStatus: Value = self.safe_string_k(order.clone(), "os", &[]);
let mut marketId: Value = self.safe_string_k(order.clone(), "s", &[]);
let mut rawTimeInForce: Value = self.safe_string_k(order.clone(), "tIF", &[]);
let mut remainSize: Value = self.safe_string_k(order.clone(), "rS", &[]);
let mut canceledSize: Value = self.safe_string_k(order.clone(), "cS", &[]);
let mut remaining: Value = crate::precise::Precise::stringAdd(&remainSize, &canceledSize);
market = self.safe_market(&[marketId, market.clone()]);
let mut fee: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.safe_string_k(order.clone(), "f", &[]));
m.insert("currency".to_string(), self.safe_currency_code(self.safe_string_k(order.clone(), "fC", &[]), &[]));
m
});
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), self.safe_string_k(order.clone(), "oi", &[]));
m.insert("clientOrderId".to_string(), self.safe_string_k(order.clone(), "ci", &[]));
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("timestamp".to_string(), timestamp);
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), self.safe_integer_product_k(order.clone(), "U", Value::Float(0.000001), &[]));
m.insert("status".to_string(), self.parent.parse_order_status(rawStatus).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), self.safe_string_lower_k(order.clone(), "oT", &[]));
m.insert("timeInForce".to_string(), self.parent.parse_order_time_in_force(rawTimeInForce).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("side".to_string(), self.safe_string_lower_k(order.clone(), "S", &[]));
m.insert("price".to_string(), self.safe_string_k(order.clone(), "p", &[]));
m.insert("average".to_string(), self.safe_string_k(order.clone(), "aP", &[]));
m.insert("amount".to_string(), self.safe_string_k(order.clone(), "q", &[]));
m.insert("filled".to_string(), self.safe_string_k(order.clone(), "fS", &[]));
m.insert("remaining".to_string(), remaining);
m.insert("triggerPrice".to_string(), self.safe_string_k(order.clone(), "tP", &[]));
m.insert("takeProfitPrice".to_string(), self.safe_string_k(order.clone(), "pP", &[]));
m.insert("stopLossPrice".to_string(), self.safe_string_k(order.clone(), "lP", &[]));
m.insert("cost".to_string(), self.safe_string_k(order.clone(), "c", &[]));
m.insert("trades".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m.insert("reduceOnly".to_string(), self.safe_bool_k(order.clone(), "rO", &[]));
m.insert("postOnly".to_string(), self.safe_bool_k(order, "pO", &[]));
m
}), &[market]);
Value::Null
}
pub fn handle_order(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// Trigger Orders
//
// {
// "createdAt": 1692745706437,
// "error": "Balance insufficient!", // not always there
// "orderId": "vs86kp757vlda6ni003qs70v",
// "orderPrice": "0.26",
// "orderType": "stop",
// "side": "sell",
// "size": "5",
// "stop": "loss",
// "stopPrice": "0.26",
// "symbol": "ADA-USDT",
// "tradeType": "TRADE",
// "triggerSuccess": false, // not always there
// "ts": "1692745706442929298",
// "type": "open"
// }
//
let mut data: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
let mut tradeId: Option<String> = self.safe_string_k(data.clone(), "tradeId", &[]).as_str().map(str::to_owned);
if (tradeId.is_some()) {
self.handle_my_trade(client.clone(), message);
}
let mut parsed: Value = self.parse_ws_order(data.clone(), &[]);
let mut symbol: Value = self.safe_string_k(parsed.clone(), "symbol", &[]);
let mut orderId: Value = self.safe_string_k(parsed.clone(), "id", &[]);
let mut triggerPrice: Option<String> = self.safe_string_k(parsed.clone(), "triggerPrice", &[]).as_str().map(str::to_owned);
let mut isTriggerOrder: bool = triggerPrice.is_some();
if (self.orders.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCacheBySymbolById::new(limit.clone());
self.triggerOrders = ArrayCacheBySymbolById::new(limit);
}
let mut cachedOrders: Value = (if isTriggerOrder { self.triggerOrders.clone() } else { self.orders.clone() });
let mut orders: Value = self.safe_dict(cachedOrders.hashmap(), symbol.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut order: Value = self.safe_dict(orders, orderId, &[]);
if (order != Value::Null) {
if (order.as_map().and_then(|__m| __m.get("status")).cloned().unwrap_or(Value::Null).as_str() == Some("closed")) {
add_element_to_object(&mut parsed, &Value::Str("status".into()), Value::Str("closed".into()));
}
// carry the accumulated fill state forward, the raw feed only
// carries the match prices on the match messages, and safeOrder
// derives cost from the order price otherwise, which is wrong for
// orders filled at better prices, so the accumulated values win on
// the non match messages, see https://github.com/ccxt/ccxt/issues/19083
if (order.as_map().and_then(|__m| __m.get("average")).cloned().unwrap_or(Value::Null) != Value::Null) {
add_element_to_object(&mut parsed, &Value::Str("average".into()), order.as_map().and_then(|__m| __m.get("average")).cloned().unwrap_or(Value::Null));
add_element_to_object(&mut parsed, &Value::Str("cost".into()), order.as_map().and_then(|__m| __m.get("cost")).cloned().unwrap_or(Value::Null));
}
if (parsed.as_map().and_then(|__m| __m.get("filled")).cloned().unwrap_or(Value::Null) == Value::Null) {
add_element_to_object(&mut parsed, &Value::Str("filled".into()), order.as_map().and_then(|__m| __m.get("filled")).cloned().unwrap_or(Value::Null));
}
}
// accumulate the average fill price and cost from the match messages,
// which carry matchPrice and matchSize, the terminal filled message
// does not repeat them, see https://github.com/ccxt/ccxt/issues/19083
let mut rawType: Option<String> = self.safe_string_k(data.clone(), "type", &[]).as_str().map(str::to_owned);
let mut matchPrice: Value = self.safe_string_k(data.clone(), "matchPrice", &[]);
let mut matchSize: Value = self.safe_string_k(data, "matchSize", &[]);
if (rawType.as_deref() == Some("match")) && (matchPrice != Value::Null) && (matchSize != Value::Null) {
let mut matchCost: Value = crate::precise::Precise::stringMul(&matchPrice, &matchSize);
let mut previousCost: Value = (if (order == Value::Null) { Value::Str("0".into()) } else { self.number_to_string(self.safe_number_k(order, "cost", &[Value::Int(0)])) });
let mut costString: Value = crate::precise::Precise::stringAdd(&previousCost, &matchCost);
add_element_to_object(&mut parsed, &Value::Str("cost".into()), self.parse_number(costString.clone(), &[]));
let mut filledString: Value = self.number_to_string(parsed.as_map().and_then(|__m| __m.get("filled")).cloned().unwrap_or(Value::Null));
if (filledString != Value::Null) && is_true(&(crate::precise::Precise::stringGt(&filledString, &Value::Str("0".into())))) {
add_element_to_object(&mut parsed, &Value::Str("average".into()), self.parse_number(crate::precise::Precise::stringDiv(&costString, &filledString), &[]));
}
}
cachedOrders.append(parsed);
let mut messageHash: Value = Value::Str("orders".into());
let mut topic: Value = (match __pro_message.get("topic").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut suffix: Value = self.get_orders_message_hash_suffix(topic).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut typeSpecificMessageHash: Value = Value::Str(format!("{}{}", messageHash, suffix).into());
client.resolve(&[cachedOrders.clone(), typeSpecificMessageHash]);
let mut symbolSpecificMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str(":".into())).into()), symbol).into());
client.resolve(&[cachedOrders, symbolSpecificMessageHash]);
}
pub fn handle_uta_order(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "T": "orderAll.UNIFIED",
// "P": "1774794309609274499",
// "d": {
// "tT": "FUTURES",
// "oi": "427737326394129559",
// "ci": "",
// "os": 5,
// "eT": "CANCEL",
// "s": "DOGEUSDTM",
// "S": "SELL",
// "oT": "MARKET",
// "lR": "",
// "oS": "USER",
// "p": "",
// "ti": "",
// "q": "1",
// "qU": "UNIT",
// "fS": "0",
// "lS": "0",
// "ls": "0",
// "aP": "0",
// "f": "0",
// "fC": "USDT",
// "t": "0",
// "cR": "USER",
// "cS": "1",
// "rS": "0",
// "tD": "DOWN",
// "tP": "0.01",
// "tPT": "MP",
// "pP": "",
// "pPT": "",
// "lP": "",
// "lPT": "",
// "toi": "427737326102335488",
// "stp": "",
// "rO": true,
// "tIF": "GTC",
// "pO": false,
// "O": "1774793727626043888",
// "U": 1774794309608959200
// }
// }
//
let mut data: Value = (match message.get("d") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut parsed: Value = self.parse_ws_uta_order(data, &[]);
let mut symbol: Value = self.safe_string_k(parsed.clone(), "symbol", &[]);
if (self.orders.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCacheBySymbolById::new(limit);
}
let mut cachedOrders: Value = self.orders.clone();
cachedOrders.append(parsed);
let mut messageHash: Value = Value::Str("uta:orders".into());
let mut symbolSpecificMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str(":".into())).into()), symbol).into());
client.resolve(&[cachedOrders.clone(), symbolSpecificMessageHash]);
client.resolve(&[cachedOrders, messageHash]);
}
/*
* @method
* @name kucoin#watchMyTrades
* @description watches information on multiple trades made by the user on spot
* @see https://www.kucoin.com/docs-new/3470074w0
* @see https://www.kucoin.com/docs-new/3470090w0
* @see https://www.kucoin.com/docs-new/3470264w0
* @param {string} symbol unified market symbol of the market trades were made in
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trade structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.uta] set to true for the unified trading account (uta)
* @param {string} [params.method] *classic (non-uta) account only* '/spotMarket/tradeOrders' or '/spot/tradeFills' or '/contractMarket/tradeOrders', default is '/spotMarket/tradeOrders'
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut messageHash: Value = Value::Str("myTrades".into());
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str(":".into())).into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into());
}
let mut marketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchMyTrades".into()), &[market, params.clone()]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut isFuturesMethod: Value = (Value::Bool((marketType.as_str() != Some("spot")) && (marketType.as_str() != Some("margin"))));
let mut uta: Value = self.is_uta_enabled(&[]).await;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchMyTrades".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut trades: Value = Value::Null;
if is_true(&uta) {
params = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tradeType".to_string(), Value::Str("UNIFIED".into()));
m
})]);
messageHash = Value::Str(format!("{}{}", Value::Str("uta:".into()), messageHash).into());
let mut channel: Value = Value::Str("execution.lite".into());
trades = self.subscribe_private_uta(Value::from(vec![messageHash.clone()]), channel.clone(), channel.clone(), &[Value::Null, params.clone()]).await;
} else {
let mut url: Value = self.negotiate(Value::Bool(true), &[isFuturesMethod.clone()]).await;
let mut topic: Value = (if matches!(&isFuturesMethod, Value::Bool(true)) { Value::Str("/contractMarket/tradeOrders".into()) } else { Value::Str("/spotMarket/tradeOrders".into()) });
let mut optionName: Value = (if matches!(&isFuturesMethod, Value::Bool(true)) { Value::Str("contractMethod".into()) } else { Value::Str("spotMethod".into()) });
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("watchMyTrades".into()), optionName, Value::Str("method".into()), &[topic.clone()]); topic = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("privateChannel".to_string(), Value::Bool(true));
m
});
if (symbol == Value::Null) {
let mut suffix: Value = self.get_my_trades_message_hash_suffix(topic.clone());
messageHash = Value::Str(format!("{}{}", messageHash, suffix).into());
}
let __ws_arg_3 = self.extend(request, &[params]);
trades = self.subscribe(url, messageHash, topic, &[__ws_arg_3]).await;
}
if is_true(&self.newUpdates) {
limit = trades.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_symbol_since_limit(trades, &[symbol, since, limit, Value::Bool(true)]);
Value::Null
}
pub fn get_my_trades_message_hash_suffix(&self, mut topic: Value) -> Value {
let mut suffix: Value = Value::Str("-spot".into());
if get_index_of(&topic, &Value::Str("contractMarket".into())).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
suffix = Value::Str("-contract".into());
}
return suffix;
Value::Null
}
pub fn handle_my_trade(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "type": "message",
// "topic": "/spotMarket/tradeOrders",
// "subject": "orderChange",
// "channelType": "private",
// "data": {
// "symbol": "KCS-USDT",
// "orderType": "limit",
// "side": "sell",
// "orderId": "5efab07953bdea00089965fa",
// "liquidity": "taker",
// "type": "match",
// "feeType": "takerFee",
// "orderTime": 1670329987026,
// "size": "0.1",
// "filledSize": "0.1",
// "price": "0.938",
// "matchPrice": "0.96738",
// "matchSize": "0.1",
// "tradeId": "5efab07a4ee4c7000a82d6d9",
// "clientOid": "1593487481000313",
// "remainSize": "0",
// "status": "match",
// "ts": 1670329987311000000
// }
// }
//
if (self.myTrades.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCacheBySymbolById::new(limit);
}
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Null });
let mut parsed: Value = self.parse_ws_trade(data, &[]);
let mut myTrades: Value = self.myTrades.clone();
myTrades.append(parsed.clone());
let mut messageHash: Value = Value::Str("myTrades".into());
let mut topic: Value = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut suffix: Value = self.get_my_trades_message_hash_suffix(topic);
let mut typeSpecificMessageHash: Value = Value::Str(format!("{}{}", messageHash, suffix).into());
client.resolve(&[self.myTrades.clone(), typeSpecificMessageHash]);
let mut symbolSpecificMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str(":".into())).into()), parsed.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into());
client.resolve(&[self.myTrades.clone(), symbolSpecificMessageHash]);
}
pub fn handle_uta_my_trade(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "T": "execution.lite.UNIFIED",
// "P": "1774977429844510434",
// "d": {
// "E": "1774977429843000000",
// "S": "SELL",
// "p": "0.09211",
// "q": "10",
// "s": "DOGE-USDT",
// "lR": "TAKER",
// "oT": "MARKET",
// "oi": "428507829452754944",
// "ti": 20801647764195330
// }
// }
//
let mut data: Value = (match message.get("d") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut trade: Value = self.parse_ws_uta_trade(data, &[market]);
let mut symbol: Value = trade.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (self.myTrades.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCacheBySymbolById::new(limit);
}
let mut cache: Value = self.myTrades.clone();
cache.append(trade);
let mut messageHash: Value = Value::Str("uta:myTrades".into());
let mut symbolMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str(":".into())).into()), symbol).into());
client.resolve(&[self.myTrades.clone(), messageHash]);
client.resolve(&[cache, symbolMessageHash]);
}
pub fn parse_ws_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// /spotMarket/tradeOrders
//
// {
// "symbol": "KCS-USDT",
// "orderType": "limit",
// "side": "sell",
// "orderId": "5efab07953bdea00089965fa",
// "liquidity": "taker",
// "type": "match",
// "feeType": "takerFee",
// "orderTime": 1670329987026,
// "size": "0.1",
// "filledSize": "0.1",
// "price": "0.938",
// "matchPrice": "0.96738",
// "matchSize": "0.1",
// "tradeId": "5efab07a4ee4c7000a82d6d9",
// "clientOid": "1593487481000313",
// "remainSize": "0",
// "status": "match",
// "ts": 1670329987311000000
// }
//
// /spot/tradeFills
//
// {
// "fee": 0.00262148,
// "feeCurrency": "USDT",
// "feeRate": 0.001,
// "orderId": "62417436b29df8000183df2f",
// "orderType": "market",
// "price": 131.074,
// "side": "sell",
// "size": 0.02,
// "symbol": "LTC-USDT",
// "time": "1648456758734571745",
// "tradeId": "624174362e113d2f467b3043"
// }
//
let mut marketId: Value = self.safe_string_k(trade.clone(), "symbol", &[]);
market = self.safe_market(&[marketId, market.clone(), Value::Str("-".into())]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut type_var: Value = self.safe_string_k(trade.clone(), "orderType", &[]);
let mut side: Value = self.safe_string_k(trade.clone(), "side", &[]);
let mut tradeId: Value = self.safe_string_k(trade.clone(), "tradeId", &[]);
let mut price: Value = self.safe_string_k(trade.clone(), "matchPrice", &[]);
let mut amount: Value = self.safe_string_k(trade.clone(), "matchSize", &[]);
if (price == Value::Null) {
// /spot/tradeFills
price = self.safe_string_k(trade.clone(), "price", &[]);
amount = self.safe_string_k(trade.clone(), "size", &[]);
}
let mut order: Value = self.safe_string_k(trade.clone(), "orderId", &[]);
let mut timestamp: Value = self.safe_integer_product2(trade.clone(), Value::Str("ts".into()), Value::Str("time".into()), Value::Float(0.000001), &[]);
let mut feeCurrency: Value = market.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null);
let mut feeRate: Value = self.safe_string_k(trade.clone(), "feeRate", &[]);
let mut feeCost: Value = self.safe_string_k(trade.clone(), "fee", &[]);
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));
m.insert("symbol".to_string(), symbol);
m.insert("id".to_string(), tradeId);
m.insert("order".to_string(), order);
m.insert("type".to_string(), type_var);
m.insert("takerOrMaker".to_string(), self.safe_string_k(trade, "liquidity", &[]));
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost);
m.insert("rate".to_string(), feeRate);
m.insert("currency".to_string(), feeCurrency);
m
}));
m
}), &[market]);
Value::Null
}
/*
* @method
* @name kucoin#watchBalance
* @description watch balance and get the amount of funds available for trading or funds locked in orders
* @see https://www.kucoin.com/docs-new/3470075w0 // spot balance
* @see https://www.kucoin.com/docs-new/3470092w0 // contract balance
* @see https://www.kucoin.com/docs-new/3470231w0 // uta balance
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.uta] set to true for the unified trading account (uta)
* @param {string} [params.type] *classic (non-uta) account only* 'spot' or 'swap' (default is 'spot')
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn watch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut uta: Value = self.is_uta_enabled(&[]).await;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchBalance".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut defaultType: Value = (if is_true(&uta) { Value::Str("unified".into()) } else { Value::Str("spot".into()) });
let mut type_var: Value = defaultType.clone();
if !is_true(&uta) {
defaultType = self.safe_string_k(self.options.clone(), "defaultType", &[defaultType.clone()]);
type_var = self.safe_string_k(params.clone(), "type", &[defaultType]);
}
params = self.omit(params.clone(), Value::Str("type".into()), &[]);
let mut accountsByType: Value = self.safe_dict_k(self.options.clone(), "accountsByType", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut uniformType: Value = self.safe_string(accountsByType, type_var.clone(), &[type_var.clone()]);
let mut isClassicFuturesMethod: Value = (Value::Bool(uniformType.as_str() == Some("contract")));
let mut subscriptionHash: Value = (if matches!(&isClassicFuturesMethod, Value::Bool(true)) { Value::Str("/contractAccount/wallet".into()) } else { Value::Str("/account/balance".into()) });
let mut url: Value = Value::Null;
if is_true(&uta) {
url = self.get_uta_url().await;
subscriptionHash = uniformType.clone();
} else {
url = self.negotiate(Value::Bool(true), &[isClassicFuturesMethod]).await;
}
let mut client: Value = self.client(&[url.clone()]);
self.set_balance_cache(client.clone(), uniformType.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, "awaitBalanceSnapshot", &[Value::Bool(true)]);
if (fetchBalanceSnapshot.as_bool() == Some(true)) && (awaitBalanceSnapshot.as_bool() == Some(true)) {
crate::exchange_stubs::ws_await_flight(&client.future(&[Value::Str(format!("{}{}", uniformType, Value::Str(":fetchBalanceSnapshot".into())).into())])).await;
}
let mut messageHash: Value = Value::Str(format!("{}{}", uniformType, Value::Str(":balance".into())).into());
if is_true(&uta) {
let mut extendedParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountType".to_string(), uniformType.clone());
m
});
let mut channel: Value = Value::Str("balance".into());
let __ws_arg_4 = self.extend(extendedParams, &[params.clone()]);
return self.subscribe_private_uta(Value::from(vec![messageHash.clone()]), subscriptionHash.clone(), channel, &[Value::Null, __ws_arg_4]).await;
} else {
let mut requestId: Value = to_string_val(&self.request_id());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("type".to_string(), Value::Str("subscribe".into()));
m.insert("topic".to_string(), subscriptionHash.clone());
m.insert("response".to_string(), Value::Bool(true));
m.insert("privateChannel".to_string(), Value::Bool(true));
m
});
let mut message: Value = self.extend(request, &[params]);
if !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &subscriptionHash)) {
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &requestId, subscriptionHash.clone());
}
return self.watch(url, messageHash, &[message, uniformType]).await;
}
Value::Null
}
pub fn set_balance_cache(&mut self, mut client: Value, mut type_var: Value) {
if (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &type_var)) && (in_op(&self.balance, &type_var)) {
return;
}
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchBalance", &[]);
let mut fetchBalanceSnapshot: Value = self.safe_bool_k(options, "fetchBalanceSnapshot", &[Value::Bool(false)]);
if (fetchBalanceSnapshot.as_bool() == Some(true)) {
let mut messageHash: Value = Value::Str(format!("{}{}", type_var, Value::Str(":fetchBalanceSnapshot".into())).into());
if !(in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
client.future(&[messageHash.clone()]);
self.spawn(&[Value::Str("load_balance_snapshot".into()).clone(), client.clone(), messageHash.clone(), type_var.clone()]);
}
} else {
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&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) -> Value {
let mut uta: Value = (Value::Bool(type_var.as_str() == Some("unified")));
let mut params: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var.clone());
m.insert("uta".to_string(), uta);
m
});
let mut response: Value = self.fetch_balance(&[params]).await;
let __ws_arg_5 = self.safe_dict(self.balance.clone(), type_var.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
{ let __be_tmp = self.extend(response, &[__ws_arg_5]); if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&type_var), __be_tmp); } }
// don't remove the future from the .futures cache
if (in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
let mut future: Value = get_value(&get_value(&client, &Value::Str("futures".into())), &messageHash);
future.resolve(&[]);
client.resolve(&[get_value(&self.balance, &type_var), Value::Str(format!("{}{}", type_var, Value::Str(":balance".into())).into())]);
}
Value::Null
}
pub fn handle_balance(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "id":"6217a451294b030001e3a26a",
// "type":"message",
// "topic":"/account/balance",
// "userId":"6217707c52f97f00012a67db",
// "channelType":"private",
// "subject":"account.balance",
// "data":{
// "accountId":"62177fe67810720001db2f18",
// "available":"89",
// "availableChange":"-30",
// "currency":"USDT",
// "hold":"0",
// "holdChange":"0",
// "relationContext":{
// },
// "relationEvent":"main.transfer",
// "relationEventId":"6217a451294b030001e3a26a",
// "time":"1645716561816",
// "total":"89"
// }
//
// futures
// {
// "id": "6375553193027a0001f6566f",
// "type": "message",
// "topic": "/contractAccount/wallet",
// "userId": "613a896885d8660006151f01",
// "channelType": "private",
// "subject": "availableBalance.change",
// "data": {
// "currency": "USDT",
// "holdBalance": "0.0000000000",
// "availableBalance": "14.0350281903",
// "timestamp": "1668633905657"
// }
// }
//
// {
// "topic": "/contractAccount/wallet",
// "type": "message",
// "subject": "walletBalance.change",
// "id": "699f586d4416a80001df3804",
// "userId": "64f99aced178640001306e6e",
// "channelType": "private",
// "data": {
// "crossPosMargin": "0",
// "isolatedOrderMargin": "0",
// "holdBalance": "0",
// "equity": "49.50050236",
// "version": "2874",
// "availableBalance": "28.67180236",
// "isolatedPosMargin": "20.7308",
// "maxWithdrawAmount": "28.67180236",
// "walletBalance": "49.40260236",
// "isolatedFundingFeeMargin": "0",
// "crossUnPnl": "0",
// "totalCrossMargin": "28.67180236",
// "currency": "USDT",
// "isolatedUnPnl": "0.0979",
// "availableMargin": "28.67180236",
// "crossOrderMargin": "0",
// "timestamp": "1772050541214"
// }
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut currencyId: Value = self.safe_string_k(data.clone(), "currency", &[]);
let mut relationEvent: Value = self.safe_string_k(data.clone(), "relationEvent", &[]);
let mut requestAccountType: Value = Value::Null;
if (relationEvent != Value::Null) {
let mut relationEventParts: Value = split(&relationEvent, &Value::Str(".".into()));
requestAccountType = self.safe_string(relationEventParts, Value::Int(0), &[]);
}
let mut topic: Option<String> = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (topic.as_deref() == Some("/contractAccount/wallet")) {
requestAccountType = Value::Str("contract".into());
}
let mut accountsByType: Value = self.safe_dict_k(self.options.clone(), "accountsByType", &[]);
let mut uniformType: Value = self.safe_string(accountsByType, requestAccountType, &[Value::Str("trade".into())]);
if !(in_op(&self.balance, &uniformType)) {
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&uniformType), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})); }
}
add_element_to_object(get_value_mut(&mut self.balance, &uniformType), &Value::Str("info".into()), data.clone());
let mut timestamp: Value = self.safe_integer2(data.clone(), Value::Str("time".into()), Value::Str("timestamp".into()), &[]);
add_element_to_object(get_value_mut(&mut self.balance, &uniformType), &Value::Str("timestamp".into()), timestamp.clone());
{ let __be_tmp = self.iso8601(timestamp); add_element_to_object(get_value_mut(&mut self.balance, &uniformType), &Value::Str("datetime".into()), __be_tmp); };
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut account: Value = self.account();
let mut used: Value = self.safe_string2(data.clone(), Value::Str("hold".into()), Value::Str("holdBalance".into()), &[]);
let mut isolatedPosMargin: Value = self.omit_zero(self.safe_string_k(data.clone(), "isolatedPosMargin", &[]));
if (isolatedPosMargin != Value::Null) {
used = crate::precise::Precise::stringAdd(&used, &isolatedPosMargin);
}
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string2(data.clone(), Value::Str("available".into()), Value::Str("availableBalance".into()), &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), used); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string_k(data, "total", &[])); }
if (uniformType != Value::Null) && (code != Value::Null) {
add_element_to_object(get_value_mut(&mut self.balance, &uniformType), &code, account);
}
{ let __be_tmp = self.safe_balance(get_value(&self.balance, &uniformType)); if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&uniformType), __be_tmp); } }
let mut messageHash: Value = Value::Str(format!("{}{}", uniformType, Value::Str(":balance".into())).into());
client.resolve(&[get_value(&self.balance, &uniformType), messageHash]);
}
pub fn handle_uta_balance(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "T": "balance.UNIFIED",
// "P": "1774982552507478380",
// "d": {
// "c": "USDT",
// "e": "100.0030439507",
// "b": "100.0030439507",
// "a": "89.9930439507",
// "h": "10.0100000000",
// "U": "1774982552505000000",
// "l": "0.0000000000"
// }
// }
//
let mut type_var: Value = Value::Str("unified".into());
let mut data: Value = (match message.get("d") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut currencyId: Value = self.safe_string_k(data.clone(), "c", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
if !(in_op(&self.balance, &type_var)) {
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&type_var), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})); }
}
add_element_to_object(get_value_mut(&mut self.balance, &type_var), &Value::Str("info".into()), data.clone());
let mut timestamp: Value = self.safe_integer_product_k(data.clone(), "U", Value::Float(0.000001), &[]);
add_element_to_object(get_value_mut(&mut self.balance, &type_var), &Value::Str("timestamp".into()), timestamp.clone());
{ let __be_tmp = self.iso8601(timestamp); add_element_to_object(get_value_mut(&mut self.balance, &type_var), &Value::Str("datetime".into()), __be_tmp); };
let mut account: Value = self.account();
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_k(data.clone(), "a", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_string_k(data.clone(), "h", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string_k(data, "b", &[])); }
if (type_var != Value::Null) && (code != Value::Null) {
add_element_to_object(get_value_mut(&mut self.balance, &type_var), &code, account);
}
{ let __be_tmp = self.safe_balance(get_value(&self.balance, &type_var)); if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&type_var), __be_tmp); } }
let mut messageHash: Value = Value::Str(format!("{}{}", type_var, Value::Str(":balance".into())).into());
client.resolve(&[get_value(&self.balance, &type_var), messageHash]);
}
/*
* @method
* @name kucoin#watchPosition
* @description watch open positions for a specific symbol
* @see https://www.kucoin.com/docs-new/3470093w0
* @param {string|undefined} symbol unified market symbol
* @param {object} params extra parameters specific to the exchange API endpoint
* @returns {object} a [position structure]{@link https://docs.ccxt.com/en/latest/manual.html#position-structure}
*/
pub async fn watch_position(&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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchPosition() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut url: Value = self.negotiate(Value::Bool(true), &[]).await;
let mut market: Value = self.market(symbol.clone());
let mut topic: Value = Value::Str(format!("{}{}", Value::Str("/contract/position:".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("privateChannel".to_string(), Value::Bool(true));
m
});
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("position:".into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into());
let mut client: Value = self.client(&[url.clone()]);
self.set_position_cache(client.clone(), symbol.clone());
let mut fetchPositionSnapshot: Value = self.handle_option(Value::Str("watchPosition".into()), Value::Str("fetchPositionSnapshot".into()), &[Value::Bool(true)]);
let mut awaitPositionSnapshot: Value = self.handle_option(Value::Str("watchPosition".into()), Value::Str("awaitPositionSnapshot".into()), &[Value::Bool(true)]);
let mut currentPosition: Value = self.get_current_position(symbol.clone());
if (is_equal(&fetchPositionSnapshot, &Value::Bool(true))) && (is_equal(&awaitPositionSnapshot, &Value::Bool(true))) && (currentPosition == Value::Null) {
let mut snapshot: Value = crate::exchange_stubs::ws_await_flight(&client.future(&[Value::Str(format!("{}{}", Value::Str("fetchPositionSnapshot:".into()), symbol).into())])).await;
return snapshot;
}
let __ws_arg_6 = self.extend(request, &[params]);
return self.subscribe(url, messageHash, topic, &[__ws_arg_6]).await;
Value::Null
}
/*
* @method
* @name kucoin#watchPositions
* @see https://www.kucoin.com/docs-new/3470233w0
* @description watch all open positions
* @param {string[]} [symbols] list of unified market symbols
* @param {int} [since] the earliest time in ms to fetch positions for
* @param {int} [limit] the maximum number of positions to retrieve
* @param {object} params extra parameters specific to the exchange API endpoint
* @param {boolean} [params.uta] set to true for the unified trading account (uta)
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/en/latest/manual.html#position-structure}
*/
pub async fn watch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut uta: Value = self.is_uta_enabled(&[]).await;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchPositions".into()), Value::Str("uta".into()), &[uta.clone()]); uta = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut tradeType: Value = (if is_true(&uta) { Value::Str("UNIFIED".into()) } else { Value::Str("TRADE".into()) });
let mut messageHash: Value = Value::Str("positions".into());
let mut messageHashes: Value = Value::from(vec![]);
symbols = self.market_symbols(&[symbols.clone()]);
if (symbols == Value::Null) {
append_to_array(&mut messageHashes, messageHash.clone());
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_451: bool = true;
while { if !__for_first_451 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_451 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
append_to_array(&mut messageHashes, Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str(":".into())).into()), symbol).into()));
}
}
}
let mut url: Value = self.get_uta_url().await;
let mut client: Value = self.client(&[url]);
self.set_positions_cache(client.clone(), uta);
let mut fetchPositionSnapshot: Value = self.handle_option(Value::Str("watchPositions".into()), Value::Str("fetchPositionsSnapshot".into()), &[Value::Bool(true)]);
let mut awaitPositionSnapshot: Value = self.handle_option(Value::Str("watchPositions".into()), Value::Str("awaitPositionsSnapshot".into()), &[Value::Bool(true)]);
let mut cache: Value = self.positions.clone();
if (is_equal(&fetchPositionSnapshot, &Value::Bool(true))) && (is_equal(&awaitPositionSnapshot, &Value::Bool(true))) && (cache == Value::Null) {
let mut snapshot: Value = crate::exchange_stubs::ws_await_flight(&client.future(&[Value::Str("fetchPositionsSnapshot".into())])).await;
return self.filter_by_symbols_since_limit(snapshot, &[symbols.clone(), since.clone(), limit.clone(), Value::Bool(true)]);
}
let mut channel: Value = Value::Str("positionAll".into());
params = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tradeType".to_string(), tradeType);
m
})]);
let mut newPositions: Value = self.subscribe_private_uta(messageHashes, channel.clone(), channel.clone(), &[Value::Null, params]).await;
if is_true(&self.newUpdates) {
return newPositions;
}
return self.filter_by_symbols_since_limit(cache, &[symbols, since, limit, Value::Bool(true)]);
Value::Null
}
pub fn get_current_position(&self, mut symbol: Value) -> Value {
if (self.positions.clone() == Value::Null) {
return Value::Null;
}
let mut cache: Value = self.positions.hashmap();
let mut symbolCache: Value = self.safe_dict(cache, symbol, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut values: Value = object_values(&symbolCache);
return self.safe_dict(values, Value::Int(0), &[]);
Value::Null
}
pub fn set_positions_cache(&mut self, mut client: Value, mut uta: Value) {
if !(self.is_empty(self.positions.clone()).as_bool() == Some(true)) {
return;
}
let mut fetchPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".into()), Value::Str("fetchPositionsSnapshot".into()), &[Value::Bool(false)]);
if is_equal(&fetchPositionsSnapshot, &Value::Bool(true)) {
let mut messageHash: Value = Value::Str("fetchPositionsSnapshot".into());
if !(in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
client.future(&[messageHash.clone()]);
self.spawn(&[Value::Str("load_positions_snapshot".into()).clone(), client.clone(), messageHash.clone(), uta]);
}
} else {
self.positions = ArrayCacheBySymbolById::new(Value::Null);
}
}
pub async fn load_positions_snapshot(&mut self, mut client: Value, mut messageHash: Value, mut uta: Value) -> Value {
let mut positions: Value = self.fetch_positions(&[Value::Null, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("uta".to_string(), uta);
m
})]).await;
self.positions = ArrayCacheBySymbolById::new(Value::Null);
let mut cache: Value = self.positions.clone();
{
let mut i: Value = Value::Int(0);
let mut __for_first_452: bool = true;
while { if !__for_first_452 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_452 = false; i.as_f64().unwrap_or(f64::NAN) < ((positions.len() as i64) as f64) } {
let mut position: Value = positions.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut contracts: Value = self.safe_number_k(position.clone(), "contracts", &[Value::Int(0)]);
if contracts.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
cache.append(position);
}
}
}
// don't remove the future from the .futures cache
if (in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
let mut future: Value = get_value(&get_value(&client, &Value::Str("futures".into())), &messageHash);
future.resolve(&[cache.clone()]);
client.resolve(&[cache, Value::Str("positions".into())]);
}
Value::Null
}
pub fn set_position_cache(&mut self, mut client: Value, mut symbol: Value) {
let mut fetchPositionSnapshot: Value = self.handle_option(Value::Str("watchPosition".into()), Value::Str("fetchPositionSnapshot".into()), &[Value::Bool(false)]);
if is_equal(&fetchPositionSnapshot, &Value::Bool(true)) {
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("fetchPositionSnapshot:".into()), symbol).into());
if !(in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
client.future(&[messageHash.clone()]);
self.spawn(&[Value::Str("load_position_snapshot".into()).clone(), client.clone(), messageHash.clone(), symbol]);
}
}
}
pub async fn load_position_snapshot(&mut self, mut client: Value, mut messageHash: Value, mut symbol: Value) -> Value {
let mut position: Value = self.fetch_position(symbol.clone(), &[]).await;
self.positions = ArrayCacheBySymbolById::new(Value::Null);
let mut cache: Value = self.positions.clone();
cache.append(position.clone());
// don't remove the future from the .futures cache
if (in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
let mut future: Value = get_value(&get_value(&client, &Value::Str("futures".into())), &messageHash);
future.resolve(&[cache]);
client.resolve(&[position, Value::Str(format!("{}{}", Value::Str("position:".into()), symbol).into())]);
}
Value::Null
}
pub fn handle_position(&self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// Position Changes Caused Operations
// {
// "type": "message",
// "userId": "5c32d69203aa676ce4b543c7", // Deprecated, will detele later
// "channelType": "private",
// "topic": "/contract/position:XBTUSDM",
// "subject": "position.change",
// "data": {
// "realisedGrossPnl": 0E-8, //Accumulated realised profit and loss
// "symbol": "XBTUSDM", //Symbol
// "crossMode": false, //Cross mode or not
// "liquidationPrice": 1000000.0, //Liquidation price
// "posLoss": 0E-8, //Manually added margin amount
// "avgEntryPrice": 7508.22, //Average entry price
// "unrealisedPnl": -0.00014735, //Unrealised profit and loss
// "markPrice": 7947.83, //Mark price
// "posMargin": 0.00266779, //Position margin
// "autoDeposit": false, //Auto deposit margin or not
// "riskLimit": 100000, //Risk limit
// "unrealisedCost": 0.00266375, //Unrealised value
// "posComm": 0.00000392, //Bankruptcy cost
// "posMaint": 0.00001724, //Maintenance margin
// "posCost": 0.00266375, //Position value
// "maintMarginReq": 0.005, //Maintenance margin rate
// "bankruptPrice": 1000000.0, //Bankruptcy price
// "realisedCost": 0.00000271, //Currently accumulated realised position value
// "markValue": 0.00251640, //Mark value
// "posInit": 0.00266375, //Position margin
// "realisedPnl": -0.00000253, //Realised profit and losts
// "maintMargin": 0.00252044, //Position margin
// "realLeverage": 1.06, //Leverage of the order
// "changeReason": "positionChange", //changeReason:marginChange、positionChange、liquidation、autoAppendMarginStatusChange、adl
// "currentCost": 0.00266375, //Current position value
// "openingTimestamp": 1558433191000, //Open time
// "currentQty": -20, //Current position
// "delevPercentage": 0.52, //ADL ranking percentile
// "currentComm": 0.00000271, //Current commission
// "realisedGrossCost": 0E-8, //Accumulated reliased gross profit value
// "isOpen": true, //Opened position or not
// "posCross": 1.2E-7, //Manually added margin
// "currentTimestamp": 1558506060394, //Current timestamp
// "unrealisedRoePcnt": -0.0553, //Rate of return on investment
// "unrealisedPnlPcnt": -0.0553, //Position profit and loss ratio
// "settleCurrency": "XBT" //Currency used to clear and settle the trades
// }
// }
// Position Changes Caused by Mark Price
// {
// "userId": "5cd3f1a7b7ebc19ae9558591", // Deprecated, will detele later
// "topic": "/contract/position:XBTUSDM",
// "subject": "position.change",
// "data": {
// "markPrice": 7947.83, //Mark price
// "markValue": 0.00251640, //Mark value
// "maintMargin": 0.00252044, //Position margin
// "realLeverage": 10.06, //Leverage of the order
// "unrealisedPnl": -0.00014735, //Unrealised profit and lost
// "unrealisedRoePcnt": -0.0553, //Rate of return on investment
// "unrealisedPnlPcnt": -0.0553, //Position profit and loss ratio
// "delevPercentage": 0.52, //ADL ranking percentile
// "currentTimestamp": 1558087175068, //Current timestamp
// "settleCurrency": "XBT" //Currency used to clear and settle the trades
// }
// }
// Funding Settlement
// {
// "userId": "xbc453tg732eba53a88ggyt8c", // Deprecated, will detele later
// "topic": "/contract/position:XBTUSDM",
// "subject": "position.settlement",
// "data": {
// "fundingTime": 1551770400000, //Funding time
// "qty": 100, //Position siz
// "markPrice": 3610.85, //Settlement price
// "fundingRate": -0.002966, //Funding rate
// "fundingFee": -296, //Funding fees
// "ts": 1547697294838004923, //Current time (nanosecond)
// "settleCurrency": "XBT" //Currency used to clear and settle the trades
// }
// }
// Adjustmet result of risk limit level
// {
// "userId": "xbc453tg732eba53a88ggyt8c",
// "topic": "/contract/position:ADAUSDTM",
// "subject": "position.adjustRiskLimit",
// "data": {
// "success": true, // Successful or not
// "riskLimitLevel": 1, // Current risk limit level
// "msg": "" // Failure reason
// }
// }
//
let mut topic: Value = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
let mut parts: Value = split(&topic, &Value::Str(":".into()));
let mut marketId: Value = self.safe_string(parts, Value::Int(1), &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[Value::Null, Value::Str("".into())]);
let mut cache: Value = self.positions.clone();
let mut currentPosition: Value = self.get_current_position(symbol.clone());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("position:".into()), symbol).into());
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut newPosition: Value = self.parse_position(data, &[]);
let mut keys: Value = object_keys(&newPosition);
{
let mut i: Value = Value::Int(0);
let mut __for_first_453: bool = true;
while { if !__for_first_453 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_453 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut key: Value = keys.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if (newPosition.as_map().and_then(|__m| key.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null) == Value::Null) {
remove(&mut newPosition, &key);
}
}
}
let mut position: Value = self.extend(currentPosition, &[newPosition]);
cache.append(position.clone());
client.resolve(&[position, messageHash]);
}
pub fn handle_uta_position(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "T": "positionAll.UNIFIED",
// "P": "1774805155993190995",
// "d": {
// "pi": "30000000000084845",
// "s": "DOGEUSDTM",
// "mM": "CROSS",
// "q": "3",
// "eP": "0.09038666666666666666",
// "pV": "27.021",
// "mP": "0.09007",
// "lP": "0.00001",
// "bP": "0.00001",
// "l": "4.5",
// "uPL": "-0.095",
// "rPL": "-0.01473705",
// "iM": "6.0046666666666666666",
// "mmr": "0.007",
// "mtM": "0.189147",
// "U": "1774805155988000000",
// "O": 1774793727585000000
// }
// }
//
if (self.positions.clone() == Value::Null) {
self.positions = ArrayCacheBySymbolById::new(Value::Null);
}
let mut data: Value = (match message.get("d") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[]);
let mut cache: Value = self.positions.clone();
let mut currentPosition: Value = self.get_current_position(symbol.clone());
let mut newPosition: Value = self.parse_ws_uta_position(data, &[]);
let mut keys: Value = object_keys(&newPosition);
{
let mut i: Value = Value::Int(0);
let mut __for_first_454: bool = true;
while { if !__for_first_454 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_454 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut key: Value = keys.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if (newPosition.as_map().and_then(|__m| key.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null) == Value::Null) {
remove(&mut newPosition, &key);
}
}
}
let mut position: Value = self.extend(currentPosition, &[newPosition]);
cache.append(position);
let mut messageHash: Value = Value::Str("positions".into());
let mut symbolMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str(":".into())).into()), symbol).into());
client.resolve(&[self.positions.clone(), messageHash]);
client.resolve(&[self.positions.clone(), symbolMessageHash]);
}
pub fn parse_ws_uta_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "pi": "30000000000084845",
// "s": "DOGEUSDTM",
// "mM": "CROSS",
// "q": "3",
// "eP": "0.09038666666666666666",
// "pV": "27.021",
// "mP": "0.09007",
// "lP": "0.00001",
// "bP": "0.00001",
// "l": "4.5",
// "uPL": "-0.095",
// "rPL": "-0.01473705",
// "iM": "6.0046666666666666666",
// "mmr": "0.007",
// "mtM": "0.189147",
// "U": "1774805155988000000",
// "O": 1774793727585000000
// }
//
let mut marketId: Value = self.safe_string_k(position.clone(), "s", &[]);
market = self.safe_market(&[marketId, market.clone()]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = self.safe_integer_product_k(position.clone(), "O", Value::Float(0.000001), &[]);
let mut amountString: Value = self.safe_string_k(position.clone(), "q", &[]);
let mut size: Value = crate::precise::Precise::stringAbs(&amountString);
let mut side: Value = (if is_true(&crate::precise::Precise::stringGt(&amountString, &Value::Str("0".into()))) { Value::Str("long".into()) } else { Value::Str("short".into()) });
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), self.safe_string_k(position.clone(), "pi", &[]));
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastUpdateTimestamp".to_string(), self.safe_integer_product_k(position.clone(), "U", Value::Float(0.000001), &[]));
m.insert("initialMargin".to_string(), self.safe_number_k(position.clone(), "iM", &[]));
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), self.safe_number_k(position.clone(), "mtM", &[]));
m.insert("maintenanceMarginPercentage".to_string(), self.safe_number_k(position.clone(), "mmr", &[]));
m.insert("entryPrice".to_string(), self.safe_number_k(position.clone(), "eP", &[]));
m.insert("notional".to_string(), self.safe_number_k(position.clone(), "pV", &[]));
m.insert("leverage".to_string(), self.safe_number_k(position.clone(), "l", &[]));
m.insert("unrealizedPnl".to_string(), self.safe_number_k(position.clone(), "uPL", &[]));
m.insert("contracts".to_string(), self.parse_number(size, &[]));
m.insert("contractSize".to_string(), self.safe_number_k(market, "contractSize", &[]));
m.insert("realizedPnl".to_string(), self.safe_number_k(position.clone(), "rPL", &[]));
m.insert("marginRatio".to_string(), Value::Null);
m.insert("liquidationPrice".to_string(), self.safe_number_k(position.clone(), "lP", &[]));
m.insert("markPrice".to_string(), self.safe_number_k(position.clone(), "mP", &[]));
m.insert("lastPrice".to_string(), Value::Null);
m.insert("collateral".to_string(), Value::Null);
m.insert("marginMode".to_string(), self.safe_string_lower_k(position, "mM", &[]));
m.insert("side".to_string(), side);
m.insert("percentage".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
/*
* @method
* @name kucoin#watchFundingRate
* @description watch the current funding rate
* @see https://www.kucoin.com/docs-new/3470270w0
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn watch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbol = self.safe_symbol(symbol.clone(), &[]);
let mut channel: Value = Value::Str("funding-fee".into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("fundingRate:".into()), symbol).into());
return self.subscribe_public_uta(messageHash, channel, symbol, &[params]).await;
Value::Null
}
/*
* @method
* @name kucoin#unWatchFundingRate
* @description unWatches the current funding rate for a symbol
* @see https://www.kucoin.com/docs-new/3470270w0
* @param {string} symbol unified symbol of the market
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn un_watch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbol = self.safe_symbol(symbol.clone(), &[]);
let mut channel: Value = Value::Str("funding-fee".into());
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str("fundingRate:".into()), symbol).into());
let mut unSubMessageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbols".to_string(), Value::from(vec![symbol.clone()]));
m.insert("topic".to_string(), Value::Str("fundingRate".into()));
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("subMessageHashes".to_string(), Value::from(vec![subMessageHash]));
m.insert("messageHashes".to_string(), Value::from(vec![unSubMessageHash.clone()]));
m
});
return self.subscribe_public_uta(unSubMessageHash, channel, symbol, &[params, subscription]).await;
Value::Null
}
pub fn handle_uta_funding_rate(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "T": "funding-fee",
// "P": "1782831961172694254",
// "d": {
// "s": "ETHUSDTM",
// "fr": "0.000035",
// "ft": 1782806400000,
// "nt": 1782835200000,
// "gl": 28800000,
// "fc": "0.00375",
// "ff": "-0.00375"
// }
// }
//
let mut data: Value = (match message.get("d") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut fundingRate: Value = self.parse_ws_funding_rate(data, &[]);
let mut symbol: Value = fundingRate.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut self.fundingRates { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), fundingRate.clone()); }
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("fundingRate:".into()), symbol).into());
client.resolve(&[fundingRate, messageHash]);
}
pub fn parse_ws_funding_rate(&self, mut data: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "s": "ETHUSDTM",
// "fr": "0.000035",
// "ft": 1782806400000,
// "nt": 1782835200000,
// "gl": 28800000,
// "fc": "0.00375",
// "ff": "-0.00375"
// }
//
let mut fundingTimestamp: Value = self.safe_integer_k(data.clone(), "ft", &[]);
let mut nextFundingTimestamp: Value = self.safe_integer_k(data.clone(), "nt", &[]);
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
let mut granularity: Value = self.safe_string_k(data.clone(), "gl", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market, Value::Null, Value::Str("contract".into())]));
m.insert("markPrice".to_string(), Value::Null);
m.insert("indexPrice".to_string(), Value::Null);
m.insert("interestRate".to_string(), Value::Null);
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("fundingRate".to_string(), self.safe_number_k(data, "fr", &[]));
m.insert("fundingTimestamp".to_string(), fundingTimestamp.clone());
m.insert("fundingDatetime".to_string(), self.iso8601(fundingTimestamp));
m.insert("nextFundingRate".to_string(), Value::Null);
m.insert("nextFundingTimestamp".to_string(), nextFundingTimestamp.clone());
m.insert("nextFundingDatetime".to_string(), self.iso8601(nextFundingTimestamp));
m.insert("previousFundingRate".to_string(), Value::Null);
m.insert("previousFundingTimestamp".to_string(), Value::Null);
m.insert("previousFundingDatetime".to_string(), Value::Null);
m.insert("interval".to_string(), self.parent.parse_funding_interval(granularity).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m
});
Value::Null
}
/*
* @method
* @name kucoin#watchMarkPrice
* @description watches a mark price for a specific market
* @see https://www.kucoin.com/docs-new/3470272w0
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbol = self.safe_symbol(symbol.clone(), &[]);
let mut channel: Value = Value::Str("mark-price".into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("uta:ticker:".into()), symbol).into());
return self.subscribe_public_uta(messageHash, channel, symbol, &[params]).await;
Value::Null
}
/*
* @method
* @name kucoin#unWatchMarkPrice
* @description unWatches a mark price for a specific market
* @see https://www.kucoin.com/docs-new/3470272w0
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn un_watch_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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbol = self.safe_symbol(symbol.clone(), &[]);
let mut channel: Value = Value::Str("mark-price".into());
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str("uta:ticker:".into()), symbol).into());
let mut unSubMessageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbols".to_string(), Value::from(vec![symbol.clone()]));
m.insert("topic".to_string(), Value::Str("ticker".into()));
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("subMessageHashes".to_string(), Value::from(vec![subMessageHash]));
m.insert("messageHashes".to_string(), Value::from(vec![unSubMessageHash.clone()]));
m
});
return self.subscribe_public_uta(unSubMessageHash, channel, symbol, &[params, subscription]).await;
Value::Null
}
pub fn handle_subject(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "type":"message",
// "topic":"/market/level2:BTC-USDT",
// "subject":"trade.l2update",
// "data":{
// "sequenceStart":1545896669105,
// "sequenceEnd":1545896669106,
// "symbol":"BTC-USDT",
// "changes": {
// "asks": [["6","1","1545896669105"]], // price, size, sequence
// "bids": [["4","1","1545896669106"]]
// }
// }
// }
//
let mut topic: Option<String> = (match __pro_message.get("topic").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (topic.as_deref() == Some("/market/ticker:all")) {
self.handle_ticker(client.clone(), message.clone());
return;
}
let mut subject: Value = self.safe_string2(message.clone(), Value::Str("subject".into()), Value::Str("T".into()), &[]);
let mut methods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("level1".to_string(), Value::Str("handle_bid_ask".into()).clone());
m.insert("level2".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("trade.l2update".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("trade.ticker".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("trade.snapshot".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("trade.l3match".to_string(), Value::Str("handle_trade".into()).clone());
m.insert("trade.candles.update".to_string(), Value::Str("handle_ohlcv".into()).clone());
m.insert("account.balance".to_string(), Value::Str("handle_balance".into()).clone());
m.insert("orderChange".to_string(), Value::Str("handle_order".into()).clone());
m.insert("stopOrder".to_string(), Value::Str("handle_order".into()).clone());
m.insert("/spot/tradeFills".to_string(), Value::Str("handle_my_trade".into()).clone());
m.insert("ticker".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("tickerV2".to_string(), Value::Str("handle_bid_ask".into()).clone());
m.insert("candle.stick".to_string(), Value::Str("handle_ohlcv".into()).clone());
m.insert("match".to_string(), Value::Str("handle_trade".into()).clone());
m.insert("orderUpdated".to_string(), Value::Str("handle_order".into()).clone());
m.insert("symbolOrderChange".to_string(), Value::Str("handle_order".into()).clone());
m.insert("availableBalance.change".to_string(), Value::Str("handle_balance".into()).clone());
m.insert("walletBalance.change".to_string(), Value::Str("handle_balance".into()).clone());
m.insert("position.change".to_string(), Value::Str("handle_position".into()).clone());
m.insert("position.settlement".to_string(), Value::Str("handle_position".into()).clone());
m.insert("position.adjustRiskLimit".to_string(), Value::Str("handle_position".into()).clone());
m.insert("ticker.SPOT".to_string(), Value::Str("handle_uta_ticker".into()).clone());
m.insert("ticker.FUTURES".to_string(), Value::Str("handle_uta_ticker".into()).clone());
m.insert("trade.SPOT".to_string(), Value::Str("handle_uta_trade".into()).clone());
m.insert("trade.FUTURES".to_string(), Value::Str("handle_uta_trade".into()).clone());
m.insert("kline.SPOT".to_string(), Value::Str("handle_uta_ohlcv".into()).clone());
m.insert("kline.FUTURES".to_string(), Value::Str("handle_uta_ohlcv".into()).clone());
m.insert("obu.SPOT".to_string(), Value::Str("handle_uta_order_book".into()).clone());
m.insert("obu.FUTURES".to_string(), Value::Str("handle_uta_order_book".into()).clone());
m.insert("order.UNIFIED".to_string(), Value::Str("handle_uta_order".into()).clone());
m.insert("order.SPOT".to_string(), Value::Str("handle_uta_order".into()).clone());
m.insert("order.FUTURES".to_string(), Value::Str("handle_uta_order".into()).clone());
m.insert("order.CROSS".to_string(), Value::Str("handle_uta_order".into()).clone());
m.insert("order.ISOLATED".to_string(), Value::Str("handle_uta_order".into()).clone());
m.insert("orderAll.UNIFIED".to_string(), Value::Str("handle_uta_order".into()).clone());
m.insert("orderAll.SPOT".to_string(), Value::Str("handle_uta_order".into()).clone());
m.insert("orderAll.FUTURES".to_string(), Value::Str("handle_uta_order".into()).clone());
m.insert("orderAll.CROSS".to_string(), Value::Str("handle_uta_order".into()).clone());
m.insert("orderAll.ISOLATED".to_string(), Value::Str("handle_uta_order".into()).clone());
m.insert("execution.UNIFIED".to_string(), Value::Str("handle_uta_my_trade".into()).clone());
m.insert("execution.SPOT".to_string(), Value::Str("handle_uta_my_trade".into()).clone());
m.insert("execution.FUTURES".to_string(), Value::Str("handle_uta_my_trade".into()).clone());
m.insert("execution.CROSS".to_string(), Value::Str("handle_uta_my_trade".into()).clone());
m.insert("execution.ISOLATED".to_string(), Value::Str("handle_uta_my_trade".into()).clone());
m.insert("execution.lite.UNIFIED".to_string(), Value::Str("handle_uta_my_trade".into()).clone());
m.insert("execution.lite.SPOT".to_string(), Value::Str("handle_uta_my_trade".into()).clone());
m.insert("execution.lite.FUTURES".to_string(), Value::Str("handle_uta_my_trade".into()).clone());
m.insert("execution.lite.CROSS".to_string(), Value::Str("handle_uta_my_trade".into()).clone());
m.insert("execution.lite.ISOLATED".to_string(), Value::Str("handle_uta_my_trade".into()).clone());
m.insert("position.UNIFIED".to_string(), Value::Str("handle_uta_position".into()).clone());
m.insert("position.FUTURES".to_string(), Value::Str("handle_uta_position".into()).clone());
m.insert("positionAll.UNIFIED".to_string(), Value::Str("handle_uta_position".into()).clone());
m.insert("positionAll.FUTURES".to_string(), Value::Str("handle_uta_position".into()).clone());
m.insert("balance.UNIFIED".to_string(), Value::Str("handle_uta_balance".into()).clone());
m.insert("funding-fee".to_string(), Value::Str("handle_uta_funding_rate".into()).clone());
m.insert("mark-price".to_string(), Value::Str("handle_uta_ticker".into()).clone());
m
});
let mut method: Value = self.safe_value(methods, subject, &[]);
if (method != Value::Null) {
self.dispatch_ws_handler(&method, &[client, message]);
}
}
pub fn ping(&mut self, mut client: Value) -> Value {
// kucoin does not support built-in ws protocol-level ping-pong
// instead it requires a custom json-based text ping-pong
// https://docs.kucoin.com/#ping
let mut id: Value = to_string_val(&self.request_id());
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("type".to_string(), Value::Str("ping".into()));
m
});
Value::Null
}
pub fn handle_pong(&self, mut client: Value, mut message: Value) {
crate::set_value(&mut client, &Value::Str("lastPong".into()), self.milliseconds());
}
pub fn handle_error_message(&self, mut client: Value, mut message: Value) -> Value {
//
// {
// "id": "1",
// "type": "error",
// "code": 415,
// "data": "type is not supported"
// }
//
// uta
// {
// "id": "1",
// "result": false,
// "reason": "missing `symbol` for topic: Position"
// }
//
let mut data: Value = self.safe_string2(message.clone(), Value::Str("data".into()), Value::Str("reason".into()), &[Value::Str("".into())]);
if (data.as_str() == Some("token is expired")) {
let mut type_var: Value = Value::Str("public".into());
if Value::Int(get_value(&client, &Value::Str("url".into())).as_str().and_then(|__s| __s.find("connectId=private")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
type_var = Value::Str("private".into());
}
// Match the negotiation cache key; spot tokens can also contain "Futures".
if get_index_of(&get_value(&client, &Value::Str("url".into())), &Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("connectId=".into()), type_var).into()), Value::Str("Futures".into())).into())).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
type_var = Value::Str(format!("{}{}", type_var, Value::Str("Futures".into())).into());
}
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("urls".into())), &type_var, Value::Null);
}
self.handle_errors(Value::Int(1), Value::Str("".into()), client.as_map().and_then(|__m| __m.get("url")).cloned().unwrap_or(Value::Null), Value::Str("".into()), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), data, message, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return Value::Bool(false);
Value::Null
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
let mut type_var: Value = self.safe_string2(message.clone(), Value::Str("type".into()), Value::Str("message".into()), &[]);
let mut methods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("welcome".to_string(), Value::Str("handle_system_status".into()).clone());
m.insert("ack".to_string(), Value::Str("handle_subscription_status".into()).clone());
m.insert("message".to_string(), Value::Str("handle_subject".into()).clone());
m.insert("pong".to_string(), Value::Str("handle_pong".into()).clone());
m.insert("error".to_string(), Value::Str("handle_error_message".into()).clone());
m
});
let mut method: Value = self.safe_value(methods, type_var, &[]);
if (method != Value::Null) {
self.dispatch_ws_handler(&method, &[client.clone(), message.clone()]);
} else if (matches!(&message, Value::Dict(__d) if __d.contains_key("T"))) {
self.handle_subject(client.clone(), message.clone());
} else if (matches!(&message, Value::Dict(__d) if __d.contains_key("result"))) {
let mut result: Value = (match __pro_message.get("result").cloned() { Some(__v) if matches!(__v, Value::Bool(_)) => __v, _ => Value::Bool(true) });
if (result.as_bool() != Some(true)) {
self.handle_error_message(client.clone(), message.clone());
}
self.handle_subscription_status(client, message.clone());
}
}
pub fn get_message_hash(&self, mut elementName: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
// method from kucoinfutures
// elementName can be 'ticker', 'bidask', ...
if (symbol != Value::Null) {
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", elementName, Value::Str(":".into())).into()), symbol).into());
} else {
return Value::Str(format!("{}{}", elementName, Value::Str("s@all".into())).into());
}
Value::Null
}
}