// 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 GateCore {
pub parent: crate::exchanges::gate::GateCore,
}
impl GateCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::gate::GateCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = GateCore::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 GateCore {
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 GateCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"authenticate" => self.authenticate(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"cancel_all_orders_ws" => self.cancel_all_orders_ws(&args[..]).await,
"cancel_order_ws" => self.cancel_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_order_ws" => self.create_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_orders_ws" => self.create_orders_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"describe_data" => self.describe_data(),
"edit_order_ws" => self.edit_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"fetch_closed_orders_ws" => self.fetch_closed_orders_ws(&args[..]).await,
"fetch_open_orders_ws" => self.fetch_open_orders_ws(&args[..]).await,
"fetch_order_ws" => self.fetch_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders_by_status_ws" => self.fetch_orders_by_status_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_market_type_by_url" => self.get_market_type_by_url(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_type_by_market" => self.get_type_by_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_url_by_market" => self.get_url_by_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_url_by_market_type" => self.get_url_by_market_type(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"handle_error_message" => self.handle_error_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"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,
"parse_ws_liquidation" => self.parse_ws_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"request_id" => self.request_id(),
"request_private" => self.request_private(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"subscribe_private" => self.subscribe_private(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), &args[5.min(args.len())..]).await,
"subscribe_public" => self.subscribe_public(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"subscribe_public_multiple" => self.subscribe_public_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_watch_tickers_and_bids_asks" => self.subscribe_watch_tickers_and_bids_asks(&args[..]).await,
"un_subscribe_public_multiple" => self.un_subscribe_public_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.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), &args[7.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_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_my_liquidations" => self.watch_my_liquidations(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_my_liquidations_for_symbols" => self.watch_my_liquidations_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_my_trades" => self.watch_my_trades(&args[..]).await,
"watch_ohlcv" => self.watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_positions" => self.watch_positions(&args[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_tickers" => self.watch_tickers(&args[..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_trades_for_symbols" => self.watch_trades_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
// Go-style inheritance: an un-overridden method dispatches to the parent core.
_ => crate::exchange_generated::ExchangeBase::call_dynamic(&mut self.parent, method, args).await,
}
})
}
}
impl GateCore {
/// Synchronous WS handler dispatch — routes a handler-name string (from the
/// venue's handle_message dispatch table) to the real handler method.
#[allow(dead_code, unreachable_patterns, clippy::all)]
pub fn dispatch_ws_handler(&mut self, __name: &crate::Value, args: &[crate::Value]) -> crate::Value {
let __n = match __name { crate::Value::Str(s) => s.as_ref(), _ => return crate::Value::Null };
match __n {
"authenticate" => { crate::exchange_stubs::enqueue_spawn("authenticate", args.to_vec()); crate::Value::Null },
"cancel_all_orders_ws" => { crate::exchange_stubs::enqueue_spawn("cancel_all_orders_ws", args.to_vec()); crate::Value::Null },
"cancel_order_ws" => { crate::exchange_stubs::enqueue_spawn("cancel_order_ws", args.to_vec()); crate::Value::Null },
"create_order_ws" => { crate::exchange_stubs::enqueue_spawn("create_order_ws", args.to_vec()); crate::Value::Null },
"create_orders_ws" => { crate::exchange_stubs::enqueue_spawn("create_orders_ws", args.to_vec()); crate::Value::Null },
"describe_data" => self.describe_data(),
"edit_order_ws" => { crate::exchange_stubs::enqueue_spawn("edit_order_ws", args.to_vec()); crate::Value::Null },
"fetch_closed_orders_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_closed_orders_ws", args.to_vec()); crate::Value::Null },
"fetch_open_orders_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_open_orders_ws", args.to_vec()); crate::Value::Null },
"fetch_order_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_order_ws", args.to_vec()); crate::Value::Null },
"fetch_orders_by_status_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_orders_by_status_ws", 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_market_type_by_url" => self.get_market_type_by_url(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_type_by_market" => self.get_type_by_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_url_by_market" => self.get_url_by_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_url_by_market_type" => self.get_url_by_market_type(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"handle_authentication_message" => { self.handle_authentication_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_balance" => { self.handle_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_balance_subscription" => { self.handle_balance_subscription(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]); crate::Value::Null },
"handle_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_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_liquidation" => { self.handle_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_my_trades" => { self.handle_my_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_new_spot_order_book" => { self.handle_new_spot_order_book(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[2.min(args.len())..]); crate::Value::Null },
"handle_positions" => { self.handle_positions(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_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_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_ticker_and_bid_ask" => { self.handle_ticker_and_bid_ask(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_trades" => { self.handle_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_un_subscribe" => { self.handle_un_subscribe(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"load_positions_snapshot" => { crate::exchange_stubs::enqueue_spawn("load_positions_snapshot", args.to_vec()); crate::Value::Null },
"parse_ws_liquidation" => self.parse_ws_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"request_id" => self.request_id(),
"request_private" => { crate::exchange_stubs::enqueue_spawn("request_private", args.to_vec()); crate::Value::Null },
"set_positions_cache" => { self.set_positions_cache(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]); crate::Value::Null },
"subscribe_private" => { crate::exchange_stubs::enqueue_spawn("subscribe_private", args.to_vec()); crate::Value::Null },
"subscribe_public" => { crate::exchange_stubs::enqueue_spawn("subscribe_public", args.to_vec()); crate::Value::Null },
"subscribe_public_multiple" => { crate::exchange_stubs::enqueue_spawn("subscribe_public_multiple", args.to_vec()); crate::Value::Null },
"subscribe_watch_tickers_and_bids_asks" => { crate::exchange_stubs::enqueue_spawn("subscribe_watch_tickers_and_bids_asks", args.to_vec()); crate::Value::Null },
"un_subscribe_public_multiple" => { crate::exchange_stubs::enqueue_spawn("un_subscribe_public_multiple", 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_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_my_liquidations" => { crate::exchange_stubs::enqueue_spawn("watch_my_liquidations", args.to_vec()); crate::Value::Null },
"watch_my_liquidations_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_my_liquidations_for_symbols", args.to_vec()); crate::Value::Null },
"watch_my_trades" => { crate::exchange_stubs::enqueue_spawn("watch_my_trades", args.to_vec()); crate::Value::Null },
"watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("watch_ohlcv", args.to_vec()); crate::Value::Null },
"watch_order_book" => { crate::exchange_stubs::enqueue_spawn("watch_order_book", args.to_vec()); crate::Value::Null },
"watch_orders" => { crate::exchange_stubs::enqueue_spawn("watch_orders", args.to_vec()); crate::Value::Null },
"watch_positions" => { crate::exchange_stubs::enqueue_spawn("watch_positions", args.to_vec()); crate::Value::Null },
"watch_ticker" => { crate::exchange_stubs::enqueue_spawn("watch_ticker", args.to_vec()); crate::Value::Null },
"watch_tickers" => { crate::exchange_stubs::enqueue_spawn("watch_tickers", args.to_vec()); crate::Value::Null },
"watch_trades" => { crate::exchange_stubs::enqueue_spawn("watch_trades", args.to_vec()); crate::Value::Null },
"watch_trades_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_trades_for_symbols", args.to_vec()); crate::Value::Null },
_ => crate::Value::Null,
}
}
}
impl std::ops::Deref for GateCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for GateCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl GateCore {
pub fn describe(&self) -> Value {
let mut superDescribe: Value = self.parent.describe();
return self.deep_extend(superDescribe, &[self.describe_data()]);
Value::Null
}
pub fn describe_data(&self) -> Value {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Bool(true));
m.insert("cancelAllOrdersWs".to_string(), Value::Bool(true));
m.insert("cancelOrderWs".to_string(), Value::Bool(true));
m.insert("createMarketBuyOrderWithCostWs".to_string(), Value::Bool(true));
m.insert("createMarketOrderWs".to_string(), Value::Bool(true));
m.insert("createMarketOrderWithCostWs".to_string(), Value::Bool(false));
m.insert("createMarketSellOrderWithCostWs".to_string(), Value::Bool(false));
m.insert("createOrderWs".to_string(), Value::Bool(true));
m.insert("createOrdersWs".to_string(), Value::Bool(true));
m.insert("createPostOnlyOrderWs".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrderWs".to_string(), Value::Bool(true));
m.insert("createStopLimitOrderWs".to_string(), Value::Bool(true));
m.insert("createStopLossOrderWs".to_string(), Value::Bool(true));
m.insert("createStopMarketOrderWs".to_string(), Value::Bool(false));
m.insert("createStopOrderWs".to_string(), Value::Bool(true));
m.insert("createTakeProfitOrderWs".to_string(), Value::Bool(true));
m.insert("createTriggerOrderWs".to_string(), Value::Bool(true));
m.insert("editOrderWs".to_string(), Value::Bool(true));
m.insert("fetchOrderWs".to_string(), Value::Bool(true));
m.insert("fetchOrdersWs".to_string(), Value::Bool(false));
m.insert("fetchOpenOrdersWs".to_string(), Value::Bool(true));
m.insert("fetchClosedOrdersWs".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchBidsAsks".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m.insert("watchTradesForSymbols".to_string(), Value::Bool(true));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchOHLCV".to_string(), Value::Bool(true));
m.insert("watchBalance".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchLiquidations".to_string(), Value::Bool(false));
m.insert("watchLiquidationsForSymbols".to_string(), Value::Bool(false));
m.insert("watchMyLiquidations".to_string(), Value::Bool(true));
m.insert("watchMyLiquidationsForSymbols".to_string(), Value::Bool(true));
m.insert("watchPositions".to_string(), Value::Bool(true));
m.insert("unWatchTicker".to_string(), Value::Bool(false));
m.insert("unWatchTickers".to_string(), Value::Bool(false));
m.insert("unWatchOHLCV".to_string(), Value::Bool(false));
m.insert("unWatchOHLCVForSymbols".to_string(), Value::Bool(false));
m.insert("unWatchOrderBook".to_string(), Value::Bool(true));
m.insert("unWatchOrderBookForSymbols".to_string(), Value::Bool(false));
m.insert("unWatchTrades".to_string(), Value::Bool(true));
m.insert("unWatchTradesForSymbols".to_string(), Value::Bool(true));
m.insert("unWatchMyTrades".to_string(), Value::Bool(false));
m.insert("unWatchOrders".to_string(), Value::Bool(false));
m.insert("unWatchPositions".to_string(), Value::Bool(false));
m.insert("unWatchMarkPrices".to_string(), Value::Bool(false));
m.insert("unWatchMarkPrice".to_string(), Value::Bool(false));
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::Str("wss://ws.gate.io/v4".into()));
m.insert("spot".to_string(), Value::Str("wss://api.gateio.ws/ws/v4/".into()));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("usdt".to_string(), Value::Str("wss://fx-ws.gateio.ws/v4/ws/usdt".into()));
m.insert("btc".to_string(), Value::Str("wss://fx-ws.gateio.ws/v4/ws/btc".into()));
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("usdt".to_string(), Value::Str("wss://fx-ws.gateio.ws/v4/ws/delivery/usdt".into()));
m.insert("btc".to_string(), Value::Str("wss://fx-ws.gateio.ws/v4/ws/delivery/btc".into()));
m
}));
m.insert("option".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("usdt".to_string(), Value::Str("wss://op-ws.gateio.live/v4/ws/usdt".into()));
m.insert("btc".to_string(), Value::Str("wss://op-ws.gateio.live/v4/ws/btc".into()));
m
}));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("usdt".to_string(), Value::Str("wss://ws-testnet.gate.com/v4/ws/futures/usdt".into()));
m.insert("btc".to_string(), Value::Str("wss://fx-ws-testnet.gateio.ws/v4/ws/btc".into()));
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("usdt".to_string(), Value::Str("wss://fx-ws-testnet.gateio.ws/v4/ws/delivery/usdt".into()));
m.insert("btc".to_string(), Value::Str("wss://fx-ws-testnet.gateio.ws/v4/ws/delivery/btc".into()));
m
}));
m.insert("option".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("usdt".to_string(), Value::Str("wss://ws-testnet.gate.com/v4/ws/options/usdt".into()));
m.insert("btc".to_string(), Value::Str("wss://ws-testnet.gate.com/v4/ws/options/btc".into()));
m
}));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tradesLimit".to_string(), Value::Int(1000));
m.insert("OHLCVLimit".to_string(), Value::Int(1000));
m.insert("watchTradesSubscriptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("watchTickerSubscriptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("watchOrderBookSubscriptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("watchTicker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("tickers".into()));
m
}));
m.insert("watchOrderBook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("snapshotDelay".to_string(), Value::Int(10));
m.insert("snapshotMaxRetries".to_string(), Value::Int(3));
m.insert("checksum".to_string(), Value::Bool(true));
m
}));
m.insert("watchBalance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("settle".to_string(), Value::Str("usdt".into()));
m.insert("spot".to_string(), Value::Str("spot.balances".into()));
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("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("4".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("6".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("11".to_string(), Value::Str("AuthenticationError".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
m
}));
m
});
Value::Null
}
/*
* @method
* @name gate#createOrderWs
* @see https://www.gate.io/docs/developers/apiv4/ws/en/#order-place
* @see https://www.gate.io/docs/developers/futures/ws/en/#order-place
* @description Create an order on the exchange
* @param {string} symbol Unified CCXT market symbol
* @param {string} type 'limit' or 'market' *"market" is contract only*
* @param {string} side 'buy' or 'sell'
* @param {float} amount the amount of currency to trade
* @param {float} [price] *ignored in "market" orders* the price at which the order is to be fulfilled at in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {float} [params.stopPrice] The price at which a trigger order is triggered at
* @param {string} [params.timeInForce] "GTC", "IOC", or "PO"
* @param {float} [params.stopLossPrice] The price at which a stop loss order is triggered at
* @param {float} [params.takeProfitPrice] The price at which a take profit order is triggered at
* @param {string} [params.marginMode] 'cross' or 'isolated' - marginMode for margin trading if not provided this.options['defaultMarginMode'] is used
* @param {int} [params.iceberg] Amount to display for the iceberg order, Null or 0 for normal orders, Set to -1 to hide the order completely
* @param {string} [params.text] User defined information
* @param {string} [params.account] *spot and margin only* "spot", "margin" or "cross_margin"
* @param {bool} [params.auto_borrow] *margin only* Used in margin or cross margin trading to allow automatic loan of insufficient amount if balance is not enough
* @param {string} [params.settle] *contract only* Unified Currency Code for settle currency
* @param {bool} [params.reduceOnly] *contract only* Indicates if this order is to reduce the size of a position
* @param {bool} [params.close] *contract only* Set as true to close the position, with size set to 0
* @param {bool} [params.auto_size] *contract only* Set side to close dual-mode position, close_long closes the long side, while close_short the short one, size also needs to be set to 0
* @param {int} [params.price_type] *contract only* 0 latest deal price, 1 mark price, 2 index price
* @param {float} [params.cost] *spot market buy only* the quote quantity that can be used as an alternative for the amount
* @returns {object|undefined} [An order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_order_ws(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (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 messageType: Value = self.get_type_by_market(market.clone());
let mut channel: Value = Value::Str(format!("{}{}", messageType, Value::Str(".order_place".into())).into());
let mut url: Value = self.get_url_by_market(market.clone());
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("textIsRequired".into(), Value::Bool(true)); }
let mut request: Value = self.parent.create_order_request(symbol, type_var, side, amount, &[price, params]);
self.authenticate(url.clone(), messageType).await;
let mut rawOrder: Value = self.request_private(url, request, channel, &[]).await;
let mut order: Value = self.parse_order(rawOrder, &[market]);
return order;
Value::Null
}
/*
* @method
* @name gate#createOrdersWs
* @description create a list of trade orders
* @see https://www.gate.io/docs/developers/futures/ws/en/#order-batch-place
* @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_orders_ws(&mut self, mut orders: 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 request: Value = self.parent.create_orders_request(orders.clone(), &[params]);
let mut firstOrder: Value = orders.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(firstOrder.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrdersWs is not supported for swap markets".into()))));
}
// todo add swap support
let mut messageType: Value = self.get_type_by_market(market.clone());
let mut channel: Value = Value::Str(format!("{}{}", messageType, Value::Str(".order_batch_place".into())).into());
let mut url: Value = self.get_url_by_market(market.clone());
self.authenticate(url.clone(), messageType).await;
let mut rawOrders: Value = self.request_private(url, request, channel, &[]).await;
return self.parse_orders(rawOrders, &[market]);
Value::Null
}
/*
* @method
* @name gate#cancelAllOrdersWs
* @description cancel all open orders
* @see https://www.gate.com/docs/developers/futures/ws/en/#cancel-matched-open-orders
* @see https://www.gate.io/docs/developers/apiv4/ws/en/#order-cancel-all-with-specified-currency-pair
* @param {string} symbol unified market symbol, only orders in the market of this symbol are cancelled when symbol is not undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.channel] the channel to use, defaults to spot.order_cancel_cp or futures.order_cancel_cp
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_all_orders_ws(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelAllOrdersWs() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = (if (symbol == Value::Null) { Value::Null } else { self.market(symbol) });
let mut trigger: Value = self.safe_bool2(params.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
let mut messageType: Value = self.get_type_by_market(market.clone());
let mut channel: Value = Value::Str(format!("{}{}", messageType, Value::Str(".order_cancel_cp".into())).into());
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("cancelAllOrdersWs".into()), Value::Str("channel".into()), &[channel.clone()]); channel = __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 url: Value = self.get_url_by_market(market.clone());
params = self.omit(params.clone(), Value::from(vec![Value::Str("stop".into()), Value::Str("trigger".into())]), &[]);
let mut type_varqueryVariable = self.handle_market_type_and_params(Value::Str("cancelAllOrders".into()), &[market.clone(), params]);
let mut type_var: Value = type_varqueryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = type_varqueryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut requestrequestParamsVariable = (if (type_var.as_str() == Some("spot")) { self.parent.multi_order_spot_prepare_request(&[market.clone(), trigger, query.clone()]) } else { self.parent.prepare_request(&[market.clone(), type_var, query]) });
let mut request: Value = requestrequestParamsVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut requestParams: Value = requestrequestParamsVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
self.authenticate(url.clone(), messageType).await;
let __ws_arg_0 = self.extend(request, &[requestParams]);
let mut rawOrders: Value = self.request_private(url, __ws_arg_0, channel, &[]).await;
return self.parse_orders(rawOrders, &[market]);
Value::Null
}
/*
* @method
* @name gate#cancelOrderWs
* @description Cancels an open order
* @see https://www.gate.io/docs/developers/apiv4/ws/en/#order-cancel
* @see https://www.gate.io/docs/developers/futures/ws/en/#order-cancel
* @param {string} id Order id
* @param {string} symbol Unified market symbol
* @param {object} [params] Parameters specified by the exchange api
* @param {bool} [params.trigger] True if the order to be cancelled is a trigger order
* @returns An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order_ws(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = (if (symbol == Value::Null) { Value::Null } else { self.market(symbol) });
let mut trigger: Value = self.safe_bool_n(params.clone(), Value::from(vec![Value::Str("is_stop_order".into()), Value::Str("stop".into()), Value::Str("trigger".into())]), &[Value::Bool(false)]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("is_stop_order".into()), Value::Str("stop".into()), Value::Str("trigger".into())]), &[]);
let mut type_varqueryVariable = self.handle_market_type_and_params(Value::Str("cancelOrder".into()), &[market.clone(), params]);
let mut type_var: Value = type_varqueryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = type_varqueryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut requestrequestParamsVariable = (if ((type_var.as_str() == Some("spot")) || (type_var.as_str() == Some("margin"))) { self.parent.spot_order_prepare_request(&[market.clone(), trigger, query.clone()]) } else { self.parent.prepare_request(&[market.clone(), type_var, query]) });
let mut request: Value = requestrequestParamsVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut requestParams: Value = requestrequestParamsVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut messageType: Value = self.get_type_by_market(market.clone());
let mut channel: Value = Value::Str(format!("{}{}", messageType, Value::Str(".order_cancel".into())).into());
let mut url: Value = self.get_url_by_market(market.clone());
self.authenticate(url.clone(), messageType).await;
add_element_to_object(&mut request, &Value::Str("order_id".into()), to_string_val(&id));
let __ws_arg_1 = self.extend(request, &[requestParams]);
let mut res: Value = self.request_private(url, __ws_arg_1, channel, &[]).await;
return self.parse_order(res, &[market]);
Value::Null
}
/*
* @method
* @name gate#editOrderWs
* @description edit a trade order, gate currently only supports the modification of the price or amount fields
* @see https://www.gate.io/docs/developers/apiv4/ws/en/#order-amend
* @see https://www.gate.io/docs/developers/futures/ws/en/#order-amend
* @param {string} id order id
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of the currency you want to trade in units of the base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn edit_order_ws(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut extendedRequest: Value = self.parent.edit_order_request(id, symbol, type_var, side, &[amount, price, params]);
let mut messageType: Value = self.get_type_by_market(market.clone());
let mut channel: Value = Value::Str(format!("{}{}", messageType, Value::Str(".order_amend".into())).into());
let mut url: Value = self.get_url_by_market(market.clone());
self.authenticate(url.clone(), messageType).await;
let mut rawOrder: Value = self.request_private(url, extendedRequest, channel, &[]).await;
return self.parse_order(rawOrder, &[market]);
Value::Null
}
/*
* @method
* @name gate#fetchOrderWs
* @description Retrieves information on an order
* @see https://www.gate.io/docs/developers/apiv4/ws/en/#order-status
* @see https://www.gate.io/docs/developers/futures/ws/en/#order-status
* @param {string} id Order id
* @param {string} symbol Unified market symbol, *required for spot and margin*
* @param {object} [params] Parameters specified by the exchange api
* @param {bool} [params.trigger] True if the order being fetched is a trigger order
* @param {string} [params.marginMode] 'cross' or 'isolated' - marginMode for margin trading if not provided this.options['defaultMarginMode'] is used
* @param {string} [params.type] 'spot', 'swap', or 'future', if not provided this.options['defaultMarginMode'] is used
* @param {string} [params.settle] 'btc' or 'usdt' - settle currency for perpetual swap and future - market settle currency is used if symbol !== undefined, default="usdt" for swap and "btc" for future
* @returns An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_order_ws(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = (if (symbol == Value::Null) { Value::Null } else { self.market(symbol.clone()) });
let mut requestrequestParamsVariable = self.parent.fetch_order_request(id, &[symbol, params]);
let mut request: Value = requestrequestParamsVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut requestParams: Value = requestrequestParamsVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut messageType: Value = self.get_type_by_market(market.clone());
let mut channel: Value = Value::Str(format!("{}{}", messageType, Value::Str(".order_status".into())).into());
let mut url: Value = self.get_url_by_market(market.clone());
self.authenticate(url.clone(), messageType).await;
let __ws_arg_2 = self.extend(request, &[requestParams]);
let mut rawOrder: Value = self.request_private(url, __ws_arg_2, channel, &[]).await;
return self.parse_order(rawOrder, &[market]);
Value::Null
}
/*
* @method
* @name gate#fetchOpenOrdersWs
* @description fetch all unfilled currently open orders
* @see https://www.gate.io/docs/developers/futures/ws/en/#order-list
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_orders_ws(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_orders_by_status_ws(Value::Str("open".into()), &[symbol, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name gate#fetchClosedOrdersWs
* @description fetches information on multiple closed orders made by the user
* @see https://www.gate.io/docs/developers/futures/ws/en/#order-list
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_closed_orders_ws(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_orders_by_status_ws(Value::Str("finished".into()), &[symbol, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name gate#fetchOrdersWs
* @see https://www.gate.io/docs/developers/futures/ws/en/#order-list
* @description fetches information on multiple orders made by the user by status
* @param {string} status requested order status
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int|undefined} [since] the earliest time in ms to fetch orders for
* @param {int|undefined} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.orderId] order id to begin at
* @param {int} [params.limit] the maximum number of order structures to retrieve
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_orders_by_status_ws(&mut self, mut status: Value, 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 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);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOrdersByStatusWs is only supported by swap markets. Use rest API for other markets".into()))));
}
}
let mut requestrequestParamsVariable = self.parent.prepare_orders_by_status_request(status, &[symbol.clone(), since.clone(), limit.clone(), params]);
let mut request: Value = requestrequestParamsVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut requestParams: Value = requestrequestParamsVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut newRequest: Value = self.omit(request, Value::from(vec![Value::Str("settle".into())]), &[]);
let mut messageType: Value = self.get_type_by_market(market.clone());
let mut channel: Value = Value::Str(format!("{}{}", messageType, Value::Str(".order_list".into())).into());
let mut url: Value = self.get_url_by_market(market.clone());
self.authenticate(url.clone(), messageType).await;
let __ws_arg_3 = self.extend(newRequest, &[requestParams]);
let mut rawOrders: Value = self.request_private(url, __ws_arg_3, channel, &[]).await;
let mut orders: Value = self.parse_orders(rawOrders, &[market]);
return self.filter_by_symbol_since_limit(orders, &[symbol, since, limit]);
Value::Null
}
/*
* @method
* @name gate#watchOrderBook
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://www.gate.com/docs/developers/apiv4/ws/en/#order-book-channel
* @see https://www.gate.com/docs/developers/apiv4/ws/en/#order-book-v2-api
* @see https://www.gate.com/docs/developers/futures/ws/en/#order-book-api
* @see https://www.gate.com/docs/developers/futures/ws/en/#order-book-v2-api
* @see https://www.gate.com/docs/developers/delivery/ws/en/#order-book-api
* @see https://www.gate.com/docs/developers/options/ws/en/#order-book-channel
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut marketId: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut url: Value = self.get_url_by_market(market.clone());
let mut isEuUrl: bool = get_index_of(&url, &Value::Str("gateeu".into())).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64);
let mut isNonEuSpot: bool = (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) && !isEuUrl;
let mut intervalDefault: Value = (if isNonEuSpot { Value::Str("50".into()) } else { Value::Str("100ms".into()) });
let mut intervalqueryVariable = self.handle_option_and_params(params, Value::Str("watchOrderBook".into()), Value::Str("interval".into()), &[intervalDefault]);
let mut interval: Value = intervalqueryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = intervalqueryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut messageType: Value = self.get_type_by_market(market.clone());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("orderbook".into()), Value::Str(":".into())).into()), symbol).into());
if (limit == Value::Null) {
limit = (if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { Value::Int(50) } else { Value::Int(100) }); // max 100 atm
if (messageType.as_str() == Some("options")) {
limit = Value::Int(50); // max 50 for options
}
}
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
// the subscription limit seeds the rest snapshot, gateeu returns an empty book above 100
let mut maxSpotLimit: Value = self.handle_option(Value::Str("fetchOrderBook".into()), Value::Str("maxSpotLimit".into()), &[Value::Int(1000)]);
limit = crate::runtime::Math::min(&limit, &maxSpotLimit);
}
let mut payload: Value = Value::from(vec![]);
let mut channel: Value = Value::Str("".into());
if isEuUrl {
channel = Value::Str("spot.order_book_update".into());
payload = Value::from(vec![marketId.clone(), interval.clone()]);
} else if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
channel = Value::Str("spot.obu".into());
let mut finalInterval: Value = interval.clone();
if (limit.as_f64() == Some(400.0)) {
finalInterval = Value::Str("400".into());
}
payload = Value::from(vec![Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("ob.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".".into())).into()), finalInterval).into())]);
} else {
channel = Value::Str(format!("{}{}", messageType, Value::Str(".order_book_update".into())).into());
payload = Value::from(vec![marketId, interval]);
let mut stringLimit: Value = to_string_val(&limit);
append_to_array(&mut payload, stringLimit);
}
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("limit".to_string(), limit.clone());
m
});
let mut orderbook: Value = self.subscribe_public(url, messageHash, payload, channel, &[query, subscription]).await;
return orderbook.limit();
Value::Null
}
/*
* @method
* @name gate#unWatchOrderBook
* @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
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn un_watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut url: Value = self.get_url_by_market(market.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut marketId: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut isEuUrl: bool = get_index_of(&url, &Value::Str("gateeu".into())).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64);
let mut isNonEuSpot: bool = (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) && !isEuUrl;
let mut intervalDefault: Value = (if isNonEuSpot { Value::Str("50".into()) } else { Value::Str("100ms".into()) });
let mut interval: Value = intervalDefault;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrderBook".into()), Value::Str("interval".into()), &[interval.clone()]); interval = __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 messageType: Value = self.get_type_by_market(market.clone());
let mut limit: Value = self.safe_integer_k(params.clone(), "limit", &[]);
if (limit == Value::Null) {
limit = (if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { Value::Int(50) } else { Value::Int(100) }); // max 100 atm
if (messageType.as_str() == Some("options")) {
limit = Value::Int(50); // max 50 for options
}
}
let mut payload: Value = Value::from(vec![]);
let mut channel: Value = Value::Str("".into());
if isEuUrl {
channel = Value::Str("spot.order_book_update".into());
payload = Value::from(vec![marketId.clone(), interval.clone()]);
} else if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
channel = Value::Str("spot.obu".into());
let mut finalInterval: Value = interval.clone();
if (limit.as_f64() == Some(400.0)) {
finalInterval = Value::Str("400".into());
}
payload = Value::from(vec![Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("ob.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".".into())).into()), finalInterval).into())]);
} else {
channel = Value::Str(format!("{}{}", messageType, Value::Str(".order_book_update".into())).into());
payload = Value::from(vec![marketId, interval]);
let mut stringLimit: Value = to_string_val(&limit);
append_to_array(&mut payload, stringLimit);
}
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("orderbook".into()), Value::Str(":".into())).into()), symbol).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("unsubscribe:orderbook".into()), Value::Str(":".into())).into()), symbol).into());
return self.un_subscribe_public_multiple(url, Value::Str("orderbook".into()), Value::from(vec![symbol]), Value::from(vec![messageHash]), Value::from(vec![subMessageHash]), payload, channel, &[params]).await;
Value::Null
}
pub fn handle_order_book_subscription(&mut self, mut client: Value, mut message: Value, optional_args: &[Value]) {
let mut subscription = get_arg(optional_args, 0, Value::Null);
let mut symbol: Value = self.safe_string_k(subscription.clone(), "symbol", &[]);
let mut limit: Value = self.safe_integer_k(subscription, "limit", &[]);
if (symbol != Value::Null) {
{ let __be_tmp = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), limit]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
}
}
pub fn handle_new_spot_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);
//
// {
// "channel":"spot.obu",
// "result":{
// "t":1777275365213,
// "full":true,
// "s":"ob.XRP_USDT.50",
// "u":9649549324,
// "b":[
// [
// "1.414",
// "1397.899"
// ]
// ],
// "a":[
// [
// "1.415",
// "17344.926"
// ]
// ]
// },
// "time_ms":1777275365214,
// "event":"update"
// }
let mut result: Value = (match message.get("result") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut full: Value = self.safe_bool_k(result.clone(), "full", &[Value::Bool(false)]);
let mut marketIdWithPrefix: Value = self.safe_string_k(result.clone(), "s", &[]);
if (marketIdWithPrefix == Value::Null) {
return;
}
let mut marketIdParts: Value = split(&marketIdWithPrefix, &Value::Str(".".into()));
let mut marketId: Value = self.safe_string(marketIdParts, Value::Int(1), &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[Value::Null, Value::Str("_".into()), Value::Str("spot".into())]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbol).into());
if (self.safe_value(self.orderbooks.clone(), symbol.clone(), &[]) == Value::Null) {
{ let __be_tmp = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), Value::Int(1000)]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
}
let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
if (full.as_bool() == Some(true)) {
let mut snapshopt: Value = self.parse_order_book(result.clone(), symbol, &[Value::Null, Value::Str("b".into()), Value::Str("a".into())]);
add_element_to_object(&mut snapshopt, &Value::Str("nonce".into()), self.safe_integer_k(result.clone(), "u", &[]));
add_element_to_object(&mut snapshopt, &Value::Str("timestamp".into()), self.safe_integer_k(result.clone(), "t", &[]));
orderbook.reset(snapshopt);
} else {
let mut nonce: Value = self.safe_integer_k(orderbook.clone(), "nonce", &[]);
let mut deltaStart: Value = self.safe_integer_k(result.clone(), "u", &[]);
if (nonce == Value::Null) || ((deltaStart != Value::Null) && (nonce.as_f64().unwrap_or(f64::NAN) >= deltaStart.as_f64().unwrap_or(f64::NAN))) {
return;
}
self.handle_delta(orderbook.clone(), result);
}
client.resolve(&[orderbook, messageHash]);
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// spot
//
// {
// "time": 1650189272,
// "channel": "spot.order_book_update",
// "event": "update",
// "result": {
// "t": 1650189272515,
// "e": "depthUpdate",
// "E": 1650189272,
// "s": "GMT_USDT",
// "U": 140595902,
// "u": 140595902,
// "b": [
// [ '2.51518', "228.119" ],
// [ '2.50587', "1510.11" ],
// [ '2.49944', "67.6" ],
// ],
// "a": [
// [ '2.5182', "4.199" ],
// [ "2.51926", "1874" ],
// [ '2.53528', "96.529" ],
// ]
// }
// }
//
// swap
//
// {
// "id": null,
// "time": 1650188898,
// "channel": "futures.order_book_update",
// "event": "update",
// "error": null,
// "result": {
// "t": 1650188898938,
// "s": "GMT_USDT",
// "U": 1577718307,
// "u": 1577719254,
// "b": [
// { p: "2.5178", s: 0 },
// { p: "2.5179", s: 0 },
// { p: "2.518", s: 0 },
// ],
// "a": [
// { p: "2.52", s: 0 },
// { p: "2.5201", s: 0 },
// { p: "2.5203", s: 0 },
// ]
// }
// }
//
let mut channel: Value = (match __pro_message.get("channel").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 (channel.as_str() == Some("spot.obu")) {
self.handle_new_spot_order_book(client.clone(), message);
return;
}
let mut channelParts: Value = split(&channel, &Value::Str(".".into()));
let mut rawMarketType: Option<String> = self.safe_string(channelParts, Value::Int(0), &[]).as_str().map(str::to_owned);
let mut isSpot: bool = rawMarketType.as_deref() == Some("spot");
let mut marketType: Value = (if isSpot { Value::Str("spot".into()) } else { Value::Str("contract".into()) });
let mut delta: Value = (match __pro_message.get("result").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
let mut deltaStart: Value = self.safe_integer_k(delta.clone(), "U", &[]);
let mut deltaEnd: Value = self.safe_integer_k(delta.clone(), "u", &[]);
let mut marketId: Value = self.safe_string_k(delta.clone(), "s", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[Value::Null, Value::Str("_".into()), marketType]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbol).into());
let mut storedOrderBook: Value = self.safe_value(self.orderbooks.clone(), symbol.clone(), &[self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})])]);
let mut nonce: Value = self.safe_integer_k(storedOrderBook.clone(), "nonce", &[]);
if (nonce == Value::Null) {
let mut cacheLength: Value = Value::Int(0);
if (storedOrderBook != Value::Null) {
cacheLength = get_array_length(&get_value(&storedOrderBook, &Value::Str("cache".into())));
}
let mut snapshotDelay: Value = self.handle_option(Value::Str("watchOrderBook".into()), Value::Str("snapshotDelay".into()), &[Value::Int(10)]);
let mut waitAmount: Value = (if isSpot { snapshotDelay } else { Value::Int(0) });
if is_equal(&cacheLength, &waitAmount) {
// max limit is 100
let mut subscription: Value = get_value(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
let mut limit: Value = self.safe_integer_k(subscription, "limit", &[]);
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
})]); // needed for c#, number of args needs to match
}
crate::runtime::append_to_object_array(&mut storedOrderBook, &Value::Str("cache".into()), delta.clone());
return;
} else if (deltaEnd != Value::Null) && (nonce.as_f64().unwrap_or(f64::NAN) >= deltaEnd.as_f64().unwrap_or(f64::NAN)) {
return;
} else if (deltaStart != Value::Null) && (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)) {
self.handle_delta(storedOrderBook.clone(), delta);
} else {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
remove(&mut self.orderbooks, &symbol);
let mut checksum: Value = self.handle_option(Value::Str("watchOrderBook".into()), Value::Str("checksum".into()), &[Value::Bool(true)]);
if is_equal(&checksum, &Value::Bool(true)) {
let mut error = Value::from(crate::exchange_errors::checksum_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), self.orderbook_checksum_message(symbol))));
client.reject(&[Value::from(error), messageHash.clone()]);
}
}
client.resolve(&[storedOrderBook, messageHash]);
}
pub fn get_cache_index(&self, mut orderBook: Value, mut cache: Value) -> Value {
let mut nonce: Value = self.safe_integer_k(orderBook, "nonce", &[]);
let mut firstDelta: Value = get_value(&cache, &Value::Int(0));
let mut firstDeltaStart: Value = self.safe_integer_k(firstDelta, "U", &[]);
if (nonce != Value::Null) && (firstDeltaStart != Value::Null) && (nonce.as_f64().unwrap_or(f64::NAN) < firstDeltaStart.as_f64().unwrap_or(f64::NAN)) {
return Value::Int(-1);
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_339: bool = true;
while { if !__for_first_339 { 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_339 = 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_k(delta.clone(), "U", &[]);
let mut deltaEnd: Value = self.safe_integer_k(delta, "u", &[]);
if (nonce != Value::Null) && (deltaStart != Value::Null) && (deltaEnd != Value::Null) && (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_bid_asks(&self, mut bookSide: Value, mut bidAsks: Value) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_340: bool = true;
while { if !__for_first_340 { 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_340 = false; i.as_f64().unwrap_or(f64::NAN) < ((bidAsks.len() as i64) as f64) } {
let mut bidAsk: Value = 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);
if (matches!(&bidAsk, Value::Arr(_))) {
bookSide.store_array(self.parse_order_book_bid_ask(bidAsk.clone(), &[]));
} else {
let mut price: Value = self.safe_float_k(bidAsk.clone(), "p", &[]);
let mut amount: Value = self.safe_float_k(bidAsk, "s", &[]);
bookSide.store(price, amount);
}
}
}
}
pub fn handle_delta(&self, mut orderbook: Value, mut delta: Value) {
let mut timestamp: Value = self.safe_integer_k(delta.clone(), "t", &[]);
add_element_to_object(&mut orderbook, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut orderbook, &Value::Str("datetime".into()), self.iso8601(timestamp));
add_element_to_object(&mut orderbook, &Value::Str("nonce".into()), self.safe_integer_k(delta.clone(), "u", &[]));
let mut bids: Value = self.safe_list_k(delta.clone(), "b", &[Value::from(vec![])]);
let mut asks: Value = self.safe_list_k(delta, "a", &[Value::from(vec![])]);
let mut storedBids: Value = crate::value::get_value_k(&orderbook, "bids");
let mut storedAsks: Value = crate::value::get_value_k(&orderbook, "asks");
self.handle_bid_asks(storedBids, bids);
self.handle_bid_asks(storedAsks, asks);
}
/*
* @method
* @name gate#watchTicker
* @see https://www.gate.io/docs/developers/apiv4/ws/en/#tickers-channel
* @see https://www.gate.com/docs/developers/futures/ws/en/#tickers-api
* @see https://www.gate.com/docs/developers/delivery/ws/en/#tickers-api
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("callerMethodName".into(), Value::Str("watchTicker".into())); }
let mut result: Value = self.watch_tickers(&[Value::from(vec![symbol.clone()]), params]).await;
return self.safe_value(result, symbol, &[]);
Value::Null
}
/*
* @method
* @name gate#watchTickers
* @see https://www.gate.io/docs/developers/apiv4/ws/en/#tickers-channel
* @see https://www.gate.com/docs/developers/futures/ws/en/#tickers-api
* @see https://www.gate.com/docs/developers/delivery/ws/en/#tickers-api
* @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
* @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
}));
let __ws_arg_4 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("tickers".into()));
m
}), &[params]);
return self.subscribe_watch_tickers_and_bids_asks(&[symbols, Value::Str("watchTickers".into()), __ws_arg_4]).await;
Value::Null
}
pub fn handle_ticker(&mut self, mut client: Value, mut message: Value) {
//
// {
// "time": 1649326221,
// "channel": "spot.tickers",
// "event": "update",
// "result": {
// "currency_pair": "BTC_USDT",
// "last": "43444.82",
// "lowest_ask": "43444.82",
// "highest_bid": "43444.81",
// "change_percentage": "-4.0036",
// "base_volume": "5182.5412425462",
// "quote_volume": "227267634.93123952",
// "high_24h": "47698",
// "low_24h": "42721.03"
// }
// }
//
self.handle_ticker_and_bid_ask(Value::Str("ticker".into()), client, message);
}
/*
* @method
* @name gate#watchBidsAsks
* @see https://www.gate.io/docs/developers/apiv4/ws/en/#best-bid-or-ask-price
* @see https://www.gate.io/docs/developers/apiv4/ws/en/#order-book-channel
* @see https://www.gate.com/docs/developers/options/ws/en/#best-bid-or-ask-price
* @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
}));
let __ws_arg_5 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("book_ticker".into()));
m
}), &[params]);
return self.subscribe_watch_tickers_and_bids_asks(&[symbols, Value::Str("watchBidsAsks".into()), __ws_arg_5]).await;
Value::Null
}
pub fn handle_bid_ask(&mut self, mut client: Value, mut message: Value) {
//
// {
// "time": 1671363004,
// "time_ms": 1671363004235,
// "channel": "spot.book_ticker",
// "event": "update",
// "result": {
// "t": 1671363004228,
// "u": 9793320464,
// "s": "BTC_USDT",
// "b": "16716.8",
// "B": "0.0134",
// "a": "16716.9",
// "A": "0.0353"
// }
// }
//
self.handle_ticker_and_bid_ask(Value::Str("bidask".into()), client, message);
}
pub async fn subscribe_watch_tickers_and_bids_asks(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut callerMethodName = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
{ let __destr_tmp = self.handle_param_string(params.clone(), Value::Str("callerMethodName".into()), &[callerMethodName.clone()]); callerMethodName = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false)]);
let mut market: Value = self.market(symbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
let mut messageType: Value = self.get_type_by_market(market.clone());
let mut marketIds: Value = self.market_ids(&[symbols.clone()]);
let mut channelName: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), callerMethodName.clone(), Value::Str("method".into()), &[]); channelName = __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 url: Value = self.get_url_by_market(market);
let mut channel: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageType, Value::Str(".".into())).into()), channelName).into());
if (callerMethodName == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a callerMethodName argument".into()))));
}
let mut isWatchTickers: bool = Value::Int(callerMethodName.as_str().and_then(|__s| __s.find("watchTicker")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64);
let mut prefix: Value = (if isWatchTickers { Value::Str("ticker".into()) } else { Value::Str("bidask".into()) });
let mut messageHashes: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_341: bool = true;
while { if !__for_first_341 { 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_341 = 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!("{}{}", prefix, Value::Str(":".into())).into()), symbol).into()));
}
}
let mut tickerOrBidAsk: Value = self.subscribe_public_multiple(url, messageHashes, marketIds, channel, &[params]).await;
if is_true(&self.newUpdates) {
let mut items: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut items, &crate::value::get_value_k(&tickerOrBidAsk, "symbol"), tickerOrBidAsk.clone());
return items;
}
let mut result: Value = (if isWatchTickers { self.tickers.clone() } else { self.bidsasks.clone() });
return self.filter_by_array(result, Value::Str("symbol".into()), &[symbols, Value::Bool(true)]);
Value::Null
}
pub fn handle_ticker_and_bid_ask(&mut self, mut objectName: Value, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
let mut channel: Value = (match message.get("channel") { 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(&channel, &Value::Str(".".into()));
let mut rawMarketType: Option<String> = self.safe_string(parts, Value::Int(0), &[]).as_str().map(str::to_owned);
let mut marketType: Value = (if (rawMarketType.as_deref() == Some("futures")) { Value::Str("contract".into()) } else { Value::Str("spot".into()) });
let mut result: Value = (match message.get("result") { Some(__v) if !matches!(__v, Value::Null) && !matches!(__v, Value::Str(__s) if __s.is_empty()) => __v.clone(), _ => Value::Null });
let mut results: Value = Value::from(vec![]);
if (matches!(&result, Value::Arr(_))) {
results = (match message.get("result") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
} else {
let mut rawTicker: Value = (match message.get("result") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
results = Value::from(vec![rawTicker.clone()]);
}
let mut isTicker: bool = objectName.as_str() == Some("ticker"); // whether ticker or bid-ask
{
let mut i: Value = Value::Int(0);
let mut __for_first_342: bool = true;
while { if !__for_first_342 { 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_342 = false; i.as_f64().unwrap_or(f64::NAN) < ((results.len() as i64) as f64) } {
let mut rawTicker: Value = results.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 marketId: Value = self.safe_string_k(rawTicker.clone(), "s", &[]);
let mut market: Value = self.safe_market(&[marketId, Value::Null, Value::Str("_".into()), marketType.clone()]);
let mut parsedItem: Value = self.parse_ticker(rawTicker, &[market]);
let mut symbol: Value = parsedItem.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if isTicker {
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut self.tickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), parsedItem.clone()); }
}
} else {
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut self.bidsasks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), parsedItem.clone()); }
}
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", objectName, Value::Str(":".into())).into()), symbol).into());
client.resolve(&[parsedItem, messageHash]);
}
}
}
/*
* @method
* @name gate#watchTrades
* @see https://www.gate.com/docs/developers/apiv4/ws/en/#public-trades-channel
* @see https://www.gate.com/docs/developers/futures/ws/en/#trades-api
* @see https://www.gate.com/docs/developers/delivery/ws/en/#trades-api
* @see https://www.gate.com/docs/developers/options/ws/en/#public-contract-trades-channel
* @description get the list of most recent trades for a particular symbol
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.watch_trades_for_symbols(Value::from(vec![symbol]), &[since, limit, params]).await;
Value::Null
}
/*
* @method
* @name gate#watchTradesForSymbols
* @see https://www.gate.com/docs/developers/apiv4/ws/en/#public-trades-channel
* @see https://www.gate.com/docs/developers/futures/ws/en/#trades-api
* @see https://www.gate.com/docs/developers/delivery/ws/en/#trades-api
* @see https://www.gate.com/docs/developers/options/ws/en/#public-contract-trades-channel
* @description get the list of most recent trades for a particular symbol
* @param {string[]} symbols unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_trades_for_symbols(&mut self, mut symbols: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (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 market: Value = self.market(symbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
let mut messageType: Value = self.get_type_by_market(market.clone());
let mut channel: Value = Value::Str(format!("{}{}", messageType, Value::Str(".trades".into())).into());
let mut messageHashes: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_343: bool = true;
while { if !__for_first_343 { 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_343 = 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 url: Value = self.get_url_by_market(market);
let mut trades: Value = self.subscribe_public_multiple(url, messageHashes, marketIds, channel, &[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 gate#unWatchTradesForSymbols
* @description get the list of most recent trades for a particular symbol
* @param {string[]} symbols unified symbol of the market to fetch trades for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?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()]);
let mut marketIds: Value = self.market_ids(&[symbols.clone()]);
let mut market: Value = self.market(symbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
let mut messageType: Value = self.get_type_by_market(market.clone());
let mut channel: Value = Value::Str(format!("{}{}", messageType, Value::Str(".trades".into())).into());
let mut subMessageHashes: Value = Value::from(vec![]);
let mut messageHashes: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_344: bool = true;
while { if !__for_first_344 { 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_344 = 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 subMessageHashes, Value::Str(format!("{}{}", Value::Str("trades:".into()), symbol).into()));
append_to_array(&mut messageHashes, Value::Str(format!("{}{}", Value::Str("unsubscribe:trades:".into()), symbol).into()));
}
}
let mut url: Value = self.get_url_by_market(market);
return self.un_subscribe_public_multiple(url, Value::Str("trades".into()), symbols, messageHashes, subMessageHashes, marketIds, channel, &[params]).await;
Value::Null
}
/*
* @method
* @name gate#unWatchTrades
* @description get the list of most recent trades for a particular symbol
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?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
}));
return self.un_watch_trades_for_symbols(Value::from(vec![symbol]), &[params]).await;
Value::Null
}
pub fn handle_trades(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "time": 1648725035,
// "channel": "spot.trades",
// "event": "update",
// "result": [{
// "id": 3130257995,
// "create_time": 1648725035,
// "create_time_ms": "1648725035923.0",
// "side": "sell",
// "currency_pair": "LTC_USDT",
// "amount": "0.0116",
// "price": "130.11"
// }]
// }
//
let mut result: Value = (match message.get("result") { Some(__v) if !matches!(__v, Value::Null) && !matches!(__v, Value::Str(__s) if __s.is_empty()) => __v.clone(), _ => Value::Null });
if !(matches!(&result, Value::Arr(_))) {
result = Value::from(vec![result.clone()]);
}
let mut parsedTrades: Value = self.parse_trades(result, &[]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_345: bool = true;
while { if !__for_first_345 { 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_345 = false; i.as_f64().unwrap_or(f64::NAN) < ((parsedTrades.len() as i64) as f64) } {
let mut trade: Value = parsedTrades.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 symbol: Value = trade.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut cachedTrades: Value = self.safe_value(self.trades.clone(), symbol.clone(), &[]);
if (cachedTrades == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
cachedTrades = ArrayCache::new(limit);
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), cachedTrades.clone()); }
}
}
cachedTrades.append(trade);
let mut hash: Value = Value::Str(format!("{}{}", Value::Str("trades:".into()), symbol).into());
client.resolve(&[cachedTrades, hash]);
}
}
}
/*
* @method
* @name gate#watchOHLCV
* @see https://www.gate.com/docs/developers/apiv4/ws/en/#candlesticks-channel
* @see https://www.gate.com/docs/developers/futures/ws/en/#candlesticks-api
* @see https://www.gate.com/docs/developers/delivery/ws/en/#candlesticks-api
* @description watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn watch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
// todo add options support
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 marketId: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut interval: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
let mut messageType: Value = self.get_type_by_market(market.clone());
let mut channel: Value = Value::Str(format!("{}{}", messageType, Value::Str(".candlesticks".into())).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("candles:".into()), interval).into()), Value::Str(":".into())).into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into());
let mut url: Value = self.get_url_by_market(market);
let mut payload: Value = Value::from(vec![interval, marketId]);
let mut ohlcv: Value = self.subscribe_public(url, messageHash, payload, channel, &[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
}
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);
//
// {
// "time": 1606292600,
// "channel": "spot.candlesticks",
// "event": "update",
// "result": {
// "t": "1606292580", // total volume
// "v": "2362.32035", // volume
// "c": "19128.1", // close
// "h": "19128.1", // high
// "l": "19128.1", // low
// "o": "19128.1", // open
// "n": "1m_BTC_USDT" // sub
// }
// }
//
let mut channel: Value = (match message.get("channel") { 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 channelParts: Value = split(&channel, &Value::Str(".".into()));
let mut rawMarketType: Option<String> = self.safe_string(channelParts, Value::Int(0), &[]).as_str().map(str::to_owned);
let mut marketType: Value = (if (rawMarketType.as_deref() == Some("spot")) { Value::Str("spot".into()) } else { Value::Str("contract".into()) });
let mut result: Value = (match message.get("result") { Some(__v) if !matches!(__v, Value::Null) && !matches!(__v, Value::Str(__s) if __s.is_empty()) => __v.clone(), _ => Value::Null });
if !(matches!(&result, Value::Arr(_))) {
result = Value::from(vec![result.clone()]);
}
let mut marketIds: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_346: bool = true;
while { if !__for_first_346 { 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_346 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&result).as_f64().unwrap_or(f64::NAN) } {
let mut ohlcv: Value = get_value(&result, &i);
let mut ohlcv: Value = get_value(&result, &i);
let mut subscription: Value = self.safe_string_k(ohlcv.clone(), "n", &[Value::Str("".into())]);
let mut parts: Value = split(&subscription, &Value::Str("_".into()));
let mut timeframeId: Value = self.safe_string(parts, Value::Int(0), &[]);
let mut timeframe: Value = self.find_timeframe(timeframeId, &[]);
let mut prefix: Value = Value::Str(format!("{}{}", timeframe, Value::Str("_".into())).into());
let mut marketId: Value = replace_str(&subscription, &prefix, &Value::Str("".into()));
let mut symbol: Value = self.safe_symbol(marketId, &[Value::Null, Value::Str("_".into()), marketType.clone()]);
let mut parsed: Value = self.parse_ohlcv(ohlcv, &[]);
{ let __be_tmp = self.safe_value(self.ohlcvs.clone(), symbol.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); if let Value::Dict(__d) = &mut self.ohlcvs { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
let mut stored: Value = self.safe_value(self.safe_value(self.ohlcvs.clone(), symbol.clone(), &[]), timeframe.clone(), &[]);
if (stored == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "OHLCVLimit", &[Value::Int(1000)]);
stored = ArrayCacheByTimestamp::new(limit);
if (symbol != Value::Null) && (timeframe != Value::Null) {
add_element_to_object(get_value_mut(&mut self.ohlcvs, &symbol), &timeframe, stored.clone());
}
}
stored.append(parsed);
if let Value::Dict(__d) = &mut marketIds { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), timeframe.clone()); }
}
}
let mut keys: Value = object_keys(&marketIds);
{
let mut i: Value = Value::Int(0);
let mut __for_first_347: bool = true;
while { if !__for_first_347 { 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_347 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut symbol: 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);
let mut timeframe: Value = get_value(&marketIds, &symbol);
let mut timeframe: Value = get_value(&marketIds, &symbol);
let mut interval: Value = self.find_timeframe(timeframe, &[]);
let mut hash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("candles".into()), Value::Str(":".into())).into()), interval).into()), Value::Str(":".into())).into()), symbol).into());
let mut stored: Value = self.safe_value(get_value(&self.ohlcvs, &symbol), interval, &[]);
client.resolve(&[stored, hash]);
}
}
}
/*
* @method
* @name gate#watchMyTrades
* @see https://www.gate.com/docs/developers/apiv4/ws/en/#user-trades-channel
* @see https://www.gate.com/docs/developers/futures/ws/en/#user-trades-api
* @see https://www.gate.com/docs/developers/delivery/ws/en/#user-trades-api
* @see https://www.gate.com/docs/developers/options/ws/en/#user-trades-channel
* @description watches information on multiple trades made by the user
* @param {string} symbol unified market symbol of the market trades were made in
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trade structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut subType: Value = Value::Null;
let mut type_var: Value = Value::Null;
let mut marketId: Value = Value::Str(format!("{}{}", Value::Str("!".into()), Value::Str("all".into())).into());
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
marketId = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
}
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchMyTrades".into()), &[market.clone(), params.clone()]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
{ let __destr_tmp = self.handle_sub_type_and_params(Value::Str("watchMyTrades".into()), &[market, params.clone()]); subType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut messageType: Value = self.get_supported_mapping(type_var.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("spot".into()));
m.insert("margin".to_string(), Value::Str("spot".into()));
m.insert("future".to_string(), Value::Str("futures".into()));
m.insert("swap".to_string(), Value::Str("futures".into()));
m.insert("option".to_string(), Value::Str("options".into()));
m
})]);
let mut channel: Value = add(&messageType, &Value::Str(".usertrades".into()));
let mut messageHash: Value = Value::Str("myTrades".into());
if (symbol != Value::Null) {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(format!("{}{}", Value::Str(":".into()), symbol).into())).into());
}
let mut isInverse: Value = (Value::Bool(subType.as_str() == Some("inverse")));
let mut url: Value = self.get_url_by_market_type(type_var.clone(), &[isInverse]);
let mut payload: Value = Value::from(vec![marketId]);
// uid required for non spot markets
let mut requiresUid: Value = (Value::Bool(type_var.as_str() != Some("spot")));
let mut trades: Value = self.subscribe_private(url, messageHash, payload, channel, params, &[requiresUid]).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 handle_my_trades(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "time": 1543205083,
// "channel": "futures.usertrades",
// "event": "update",
// "error": null,
// "result": [
// {
// "id": "3335259",
// "create_time": 1628736848,
// "create_time_ms": 1628736848321,
// "contract": "BTC_USD",
// "order_id": "4872460",
// "size": 1,
// "price": "40000.4",
// "role": "maker"
// }
// ]
// }
//
let mut result: Value = (match message.get("result") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut tradesLength: f64 = ((result.len() as i64) as f64);
if (tradesLength == 0.0) {
return;
}
let mut cachedTrades: Value = self.myTrades.clone();
if (cachedTrades == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
cachedTrades = ArrayCacheBySymbolById::new(limit);
self.myTrades = cachedTrades.clone();
}
let mut parsed: Value = self.parse_trades(result, &[]);
let mut marketIds: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_348: bool = true;
while { if !__for_first_348 { 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_348 = false; i.as_f64().unwrap_or(f64::NAN) < ((parsed.len() as i64) as f64) } {
let mut trade: Value = parsed.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);
cachedTrades.append(trade.clone());
let mut symbol: Value = trade.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut marketIds { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Bool(true)); }
}
}
}
let mut keys: Value = object_keys(&marketIds);
{
let mut i: Value = Value::Int(0);
let mut __for_first_349: bool = true;
while { if !__for_first_349 { 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_349 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut market: 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);
let mut hash: Value = Value::Str(format!("{}{}", Value::Str("myTrades:".into()), market).into());
client.resolve(&[cachedTrades.clone(), hash]);
}
}
client.resolve(&[cachedTrades, Value::Str("myTrades".into())]);
}
/*
* @method
* @name gate#watchBalance
* @description watch balance and get the amount of funds available for trading or funds locked in orders
* @see https://www.gate.com/docs/developers/apiv4/ws/en/#spot-balance-channel
* @see https://www.gate.com/docs/developers/futures/ws/en/#balances-api
* @see https://www.gate.com/docs/developers/delivery/ws/en/#balances-api
* @see https://www.gate.com/docs/developers/options/ws/en/#balances-channel
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn watch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut type_var: Value = Value::Null;
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchBalance".into()), &[Value::Null, params.clone()]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
{ let __destr_tmp = self.handle_sub_type_and_params(Value::Str("watchBalance".into()), &[Value::Null, params.clone()]); subType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut isInverse: Value = (Value::Bool(subType.as_str() == Some("inverse")));
let mut url: Value = self.get_url_by_market_type(type_var.clone(), &[isInverse]);
let mut requiresUid: Value = (Value::Bool(type_var.as_str() != Some("spot")));
let mut channelType: Value = self.get_supported_mapping(type_var.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("spot".into()));
m.insert("margin".to_string(), Value::Str("spot".into()));
m.insert("future".to_string(), Value::Str("futures".into()));
m.insert("swap".to_string(), Value::Str("futures".into()));
m.insert("option".to_string(), Value::Str("options".into()));
m
})]);
// todo: add correct margin support
let mut channel: Value = add(&channelType, &Value::Str(".balances".into()));
let mut messageHash: Value = Value::Str(format!("{}{}", type_var, Value::Str(".balance".into())).into());
return self.subscribe_private(url, messageHash, Value::Null, channel, params, &[requiresUid]).await;
Value::Null
}
pub fn handle_balance(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// spot order fill
// {
// "time": 1653664351,
// "time_ms": 1605248616763,
// "channel": "spot.balances",
// "event": "update",
// "result": [
// {
// "timestamp": "1667556323",
// "timestamp_ms": "1667556323730",
// "user": "1000001",
// "currency": "USDT",
// "change": "0",
// "total": "222244.3827652",
// "available": "222244.3827",
// "freeze": "5",
// "freeze_change": "5.000000",
// "change_type": "order-create"
// }
// ]
// }
//
// account transfer
//
// {
// "id": null,
// "time": 1653665088,
// "channel": "futures.balances",
// "event": "update",
// "error": null,
// "result": [
// {
// "balance": 25.035008537,
// "change": 25,
// "text": "-",
// "time": 1653665088,
// "time_ms": 1653665088286,
// "type": "dnw",
// "user": "10406147"
// }
// ]
// }
//
// swap order fill
// {
// "id": null,
// "time": 1653665311,
// "channel": "futures.balances",
// "event": "update",
// "error": null,
// "result": [
// {
// "balance": 20.031873037,
// "change": -0.0031355,
// "text": "LTC_USDT:165551103273",
// "time": 1653665311,
// "time_ms": 1653665311437,
// "type": "fee",
// "user": "10406147"
// }
// ]
// }
//
let mut result: Value = (match message.get("result") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert("info".into(), result.clone()); }
{
let mut i: Value = Value::Int(0);
let mut __for_first_350: bool = true;
while { if !__for_first_350 { 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_350 = false; i.as_f64().unwrap_or(f64::NAN) < ((result.len() as i64) as f64) } {
let mut rawBalance: Value = result.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut account: Value = self.account();
let mut currencyId: Value = self.safe_string_k(rawBalance.clone(), "currency", &[Value::Str("USDT".into())]); // when not present it is USDT
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut timestamp: Value = self.safe_integer2(rawBalance.clone(), Value::Str("time_ms".into()), Value::Str("timestamp_ms".into()), &[]);
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert("timestamp".into(), timestamp.clone()); }
{ let __be_tmp = self.iso8601(timestamp); if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert("datetime".into(), __be_tmp); } }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_string_k(rawBalance.clone(), "freeze", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_k(rawBalance.clone(), "available", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string2(rawBalance, Value::Str("total".into()), Value::Str("balance".into()), &[])); }
if (code != Value::Null) {
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
}
}
let mut channel: Value = (match message.get("channel") { 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(&channel, &Value::Str(".".into()));
let mut rawType: Value = self.safe_string(parts, Value::Int(0), &[]);
let mut channelType: Value = self.get_supported_mapping(rawType, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("spot".into()));
m.insert("futures".to_string(), Value::Str("swap".into()));
m.insert("options".to_string(), Value::Str("option".into()));
m
})]);
let mut messageHash: Value = add(&channelType, &Value::Str(".balance".into()));
{ let __t = self.safe_balance(self.balance.clone()); self.balance = __t; }
client.resolve(&[self.balance.clone(), messageHash]);
}
/*
* @method
* @name gate#watchPositions
* @see https://www.gate.io/docs/developers/futures/ws/en/#positions-subscription
* @see https://www.gate.io/docs/developers/delivery/ws/en/#positions-subscription
* @see https://www.gate.io/docs/developers/options/ws/en/#positions-channel
* @description watch all open positions
* @param {string[]} [symbols] list of unified market symbols to watch positions for
* @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
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/en/latest/manual.html#position-structure}
*/
pub async fn watch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
symbols = self.market_symbols(&[symbols.clone()]);
let mut payload: Value = Value::from(vec![Value::Str(format!("{}{}", Value::Str("!".into()), Value::Str("all".into())).into())]);
if !(self.is_empty(symbols.clone()).as_bool() == Some(true)) {
market = self.get_market_from_symbols(&[symbols.clone()]);
}
let mut type_var: Value = Value::Null;
let mut query: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchPositions".into()), &[market.clone(), params]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (type_var.as_str() == Some("spot")) {
type_var = Value::Str("swap".into());
}
let mut typeId: Value = self.get_supported_mapping(type_var.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("future".to_string(), Value::Str("futures".into()));
m.insert("swap".to_string(), Value::Str("futures".into()));
m.insert("option".to_string(), Value::Str("options".into()));
m
})]);
let mut messageHash: Value = Value::Str(format!("{}{}", type_var, Value::Str(":positions".into())).into());
if !(self.is_empty(symbols.clone()).as_bool() == Some(true)) {
if (symbols == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchPositions() symbols is required".into()))));
}
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(format!("{}{}", Value::Str("::".into()), join(&symbols, &Value::Str(",".into()))).into())).into());
}
let mut channel: Value = add(&typeId, &Value::Str(".positions".into()));
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.handle_sub_type_and_params(Value::Str("watchPositions".into()), &[market, query.clone()]); subType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut isInverse: Value = (Value::Bool(subType.as_str() == Some("inverse")));
let mut url: Value = self.get_url_by_market_type(type_var.clone(), &[isInverse]);
let mut client: Value = self.client(&[url.clone()]);
self.set_positions_cache(client.clone(), type_var.clone(), &[symbols.clone()]);
let mut fetchPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".into()), Value::Str("fetchPositionsSnapshot".into()), &[Value::Bool(true)]);
let mut awaitPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".into()), Value::Str("awaitPositionsSnapshot".into()), &[Value::Bool(true)]);
let mut cache: Value = self.safe_value(self.positions.clone(), type_var.clone(), &[]);
if (is_equal(&fetchPositionsSnapshot, &Value::Bool(true))) && (is_equal(&awaitPositionsSnapshot, &Value::Bool(true))) && (cache == Value::Null) {
return crate::exchange_stubs::ws_await_flight(&client.future(&[Value::Str(format!("{}{}", type_var, Value::Str(":fetchPositionsSnapshot".into())).into())])).await;
}
let mut positions: Value = self.subscribe_private(url, messageHash, payload, channel, query, &[Value::Bool(true)]).await;
if is_true(&self.newUpdates) {
return positions;
}
return self.filter_by_symbols_since_limit(self.safe_value(self.positions.clone(), type_var, &[]), &[symbols, since, limit, Value::Bool(true)]);
Value::Null
}
pub fn set_positions_cache(&mut self, mut client: Value, mut type_var: Value, optional_args: &[Value]) {
let mut symbols = get_arg(optional_args, 0, Value::Null);
if (self.positions.clone() == Value::Null) {
self.positions = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
if (in_op(&self.positions, &type_var)) {
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 = add(&type_var, &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(), type_var.clone()]);
}
} else {
add_element_to_object(&mut self.positions, &type_var, ArrayCacheBySymbolBySide::new(Value::Null));
}
}
pub async fn load_positions_snapshot(&mut self, mut client: Value, mut messageHash: Value, mut type_var: Value) -> Value {
let mut positions: Value = self.fetch_positions(&[Value::Null, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var.clone());
m
})]).await;
add_element_to_object(&mut self.positions, &type_var, ArrayCacheBySymbolBySide::new(Value::Null));
let mut cache: Value = get_value(&self.positions, &type_var);
{
let mut i: Value = Value::Int(0);
let mut __for_first_351: bool = true;
while { if !__for_first_351 { 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_351 = false; i.as_f64().unwrap_or(f64::NAN) < ((positions.len() as i64) as f64) } {
let mut position: Value = positions.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut contracts: Value = self.safe_number_k(position.clone(), "contracts", &[Value::Int(0)]);
if (contracts != Value::Null) && (contracts.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
cache.append(position);
}
}
}
// don't remove the future from the .futures cache
if (in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
let mut future: Value = get_value(&get_value(&client, &Value::Str("futures".into())), &messageHash);
future.resolve(&[cache.clone()]);
client.resolve(&[cache, add(&type_var, &Value::Str(":position".into()))]);
}
Value::Null
}
pub fn handle_positions(&self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// time: 1693158497,
// time_ms: 1693158497204,
// channel: 'futures.positions',
// event: 'update',
// result: [{
// contract: 'XRP_USDT',
// cross_leverage_limit: 0,
// entry_price: 0.5253,
// history_pnl: 0,
// history_point: 0,
// last_close_pnl: 0,
// leverage: 0,
// leverage_max: 50,
// liq_price: 0.0361,
// maintenance_rate: 0.01,
// margin: 4.89609962852,
// mode: 'single',
// realised_pnl: -0.0026265,
// realised_point: 0,
// risk_limit: 500000,
// size: 1,
// time: 1693158497,
// time_ms: 1693158497195,
// update_id: 1,
// user: '10444586'
// }]
// }
//
let mut type_var: Value = self.get_market_type_by_url(client.as_map().and_then(|__m| __m.get("url")).cloned().unwrap_or(Value::Null));
let mut data: Value = (match message.get("result") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut cache: Value = get_value(&self.positions, &type_var);
let mut newPositions: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_352: bool = true;
while { if !__for_first_352 { 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_352 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut rawPosition: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut position: Value = self.parse_position(rawPosition, &[]);
let mut symbol: Value = self.safe_string_k(position.clone(), "symbol", &[]);
let mut side: Option<String> = self.safe_string_k(position.clone(), "side", &[]).as_str().map(str::to_owned);
// Control when position is closed no side is returned
if (side.is_none()) {
let mut prevLongPosition: Value = self.safe_dict(cache.clone(), Value::Str(format!("{}{}", symbol, Value::Str("long".into())).into()), &[]);
if (prevLongPosition != Value::Null) {
add_element_to_object(&mut position, &Value::Str("side".into()), prevLongPosition.as_map().and_then(|__m| __m.get("side")).cloned().unwrap_or(Value::Null));
append_to_array(&mut newPositions, position.clone());
cache.append(position.clone());
}
let mut prevShortPosition: Value = self.safe_dict(cache.clone(), Value::Str(format!("{}{}", symbol, Value::Str("short".into())).into()), &[]);
if (prevShortPosition != Value::Null) {
add_element_to_object(&mut position, &Value::Str("side".into()), prevShortPosition.as_map().and_then(|__m| __m.get("side")).cloned().unwrap_or(Value::Null));
append_to_array(&mut newPositions, position.clone());
cache.append(position.clone());
}
// if no prev position is found, default to long
if (prevLongPosition == Value::Null) && (prevShortPosition == Value::Null) {
add_element_to_object(&mut position, &Value::Str("side".into()), Value::Str("long".into()));
append_to_array(&mut newPositions, position.clone());
cache.append(position.clone());
}
} else {
append_to_array(&mut newPositions, position.clone());
cache.append(position);
}
}
}
let mut messageHashes: Value = self.find_message_hashes(client.clone(), add(&type_var, &Value::Str(":positions::".into())));
{
let mut i: Value = Value::Int(0);
let mut __for_first_353: bool = true;
while { if !__for_first_353 { 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_353 = false; i.as_f64().unwrap_or(f64::NAN) < ((messageHashes.len() as i64) as f64) } {
let mut messageHash: Value = messageHashes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut parts: Value = split(&messageHash, &Value::Str("::".into()));
let mut symbolsString: Value = parts.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut symbols: Value = split(&symbolsString, &Value::Str(",".into()));
let mut positions: Value = self.filter_by_array(newPositions.clone(), Value::Str("symbol".into()), &[symbols, Value::Bool(false)]);
if !(self.is_empty(positions.clone()).as_bool() == Some(true)) {
client.resolve(&[positions, messageHash]);
}
}
}
client.resolve(&[newPositions, add(&type_var, &Value::Str(":positions".into()))]);
}
/*
* @method
* @name gate#watchOrders
* @description watches information on multiple orders made by the user
* @see https://www.gate.com/docs/developers/apiv4/ws/en/#orders-channel
* @see https://www.gate.com/docs/developers/futures/ws/en/#orders-api
* @see https://www.gate.com/docs/developers/delivery/ws/en/#orders-api
* @see https://www.gate.com/docs/developers/options/ws/en/#orders-channel
* @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 {string} [params.type] spot, margin, swap, future, or option. Required if listening to all symbols.
* @param {boolean} [params.isInverse] if future, listen to inverse or linear contracts
* @param {boolean} [params.trigger] set to true to watch trigger orders, spot.priceorders and futures.autoorders channels, see https://github.com/ccxt/ccxt/issues/27202
* @param {boolean} [params.stop] alias of params.trigger
* @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 market: Value = Value::Null;
if (symbol != Value::Null) {
let mut marketResolved: Value = self.market(symbol.clone());
market = marketResolved;
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
}
let mut type_var: Value = Value::Null;
let mut query: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchOrders".into()), &[market.clone(), params]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut typeId: Value = self.get_supported_mapping(type_var.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("spot".into()));
m.insert("margin".to_string(), Value::Str("spot".into()));
m.insert("future".to_string(), Value::Str("futures".into()));
m.insert("swap".to_string(), Value::Str("futures".into()));
m.insert("option".to_string(), Value::Str("options".into()));
m
})]);
let mut isTrigger: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_param_bool2(query.clone(), Value::Str("trigger".into()), Value::Str("stop".into()), &[Value::Bool(false)]); isTrigger = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (isTrigger.as_bool() == Some(true)) && (typeId.as_str() == Some("options")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" watchOrders() does not support trigger orders for options, see https://github.com/ccxt/ccxt/issues/27202".into()))));
}
// gate pushes trigger orders on dedicated channels, spot.priceorders and futures.autoorders,
// see https://github.com/ccxt/ccxt/issues/27202
let mut suffix: Value = Value::Str(".orders".into());
if (isTrigger.as_bool() == Some(true)) {
suffix = (if (typeId.as_str() == Some("spot")) { Value::Str(".priceorders".into()) } else { Value::Str(".autoorders".into()) });
}
let mut channel: Value = add(&typeId, &suffix);
let mut messageHash: Value = (if (isTrigger.as_bool() == Some(true)) { Value::Str("triggerOrders".into()) } else { Value::Str("orders".into()) });
let mut payload: Value = Value::from(vec![Value::Str(format!("{}{}", Value::Str("!".into()), Value::Str("all".into())).into())]);
if (market != Value::Null) {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(format!("{}{}", Value::Str(":".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into())).into());
let mut mid: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
if (mid != Value::Null) {
payload = Value::from(vec![mid]);
}
}
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.handle_sub_type_and_params(Value::Str("watchOrders".into()), &[market, query.clone()]); subType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut isInverse: Value = (Value::Bool(subType.as_str() == Some("inverse")));
let mut url: Value = self.get_url_by_market_type(type_var.clone(), &[isInverse]);
// uid required for non spot markets
let mut requiresUid: Value = (Value::Bool(type_var.as_str() != Some("spot")));
let mut orders: Value = self.subscribe_private(url, messageHash, payload, channel, query, &[requiresUid]).await;
if is_true(&self.newUpdates) {
limit = orders.get_limit(symbol, limit.clone());
}
return self.filter_by_since_limit(orders, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
pub fn handle_order(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "time": 1774613210,
// "time_ms": 1774613210392,
// "channel": "spot.orders",
// "event": "update",
// "result": [
// {
// "id": "1036717689726",
// "text": "apiv4",
// "create_time": "1774613210",
// "update_time": "1774613210",
// "currency_pair": "BTC_USDT",
// "type": "limit",
// "account": "unified",
// "side": "buy",
// "amount": "0.1",
// "price": "200",
// "time_in_force": "gtc",
// "left": "0.1",
// "filled_amount": "0",
// "filled_total": "0",
// "avg_deal_price": "0",
// "fee": "0",
// "fee_currency": "BTC",
// "point_fee": "0",
// "gt_fee": "0",
// "rebated_fee": "0",
// "rebated_fee_currency": "BTC",
// "create_time_ms": "1774613210391",
// "update_time_ms": "1774613210391",
// "user": 10406147,
// "event": "put",
// "stp_id": 0,
// "stp_act": "-",
// "finish_as": "open",
// "biz_info": "ch:ccxt",
// "amend_text": "-"
// }
// ]
// }
//
let mut orders: Value = (match message.get("result") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut channel: Value = (match message.get("channel") { 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 isTrigger: bool = (Value::Int(channel.as_str().and_then(|__s| __s.find("autoorders")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64)) || (Value::Int(channel.as_str().and_then(|__s| __s.find("priceorders")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64));
let mut hashPrefix: Value = (if isTrigger { Value::Str("triggerOrders".into()) } else { Value::Str("orders".into()) });
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
if (self.orders.clone() == Value::Null) {
self.orders = ArrayCacheBySymbolById::new(limit.clone());
self.triggerOrders = ArrayCacheBySymbolById::new(limit);
}
let mut stored: Value = (if isTrigger { self.triggerOrders.clone() } else { self.orders.clone() });
let mut marketIds: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut parsedOrders: Value = self.parse_orders(orders, &[]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_354: bool = true;
while { if !__for_first_354 { 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_354 = false; i.as_f64().unwrap_or(f64::NAN) < ((parsedOrders.len() as i64) as f64) } {
let mut parsed: Value = parsedOrders.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);
// inject order status
let mut info: Value = self.safe_dict_k(parsed.clone(), "info", &[]);
let mut event: Option<String> = self.safe_string_k(info.clone(), "event", &[]).as_str().map(str::to_owned);
if (event.as_deref() == Some("put")) || (event.as_deref() == Some("update")) {
add_element_to_object(&mut parsed, &Value::Str("status".into()), Value::Str("open".into()));
} else if (event.as_deref() == Some("finish")) {
let mut status: Option<String> = self.safe_string_k(parsed.clone(), "status", &[]).as_str().map(str::to_owned);
if (status.is_none()) {
let mut left: Option<i64> = self.safe_integer_k(info, "left", &[]).as_i64();
add_element_to_object(&mut parsed, &Value::Str("status".into()), (if (left == Some(0)) { Value::Str("closed".into()) } else { Value::Str("canceled".into()) }));
}
}
stored.append(parsed.clone());
let mut symbol: Value = parsed.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null) != Value::Null) {
add_element_to_object(&mut marketIds, &market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null), Value::Bool(true));
}
}
}
let mut keys: Value = object_keys(&marketIds);
{
let mut i: Value = Value::Int(0);
let mut __for_first_355: bool = true;
while { if !__for_first_355 { 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_355 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", hashPrefix, Value::Str(":".into())).into()), 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)).into());
client.resolve(&[stored.clone(), messageHash]);
}
}
client.resolve(&[stored, hashPrefix]);
}
/*
* @method
* @name gate#watchMyLiquidations
* @description watch the public liquidations of a trading pair
* @see https://www.gate.io/docs/developers/futures/ws/en/#liquidates-api
* @see https://www.gate.io/docs/developers/delivery/ws/en/#liquidates-api
* @see https://www.gate.io/docs/developers/options/ws/en/#liquidates-channel
* @param {string} symbol unified CCXT market symbol
* @param {int} [since] the earliest time in ms to fetch liquidations for
* @param {int} [limit] the maximum number of liquidation structures to retrieve
* @param {object} [params] exchange specific parameters for the bitmex api endpoint
* @returns {object} an array of [liquidation structures]{@link https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure}
*/
pub async fn watch_my_liquidations(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.watch_my_liquidations_for_symbols(Value::from(vec![symbol]), &[since, limit, params]).await;
Value::Null
}
/*
* @method
* @name gate#watchMyLiquidationsForSymbols
* @description watch the private liquidations of a trading pair
* @see https://www.gate.io/docs/developers/futures/ws/en/#liquidates-api
* @see https://www.gate.io/docs/developers/delivery/ws/en/#liquidates-api
* @see https://www.gate.io/docs/developers/options/ws/en/#liquidates-channel
* @param {string[]} symbols unified CCXT market symbols
* @param {int} [since] the earliest time in ms to fetch liquidations for
* @param {int} [limit] the maximum number of liquidation structures to retrieve
* @param {object} [params] exchange specific parameters for the gate api endpoint
* @returns {object} an array of [liquidation structures]{@link https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure}
*/
pub async fn watch_my_liquidations_for_symbols(&mut self, mut symbols: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (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 market: Value = self.get_market_from_symbols(&[symbols.clone()]);
let mut type_var: Value = Value::Null;
let mut query: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchMyLiquidationsForSymbols".into()), &[market.clone(), params]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut typeId: Value = self.get_supported_mapping(type_var.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("future".to_string(), Value::Str("futures".into()));
m.insert("swap".to_string(), Value::Str("futures".into()));
m.insert("option".to_string(), Value::Str("options".into()));
m
})]);
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.handle_sub_type_and_params(Value::Str("watchMyLiquidationsForSymbols".into()), &[market.clone(), query.clone()]); subType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut isInverse: Value = (Value::Bool(subType.as_str() == Some("inverse")));
let mut url: Value = self.get_url_by_market_type(type_var, &[isInverse.clone()]);
let mut payload: Value = Value::from(vec![]);
let mut messageHash: Value = Value::Str("".into());
if self.is_empty(symbols.clone()).as_bool() == Some(true) {
if (typeId.as_str() != Some("futures")) && !(matches!(&isInverse, Value::Bool(true))) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" watchMyLiquidationsForSymbols() does not support listening to all symbols, you must call watchMyLiquidations() instead for each symbol you wish to watch.".into()))));
}
messageHash = Value::Str("myLiquidations".into());
append_to_array(&mut payload, Value::Str("!all".into()));
} else {
let mut symbolsLength: f64 = ((symbols.len() as i64) as f64);
if (symbolsLength != 1.0) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" watchMyLiquidationsForSymbols() only allows one symbol at a time. To listen to several symbols call watchMyLiquidationsForSymbols() several times.".into()))));
}
messageHash = Value::Str(format!("{}{}", Value::Str("myLiquidations::".into()), symbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null)).into());
append_to_array(&mut payload, market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
}
let mut channel: Value = add(&typeId, &Value::Str(".liquidates".into()));
let mut newLiquidations: Value = self.subscribe_private(url, messageHash, payload, channel, query, &[Value::Bool(true)]).await;
if is_true(&self.newUpdates) {
return newLiquidations;
}
return self.filter_by_symbols_since_limit(self.liquidations.clone(), &[symbols, since, limit, Value::Bool(true)]);
Value::Null
}
pub fn handle_liquidation(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// future / delivery
// {
// "channel":"futures.liquidates",
// "event":"update",
// "time":1541505434,
// "time_ms":1541505434123,
// "result":[
// {
// "entry_price":209,
// "fill_price":215.1,
// "left":0,
// "leverage":0.0,
// "liq_price":213,
// "margin":0.007816722941,
// "mark_price":213,
// "order_id":4093362,
// "order_price":215.1,
// "size":-124,
// "time":1541486601,
// "time_ms":1541486601123,
// "contract":"BTC_USD",
// "user":"1040xxxx"
// }
// ]
// }
// option
// {
// "channel":"options.liquidates",
// "event":"update",
// "time":1630654851,
// "result":[
// {
// "user":"1xxxx",
// "init_margin":1190,
// "maint_margin":1042.5,
// "order_margin":0,
// "time":1639051907,
// "time_ms":1639051907000
// }
// ]
// }
//
let mut rawLiquidations: Value = (match message.get("result") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut newLiquidations: Value = Value::from(vec![]);
if (self.liquidations.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "liquidationsLimit", &[Value::Int(1000)]);
self.liquidations = ArrayCache::new(limit);
}
let mut cache: Value = self.liquidations.clone();
{
let mut i: Value = Value::Int(0);
let mut __for_first_356: bool = true;
while { if !__for_first_356 { 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_356 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawLiquidations.len() as i64) as f64) } {
let mut rawLiquidation: Value = rawLiquidations.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 liquidation: Value = self.parse_ws_liquidation(rawLiquidation, &[]);
cache.append(liquidation.clone());
let mut symbol: Value = self.safe_string_k(liquidation, "symbol", &[]);
let mut symbolLiquidations: Value = self.safe_list(cache.clone(), symbol.clone(), &[Value::from(vec![])]);
client.resolve(&[symbolLiquidations, Value::Str(format!("{}{}", Value::Str("myLiquidations::".into()), symbol).into())]);
}
}
client.resolve(&[newLiquidations, Value::Str("myLiquidations".into())]);
}
pub fn parse_ws_liquidation(&self, mut liquidation: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// future / delivery
// {
// "entry_price": 209,
// "fill_price": 215.1,
// "left": 0,
// "leverage": 0.0,
// "liq_price": 213,
// "margin": 0.007816722941,
// "mark_price": 213,
// "order_id": 4093362,
// "order_price": 215.1,
// "size": -124,
// "time": 1541486601,
// "time_ms": 1541486601123,
// "contract": "BTC_USD",
// "user": "1040xxxx"
// }
// option
// {
// "user": "1xxxx",
// "init_margin": 1190,
// "maint_margin": 1042.5,
// "order_margin": 0,
// "time": 1639051907,
// "time_ms": 1639051907000
// }
//
let mut marketId: Value = self.safe_string_k(liquidation.clone(), "contract", &[]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut timestamp: Value = self.safe_integer_k(liquidation.clone(), "time_ms", &[]);
let mut originalSize: Value = self.safe_string_k(liquidation.clone(), "size", &[]);
let mut left: Value = self.safe_string_k(liquidation.clone(), "left", &[]);
let mut amount: Value = crate::precise::Precise::stringAbs(&crate::precise::Precise::stringSub(&originalSize, &left));
return self.safe_liquidation(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), liquidation.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market.clone()]));
m.insert("contracts".to_string(), self.parse_number(amount, &[]));
m.insert("contractSize".to_string(), self.safe_number_k(market, "contractSize", &[]));
m.insert("price".to_string(), self.safe_number_k(liquidation, "fill_price", &[]));
m.insert("baseValue".to_string(), Value::Null);
m.insert("quoteValue".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
}), &[]);
Value::Null
}
pub fn handle_error_message(&self, mut client: Value, mut message: Value) -> Value {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "time": 1647274664,
// "channel": "futures.orders",
// "event": "subscribe",
// "error": { code: 2, message: "unknown contract BTC_USDT_20220318" },
// }
// {
// "time": 1647276473,
// "channel": "futures.orders",
// "event": "subscribe",
// "error": {
// "code": 4,
// "message": "{"label":"INVALID_KEY","message":"Invalid key provided"}\n"
// },
// "result": null
// }
// {
// header: {
// response_time: '1718551891329',
// status: '400',
// channel: 'spot.order_place',
// event: 'api',
// client_id: '81.34.68.6-0xc16375e2c0',
// conn_id: '9539116e0e09678f'
// },
// data: { errs: { label: 'AUTHENTICATION_FAILED', message: 'Not login' } },
// request_id: '10406147'
// }
// {
// "time": 1739853211,
// "time_ms": 1739853211201,
// "id": 1,
// "conn_id": "62f2c1dabbe186d7",
// "trace_id": "cdb02a8c0b61086b2fe6f8fad2f98c54",
// "channel": "spot.trades",
// "event": "subscribe",
// "payload": [
// "LUNARLENS_USDT",
// "ETH_USDT"
// ],
// "error": {
// "code": 2,
// "message": "unknown currency pair: LUNARLENS_USDT"
// },
// "result": {
// "status": "fail"
// },
// "requestId": "cdb02a8c0b61086b2fe6f8fad2f98c54"
// }
//
let mut data: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
let mut errs: Value = self.safe_dict_k(data, "errs", &[]);
let mut error: Value = self.safe_dict_k(message.clone(), "error", &[errs.clone()]);
let mut code: Value = self.safe_string2(error.clone(), Value::Str("code".into()), Value::Str("label".into()), &[]);
let mut id: Value = self.safe_string_n(message.clone(), Value::from(vec![Value::Str("id".into()), Value::Str("requestId".into()), Value::Str("request_id".into())]), &[]);
if (error != Value::Null) {
let mut messageHash: Value = self.safe_string(get_value(&client, &Value::Str("subscriptions".into())), id.clone(), &[]);
let _try_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
self.throw_exactly_matched_exception(crate::value::get_value_k(&self.exceptions.as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "exact"), code.clone(), json_stringify(&message));
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), code.clone(), json_stringify(&errs));
let mut errorMessage: Value = self.safe_string_k(error.clone(), "message", &[self.safe_string(errs.clone(), Value::Str("message".into()), &[])]);
self.throw_broadly_matched_exception(crate::value::get_value_k(&self.exceptions.as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "broad"), errorMessage.clone(), json_stringify(&message));
panic!("{}", crate::exchange_errors::exchange_error(json_stringify(&message)));
#[allow(unreachable_code)] { Value::Null }}));
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
client.reject(&[e, messageHash.clone()]);
if (messageHash != Value::Null) && (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash)) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
}
// remove subscriptions for watchSymbols
let mut channel: Value = (match __pro_message.get("channel").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 (channel != Value::Null) && (Value::Int(channel.as_str().and_then(|__s| __s.find(".")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
let mut parsedChannel: Value = split(&channel, &Value::Str(".".into()));
let mut payload: Value = (match __pro_message.get("payload").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
{
let mut i: Value = Value::Int(0);
let mut __for_first_357: bool = true;
while { if !__for_first_357 { 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_357 = false; i.as_f64().unwrap_or(f64::NAN) < ((payload.len() as i64) as f64) } {
let mut marketType: Value = (if (parsedChannel.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null).as_str() == Some("futures")) { Value::Str("swap".into()) } else { parsedChannel.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null) });
let mut symbol: Value = self.safe_symbol(payload.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), &[Value::Null, Value::Str("_".into()), marketType]);
let mut messageHashSymbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", parsedChannel.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null), Value::Str(":".into())).into()), symbol).into());
if (messageHashSymbol != Value::Null) && (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHashSymbol)) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHashSymbol);
}
}
}
}
}
if (id != Value::Null) && (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &id)) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &id);
}
return Value::Bool(true);
}
return Value::Bool(false);
Value::Null
}
pub fn handle_balance_subscription(&mut self, mut client: Value, mut message: Value, optional_args: &[Value]) {
let mut subscription = get_arg(optional_args, 0, Value::Null);
self.balance = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
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;
let mut channel: Value = (match __pro_message.get("channel").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut methods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("balance".to_string(), Value::Str("handle_balance_subscription".into()).clone());
m.insert("spot.order_book_update".to_string(), Value::Str("handle_order_book_subscription".into()).clone());
m.insert("futures.order_book_update".to_string(), Value::Str("handle_order_book_subscription".into()).clone());
m.insert("options.order_book_update".to_string(), Value::Str("handle_order_book_subscription".into()).clone());
m
});
let mut id: Value = (match __pro_message.get("id").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (id == Value::Null) {
return;
}
if (in_op(&methods, &channel)) {
let mut subscriptionHash: Value = self.safe_string(get_value(&client, &Value::Str("subscriptions".into())), id.clone(), &[]);
let mut subscription: Value = self.safe_value(get_value(&client, &Value::Str("subscriptions".into())), subscriptionHash, &[]);
let mut method: Value = methods.as_map().and_then(|__m| channel.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
self.dispatch_ws_handler(&method, &[client.clone(), message.clone(), subscription]);
}
if (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &id)) {
if (id != Value::Null) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &id);
}
}
}
pub fn handle_un_subscribe(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "time":1725534679,
// "time_ms":1725534679786,
// "id":2,
// "conn_id":"fac539b443fd7002",
// "trace_id":"efe1d282b630b4aa266b84bee177791a",
// "channel":"spot.trades",
// "event":"unsubscribe",
// "payload":[
// "LTC_USDT"
// ],
// "result":{
// "status":"success"
// },
// "requestId":"efe1d282b630b4aa266b84bee177791a"
// }
//
let mut id: Value = (match message.get("id") { 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 keys: Value = object_keys(&get_value(&client, &Value::Str("subscriptions".into())));
{
let mut i: Value = Value::Int(0);
let mut __for_first_359: bool = true;
while { if !__for_first_359 { 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_359 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut messageHash: 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 !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash)) {
continue;
}
if (starts_with(&messageHash, &Value::Str("unsubscribe".into()))) {
let mut subscription: Value = get_value(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
let mut subId: Value = self.safe_string_k(subscription.clone(), "id", &[]);
if (id.as_str() != subId.as_str()) {
continue;
}
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 j: Value = Value::Int(0);
let mut __for_first_358: bool = true;
while { if !__for_first_358 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_358 = false; j.as_f64().unwrap_or(f64::NAN) < ((messageHashes.len() as i64) as f64) } {
let mut unsubHash: Value = messageHashes.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut subHash: Value = subMessageHashes.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
self.clean_unsubscription(client.clone(), subHash, unsubHash, &[]);
}
}
self.clean_cache(subscription);
}
}
}
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
//
// subscribe
// {
// "time": 1649062304,
// "id": 1649062303,
// "channel": "spot.candlesticks",
// "event": "subscribe",
// "result": { status: "success" }
// }
//
// candlestick
// {
// "time": 1649063328,
// "channel": "spot.candlesticks",
// "event": "update",
// "result": {
// "t": "1649063280",
// "v": "58932.23174896",
// "c": "45966.47",
// "h": "45997.24",
// "l": "45966.47",
// "o": "45975.18",
// "n": "1m_BTC_USDT",
// "a": "1.281699"
// }
// }
//
// orders
// {
// "time": 1630654851,
// "channel": "options.orders", or futures.orders or spot.orders
// "event": "update",
// "result": [
// {
// "contract": "BTC_USDT-20211130-65000-C",
// "create_time": 1637897000,
// (...)
// ]
// }
// orderbook
// {
// "time": 1649770525,
// "channel": "spot.order_book_update",
// "event": "update",
// "result": {
// "t": 1649770525653,
// "e": "depthUpdate",
// "E": 1649770525,
// "s": "LTC_USDT",
// "U": 2622525645,
// "u": 2622525665,
// "b": [
// [Array], [Array],
// [Array], [Array],
// [Array], [Array],
// [Array], [Array],
// [Array], [Array],
// [Array]
// ],
// "a": [
// [Array], [Array],
// [Array], [Array],
// [Array], [Array],
// [Array], [Array],
// [Array], [Array],
// [Array]
// ]
// }
// }
//
// balance update
//
// {
// "time": 1653664351,
// "channel": "spot.balances",
// "event": "update",
// "result": [
// {
// "timestamp": "1653664351",
// "timestamp_ms": "1653664351017",
// "user": "10406147",
// "currency": "LTC",
// "change": "-0.0002000000000000",
// "total": "0.09986000000000000000",
// "available": "0.09986000000000000000"
// }
// ]
// }
//
if (self.handle_error_message(client.clone(), message.clone()).as_bool() == Some(true)) {
return;
}
let mut event: Option<String> = self.safe_string_k(message.clone(), "event", &[]).as_str().map(str::to_owned);
if (event.as_deref() == Some("subscribe")) {
self.handle_subscription_status(client.clone(), message.clone());
return;
}
if (event.as_deref() == Some("unsubscribe")) {
self.handle_un_subscribe(client.clone(), message.clone());
return;
}
let mut channel: Value = self.safe_string_k(message.clone(), "channel", &[Value::Str("".into())]);
// after supporting more method we can create a mapping for this
if (channel.as_str() == Some("spot.obu")) {
self.handle_order_book(client.clone(), message.clone());
return;
}
let mut channelParts: Value = split(&channel, &Value::Str(".".into()));
let mut channelType: Value = self.safe_string(channelParts, Value::Int(1), &[]);
let mut v4Methods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("usertrades".to_string(), Value::Str("handle_my_trades".into()).clone());
m.insert("candlesticks".to_string(), Value::Str("handle_ohlcv".into()).clone());
m.insert("orders".to_string(), Value::Str("handle_order".into()).clone());
m.insert("autoorders".to_string(), Value::Str("handle_order".into()).clone());
m.insert("priceorders".to_string(), Value::Str("handle_order".into()).clone());
m.insert("positions".to_string(), Value::Str("handle_positions".into()).clone());
m.insert("tickers".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("book_ticker".to_string(), Value::Str("handle_bid_ask".into()).clone());
m.insert("trades".to_string(), Value::Str("handle_trades".into()).clone());
m.insert("order_book_update".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("balances".to_string(), Value::Str("handle_balance".into()).clone());
m.insert("liquidates".to_string(), Value::Str("handle_liquidation".into()).clone());
m
});
let mut method: Value = self.safe_value(v4Methods, channelType, &[]);
if (method != Value::Null) {
self.dispatch_ws_handler(&method, &[client.clone(), message.clone()]);
}
let mut requestId: Value = self.safe_string_k(message.clone(), "request_id", &[]);
if (requestId.as_str() == Some("authenticated")) {
self.handle_authentication_message(client.clone(), message.clone());
return;
}
if (requestId != Value::Null) {
let mut data: Value = self.safe_dict_k(message.clone(), "data", &[]);
// use safeValue as result may be Array or an Object
let mut result: Value = self.safe_value_k(data, "result", &[]);
let mut ack: Value = self.safe_bool_k(message.clone(), "ack", &[]);
if (ack.as_bool() != Some(true)) {
client.resolve(&[result, requestId]);
}
}
}
pub fn get_url_by_market(&self, mut market: Value) -> Value {
let mut baseUrl: Value = get_value(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), &crate::value::get_value_k(&market, "type"));
if is_equal(&crate::value::get_value_k(&market, "contract"), &Value::Bool(true)) {
return (if (is_equal(&crate::value::get_value_k(&market, "linear"), &Value::Bool(true))) { crate::value::get_value_k(&baseUrl, "usdt") } else { crate::value::get_value_k(&baseUrl, "btc") });
} else {
return baseUrl;
}
Value::Null
}
pub fn get_type_by_market(&self, mut market: Value) -> Value {
if (market == Value::Null) {
return Value::Null;
}
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
return Value::Str("spot".into());
} else if (market.as_map().and_then(|__m| __m.get("option")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
return Value::Str("options".into());
} else {
return Value::Str("futures".into());
}
Value::Null
}
pub fn get_url_by_market_type(&self, mut type_var: Value, optional_args: &[Value]) -> Value {
let mut isInverse = get_arg(optional_args, 0, Value::Bool(false));
let mut api: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null);
let mut url: Value = self.safe_value(api, type_var.clone(), &[]);
if (type_var.as_str() == Some("swap")) || (type_var.as_str() == Some("future")) {
return (if is_true(&isInverse) { crate::value::get_value_k(&url, "btc") } else { crate::value::get_value_k(&url, "usdt") });
} else {
return url;
}
Value::Null
}
pub fn get_market_type_by_url(&self, mut url: Value) -> Value {
let mut findBy: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("op-".to_string(), Value::Str("option".into()));
m.insert("delivery".to_string(), Value::Str("future".into()));
m.insert("fx".to_string(), Value::Str("swap".into()));
m
});
let mut keys: Value = object_keys(&findBy);
{
let mut i: Value = Value::Int(0);
let mut __for_first_360: bool = true;
while { if !__for_first_360 { 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_360 = 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);
let mut value: Value = findBy.as_map().and_then(|__m| key.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
if get_index_of(&url, &key).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
return value;
}
}
}
return Value::Str("spot".into());
Value::Null
}
pub fn request_id(&mut self) -> Value {
// their support said that reqid must be an int32, not documented
self.lock_id(&[]);
let mut reqid: Value = self.sum(&[self.safe_integer_k(self.options.clone(), "reqid", &[Value::Int(0)]), Value::Int(1)]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("reqid".into(), reqid.clone()); }
self.unlock_id(&[]);
return reqid;
Value::Null
}
pub async fn subscribe_public(&mut self, mut url: Value, mut messageHash: Value, mut payload: Value, mut channel: 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 = self.request_id();
let mut time: Value = self.seconds();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("time".to_string(), time);
m.insert("channel".to_string(), channel);
m.insert("event".to_string(), Value::Str("subscribe".into()));
m.insert("payload".to_string(), payload);
m
});
if (subscription != Value::Null) {
let mut client: Value = self.client(&[url.clone()]);
if !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash)) {
let mut tempSubscriptionHash: Value = to_string_val(&requestId);
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &tempSubscriptionHash, messageHash.clone());
}
}
let mut message: Value = self.extend(request, &[params]);
return self.watch(url, messageHash.clone(), &[message.clone(), messageHash.clone(), subscription]).await;
Value::Null
}
pub async fn subscribe_public_multiple(&mut self, mut url: Value, mut messageHashes: Value, mut payload: Value, mut channel: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut requestId: Value = self.request_id();
let mut time: Value = self.seconds();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId);
m.insert("time".to_string(), time);
m.insert("channel".to_string(), channel);
m.insert("event".to_string(), Value::Str("subscribe".into()));
m.insert("payload".to_string(), payload);
m
});
let mut message: Value = self.extend(request, &[params]);
return self.watch_multiple(url, messageHashes.clone(), &[message.clone(), messageHashes.clone()]).await;
Value::Null
}
pub async fn un_subscribe_public_multiple(&mut self, mut url: Value, mut topic: Value, mut symbols: Value, mut messageHashes: Value, mut subMessageHashes: Value, mut payload: Value, mut channel: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut requestId: Value = self.request_id();
let mut time: Value = self.seconds();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("time".to_string(), time);
m.insert("channel".to_string(), channel);
m.insert("event".to_string(), Value::Str("unsubscribe".into()));
m.insert("payload".to_string(), payload);
m
});
let mut sub: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), to_string_val(&requestId));
m.insert("topic".to_string(), topic);
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("messageHashes".to_string(), messageHashes.clone());
m.insert("subMessageHashes".to_string(), subMessageHashes);
m.insert("symbols".to_string(), symbols);
m
});
let mut message: Value = self.extend(request, &[params]);
return self.watch_multiple(url, messageHashes.clone(), &[message.clone(), messageHashes.clone(), sub]).await;
Value::Null
}
pub async fn authenticate(&mut self, mut url: Value, mut messageType: Value) -> Value {
let mut channel: Value = Value::Str(format!("{}{}", messageType, Value::Str(".login".into())).into());
let mut client: Value = self.client(&[url.clone()]);
let mut messageHash: Value = Value::Str("authenticated".into());
let mut future: Value = client.reusable_future(messageHash.clone());
let mut authenticated: Value = self.safe_value(get_value(&client, &Value::Str("subscriptions".into())), messageHash.clone(), &[]);
if (authenticated == Value::Null) {
return self.request_private(url, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), channel, &[messageHash]).await;
}
return future;
Value::Null
}
pub fn handle_authentication_message(&self, mut client: Value, mut message: Value) {
let mut messageHash: Value = Value::Str("authenticated".into());
let mut future: Value = self.safe_value(get_value(&client, &Value::Str("futures".into())), messageHash, &[]);
future.resolve(&[Value::Bool(true)]);
}
pub async fn request_private(&mut self, mut url: Value, mut reqParams: Value, mut channel: Value, optional_args: &[Value]) -> Value {
let mut requestId = get_arg(optional_args, 0, Value::Null);
self.check_required_credentials(&[]);
// uid is required for some subscriptions only so it's not a part of required credentials
let mut event: Value = Value::Str("api".into());
if (requestId == Value::Null) {
let mut reqId: Value = self.request_id();
requestId = to_string_val(&reqId);
}
let mut messageHash: Value = requestId.clone();
let mut time: Value = self.seconds();
// unfortunately, PHP demands double quotes for the escaped newline symbol
let mut signatureString: Value = join(&Value::from(vec![event.clone(), channel.clone(), json_stringify(&reqParams), to_string_val(&time)]), &Value::Str("\n".into())); // eslint-disable-line quotes
let mut signature: Value = self.hmac(self.encode(signatureString), self.encode(self.secret.clone()), Value::Str("sha512".into()), &[Value::Str("hex".into())]);
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("req_id".to_string(), requestId.clone());
m.insert("timestamp".to_string(), to_string_val(&time));
m.insert("api_key".to_string(), self.apiKey.clone());
m.insert("signature".to_string(), signature);
m.insert("req_param".to_string(), reqParams);
m
});
if (channel.as_str() == Some("spot.order_place")) || (channel.as_str() == Some("futures.order_place")) {
if let Value::Dict(__d) = &mut payload { std::sync::Arc::make_mut(__d).insert("req_header".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("X-Gate-Channel-Id".to_string(), Value::Str("ccxt".into()));
m
})); }
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("time".to_string(), time);
m.insert("channel".to_string(), channel);
m.insert("event".to_string(), event);
m.insert("payload".to_string(), payload);
m
});
return self.watch(url, messageHash.clone(), &[request, messageHash.clone(), requestId]).await;
Value::Null
}
pub async fn subscribe_private(&mut self, mut url: Value, mut messageHash: Value, mut payload: Value, mut channel: Value, mut params: Value, optional_args: &[Value]) -> Value {
let mut requiresUid = get_arg(optional_args, 0, Value::Bool(false));
self.check_required_credentials(&[]);
// uid is required for some subscriptions only so it's not a part of required credentials
if is_true(&requiresUid) {
if (self.uid.clone() == Value::Null) || (Value::Int(self.uid.len() as i64).as_f64() == Some(0.0)) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires uid to subscribe".into()))));
}
let mut idArray: Value = Value::from(vec![self.uid.clone()]);
if (payload == Value::Null) {
payload = idArray.clone();
} else {
payload = self.array_concat(idArray, payload.clone());
}
}
let mut time: Value = self.seconds();
let mut event: Value = Value::Str("subscribe".into());
let mut signaturePayload: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("channel=".into()), channel).into()), Value::Str("&".into())).into()), Value::Str("event=".into())).into()), event).into()), Value::Str("&".into())).into()), Value::Str("time=".into())).into()), to_string_val(&time)).into());
let mut signature: Value = self.hmac(self.encode(signaturePayload), self.encode(self.secret.clone()), Value::Str("sha512".into()), &[Value::Str("hex".into())]);
let mut auth: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("api_key".into()));
m.insert("KEY".to_string(), self.apiKey.clone());
m.insert("SIGN".to_string(), signature);
m
});
let mut requestId: Value = self.request_id();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("time".to_string(), time);
m.insert("channel".to_string(), channel);
m.insert("event".to_string(), event);
m.insert("auth".to_string(), auth);
m
});
if (payload != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("payload".into(), payload); }
}
let mut client: Value = self.client(&[url.clone()]);
if !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash)) {
let mut tempSubscriptionHash: Value = to_string_val(&requestId);
// in case of authenticationError we will throw
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &tempSubscriptionHash, messageHash.clone());
}
let mut message: Value = self.extend(request, &[params]);
return self.watch(url, messageHash.clone(), &[message.clone(), messageHash.clone(), messageHash.clone()]).await;
Value::Null
}
}