// 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 BybitCore {
pub parent: crate::exchanges::bybit::BybitCore,
}
impl BybitCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::bybit::BybitCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = BybitCore::describe(self);
self.initialize_properties(described);
// compatibility for sandbox/testnet options in userConfig
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
/// 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 BybitCore {
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 market(&self, symbol: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::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 BybitCore {
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[1.min(args.len())..]).await,
"cancel_order_ws" => self.cancel_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"clean_params" => self.clean_params(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"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,
"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,
"get_private_type" => self.get_private_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_url_by_market_type" => self.get_url_by_market_type(&args[..]).await,
"handle_authenticate" => self.handle_authenticate(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_error_message" => self.handle_error_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_pong" => self.handle_pong(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_subscription_status" => self.handle_subscription_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_un_subscribe" => self.handle_un_subscribe(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"load_positions_snapshot" => self.load_positions_snapshot(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"parse_ws_bid_ask" => self.parse_ws_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_liquidation" => self.parse_ws_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_ohlcv" => self.parse_ws_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_trade" => self.parse_ws_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"ping" => self.ping(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"request_id" => self.request_id(),
"un_watch_my_trades" => self.un_watch_my_trades(&args[..]).await,
"un_watch_ohlcv" => self.un_watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_ohlcv_for_symbols" => self.un_watch_ohlcv_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_order_book" => self.un_watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_order_book_for_symbols" => self.un_watch_order_book_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_orders" => self.un_watch_orders(&args[..]).await,
"un_watch_positions" => self.un_watch_positions(&args[..]).await,
"un_watch_ticker" => self.un_watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_tickers" => self.un_watch_tickers(&args[..]).await,
"un_watch_topics" => self.un_watch_topics(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[6.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_liquidations" => self.watch_liquidations(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_ohlcv_for_symbols" => self.watch_ohlcv_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book_for_symbols" => self.watch_order_book_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_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_topics" => self.watch_topics(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"watch_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 BybitCore {
/// 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_order_ws" => { crate::exchange_stubs::enqueue_spawn("cancel_order_ws", args.to_vec()); crate::Value::Null },
"clean_params" => self.clean_params(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"create_order_ws" => { crate::exchange_stubs::enqueue_spawn("create_order_ws", args.to_vec()); crate::Value::Null },
"describe_data" => self.describe_data(),
"edit_order_ws" => { crate::exchange_stubs::enqueue_spawn("edit_order_ws", args.to_vec()); crate::Value::Null },
"get_private_type" => self.get_private_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_url_by_market_type" => { crate::exchange_stubs::enqueue_spawn("get_url_by_market_type", args.to_vec()); crate::Value::Null },
"handle_authenticate" => self.handle_authenticate(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_balance" => { self.handle_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_delta" => { self.handle_delta(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_deltas" => { self.handle_deltas(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_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_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_ws" => { self.handle_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_pong" => self.handle_pong(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(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)),
"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_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)),
"load_positions_snapshot" => { crate::exchange_stubs::enqueue_spawn("load_positions_snapshot", args.to_vec()); crate::Value::Null },
"parse_ws_balance" => { self.parse_ws_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]); crate::Value::Null },
"parse_ws_bid_ask" => self.parse_ws_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_liquidation" => self.parse_ws_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_ohlcv" => self.parse_ws_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_trade" => self.parse_ws_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"ping" => self.ping(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"request_id" => self.request_id(),
"set_positions_cache" => { self.set_positions_cache(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]); crate::Value::Null },
"un_watch_my_trades" => { crate::exchange_stubs::enqueue_spawn("un_watch_my_trades", args.to_vec()); crate::Value::Null },
"un_watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("un_watch_ohlcv", args.to_vec()); crate::Value::Null },
"un_watch_ohlcv_for_symbols" => { crate::exchange_stubs::enqueue_spawn("un_watch_ohlcv_for_symbols", args.to_vec()); crate::Value::Null },
"un_watch_order_book" => { crate::exchange_stubs::enqueue_spawn("un_watch_order_book", args.to_vec()); crate::Value::Null },
"un_watch_order_book_for_symbols" => { crate::exchange_stubs::enqueue_spawn("un_watch_order_book_for_symbols", args.to_vec()); crate::Value::Null },
"un_watch_orders" => { crate::exchange_stubs::enqueue_spawn("un_watch_orders", args.to_vec()); crate::Value::Null },
"un_watch_positions" => { crate::exchange_stubs::enqueue_spawn("un_watch_positions", args.to_vec()); crate::Value::Null },
"un_watch_ticker" => { crate::exchange_stubs::enqueue_spawn("un_watch_ticker", args.to_vec()); crate::Value::Null },
"un_watch_tickers" => { crate::exchange_stubs::enqueue_spawn("un_watch_tickers", args.to_vec()); crate::Value::Null },
"un_watch_topics" => { crate::exchange_stubs::enqueue_spawn("un_watch_topics", args.to_vec()); crate::Value::Null },
"un_watch_trades" => { crate::exchange_stubs::enqueue_spawn("un_watch_trades", args.to_vec()); crate::Value::Null },
"un_watch_trades_for_symbols" => { crate::exchange_stubs::enqueue_spawn("un_watch_trades_for_symbols", args.to_vec()); crate::Value::Null },
"watch_balance" => { crate::exchange_stubs::enqueue_spawn("watch_balance", args.to_vec()); crate::Value::Null },
"watch_bids_asks" => { crate::exchange_stubs::enqueue_spawn("watch_bids_asks", args.to_vec()); crate::Value::Null },
"watch_liquidations" => { crate::exchange_stubs::enqueue_spawn("watch_liquidations", args.to_vec()); crate::Value::Null },
"watch_my_trades" => { crate::exchange_stubs::enqueue_spawn("watch_my_trades", args.to_vec()); crate::Value::Null },
"watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("watch_ohlcv", args.to_vec()); crate::Value::Null },
"watch_ohlcv_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_ohlcv_for_symbols", args.to_vec()); crate::Value::Null },
"watch_order_book" => { crate::exchange_stubs::enqueue_spawn("watch_order_book", args.to_vec()); crate::Value::Null },
"watch_order_book_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_order_book_for_symbols", args.to_vec()); crate::Value::Null },
"watch_orders" => { crate::exchange_stubs::enqueue_spawn("watch_orders", args.to_vec()); crate::Value::Null },
"watch_positions" => { crate::exchange_stubs::enqueue_spawn("watch_positions", args.to_vec()); crate::Value::Null },
"watch_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_topics" => { crate::exchange_stubs::enqueue_spawn("watch_topics", 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 BybitCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for BybitCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl BybitCore {
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("createOrderWs".to_string(), Value::Bool(true));
m.insert("editOrderWs".to_string(), Value::Bool(true));
m.insert("fetchOpenOrdersWs".to_string(), Value::Bool(false));
m.insert("fetchOrderWs".to_string(), Value::Bool(false));
m.insert("cancelOrderWs".to_string(), Value::Bool(true));
m.insert("cancelOrdersWs".to_string(), Value::Bool(false));
m.insert("cancelAllOrdersWs".to_string(), Value::Bool(false));
m.insert("fetchTradesWs".to_string(), Value::Bool(false));
m.insert("fetchBalanceWs".to_string(), Value::Bool(false));
m.insert("watchBalance".to_string(), Value::Bool(true));
m.insert("watchBidsAsks".to_string(), Value::Bool(true));
m.insert("watchLiquidations".to_string(), Value::Bool(true));
m.insert("watchLiquidationsForSymbols".to_string(), Value::Bool(false));
m.insert("watchMyLiquidations".to_string(), Value::Bool(false));
m.insert("watchMyLiquidationsForSymbols".to_string(), Value::Bool(false));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchOHLCV".to_string(), Value::Bool(true));
m.insert("watchOHLCVForSymbols".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOrderBookForSymbols".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m.insert("watchPositions".to_string(), Value::Bool(true));
m.insert("watchTradesForSymbols".to_string(), Value::Bool(true));
m.insert("unWatchTicker".to_string(), Value::Bool(true));
m.insert("unWatchTickers".to_string(), Value::Bool(true));
m.insert("unWatchOHLCV".to_string(), Value::Bool(true));
m.insert("unWatchOHLCVForSymbols".to_string(), Value::Bool(true));
m.insert("unWatchOrderBook".to_string(), Value::Bool(true));
m.insert("unWatchOrderBookForSymbols".to_string(), Value::Bool(true));
m.insert("unWatchTrades".to_string(), Value::Bool(true));
m.insert("unWatchTradesForSymbols".to_string(), Value::Bool(true));
m.insert("unWatchMyTrades".to_string(), Value::Bool(true));
m.insert("unWatchOrders".to_string(), Value::Bool(true));
m.insert("unWatchPositions".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("wss://stream.{hostname}/v5/public/spot".into()));
m.insert("inverse".to_string(), Value::Str("wss://stream.{hostname}/v5/public/inverse".into()));
m.insert("option".to_string(), Value::Str("wss://stream.{hostname}/v5/public/option".into()));
m.insert("linear".to_string(), Value::Str("wss://stream.{hostname}/v5/public/linear".into()));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("unified".to_string(), Value::Str("wss://stream.{hostname}/v5/private".into()));
m.insert("nonUnified".to_string(), Value::Str("wss://stream.{hostname}/spot/private/v3".into()));
m
}));
m.insert("contract".to_string(), Value::Str("wss://stream.{hostname}/v5/private".into()));
m.insert("usdc".to_string(), Value::Str("wss://stream.{hostname}/trade/option/usdc/private/v1".into()));
m.insert("trade".to_string(), Value::Str("wss://stream.bybit.com/v5/trade".into()));
m
}));
m
}));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("wss://stream-testnet.{hostname}/v5/public/spot".into()));
m.insert("inverse".to_string(), Value::Str("wss://stream-testnet.{hostname}/v5/public/inverse".into()));
m.insert("linear".to_string(), Value::Str("wss://stream-testnet.{hostname}/v5/public/linear".into()));
m.insert("option".to_string(), Value::Str("wss://stream-testnet.{hostname}/v5/public/option".into()));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("unified".to_string(), Value::Str("wss://stream-testnet.{hostname}/v5/private".into()));
m.insert("nonUnified".to_string(), Value::Str("wss://stream-testnet.{hostname}/spot/private/v3".into()));
m
}));
m.insert("contract".to_string(), Value::Str("wss://stream-testnet.{hostname}/v5/private".into()));
m.insert("usdc".to_string(), Value::Str("wss://stream-testnet.{hostname}/trade/option/usdc/private/v1".into()));
m.insert("trade".to_string(), Value::Str("wss://stream-testnet.bybit.com/v5/trade".into()));
m
}));
m
}));
m
}));
m.insert("demotrading".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("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("wss://stream.{hostname}/v5/public/spot".into()));
m.insert("inverse".to_string(), Value::Str("wss://stream.{hostname}/v5/public/inverse".into()));
m.insert("option".to_string(), Value::Str("wss://stream.{hostname}/v5/public/option".into()));
m.insert("linear".to_string(), Value::Str("wss://stream.{hostname}/v5/public/linear".into()));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("unified".to_string(), Value::Str("wss://stream-demo.{hostname}/v5/private".into()));
m.insert("nonUnified".to_string(), Value::Str("wss://stream-demo.{hostname}/spot/private/v3".into()));
m
}));
m.insert("contract".to_string(), Value::Str("wss://stream-demo.{hostname}/v5/private".into()));
m.insert("usdc".to_string(), Value::Str("wss://stream-demo.{hostname}/trade/option/usdc/private/v1".into()));
m.insert("trade".to_string(), Value::Str("wss://stream-demo.bybit.com/v5/trade".into()));
m
}));
m
}));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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("watchPositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fetchPositionsSnapshot".to_string(), Value::Bool(true));
m.insert("awaitPositionsSnapshot".to_string(), Value::Bool(true));
m
}));
m.insert("watchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("execType".to_string(), Value::from(vec![Value::Str("Trade".into()), Value::Str("AdlTrade".into()), Value::Str("BustTrade".into()), Value::Str("Settle".into())]));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".into()));
m.insert("3m".to_string(), Value::Str("3m".into()));
m.insert("5m".to_string(), Value::Str("5m".into()));
m.insert("15m".to_string(), Value::Str("15m".into()));
m.insert("30m".to_string(), Value::Str("30m".into()));
m.insert("1h".to_string(), Value::Str("1h".into()));
m.insert("2h".to_string(), Value::Str("2h".into()));
m.insert("4h".to_string(), Value::Str("4h".into()));
m.insert("6h".to_string(), Value::Str("6h".into()));
m.insert("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m.insert("1w".to_string(), Value::Str("1w".into()));
m.insert("1M".to_string(), Value::Str("1M".into()));
m
}));
m
}));
m.insert("contract".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1".into()));
m.insert("3m".to_string(), Value::Str("3".into()));
m.insert("5m".to_string(), Value::Str("5".into()));
m.insert("15m".to_string(), Value::Str("15".into()));
m.insert("30m".to_string(), Value::Str("30".into()));
m.insert("1h".to_string(), Value::Str("60".into()));
m.insert("2h".to_string(), Value::Str("120".into()));
m.insert("4h".to_string(), Value::Str("240".into()));
m.insert("6h".to_string(), Value::Str("360".into()));
m.insert("12h".to_string(), Value::Str("720".into()));
m.insert("1d".to_string(), Value::Str("D".into()));
m.insert("1w".to_string(), Value::Str("W".into()));
m.insert("1M".to_string(), Value::Str("M".into()));
m
}));
m
}));
m
}));
m.insert("streaming".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ping".to_string(), Value::Str("ping".into()).clone());
m.insert("keepAlive".to_string(), Value::Int(18000));
m
}));
m
});
Value::Null
}
pub fn request_id(&mut self) -> Value {
self.lock_id(&[]);
let mut requestId: Value = self.sum(&[self.safe_integer_k(self.options.clone(), "requestId", &[Value::Int(0)]), Value::Int(1)]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("requestId".into(), requestId.clone()); }
self.unlock_id(&[]);
return requestId;
Value::Null
}
pub async fn get_url_by_market_type(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut isPrivate = get_arg(optional_args, 1, Value::Bool(false));
let mut method = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut accessibility: Value = Value::Str("public".into());
if is_true(&isPrivate) {
accessibility = Value::Str("private".into());
}
let mut methodValue: Value = (if (method == Value::Null) { Value::Str("".into()) } else { method });
let mut isUsdcSettled: Value = Value::Null;
let mut isSpot: Value = Value::Null;
let mut type_var: Value = Value::Null;
let mut market: Value = Value::Null;
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
if (symbol != Value::Null) {
market = self.market(symbol);
isUsdcSettled = Value::Bool(market.as_map().and_then(|__m| __m.get("settle")).cloned().unwrap_or(Value::Null).as_str() == Some("USDC"));
type_var = self.safe_string_k(market.clone(), "type", &[]);
} else {
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(methodValue.clone(), &[Value::Null, params.clone()]);
let mut marketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
type_var = marketType;
let mut defaultSettle: Value = self.safe_string_k(self.options.clone(), "defaultSettle", &[]);
defaultSettle = self.safe_string2(paramsMarketType, Value::Str("settle".into()), Value::Str("defaultSettle".into()), &[defaultSettle.clone()]);
isUsdcSettled = (Value::Bool(defaultSettle.as_str() == Some("USDC")));
}
isSpot = (Value::Bool(type_var.as_str() == Some("spot")));
if is_true(&isPrivate) {
let mut unified: Value = self.parent.is_unified_enabled(&[]).await;
let mut isUnifiedMargin: Value = self.safe_bool(unified.clone(), Value::Int(0), &[Value::Bool(false)]);
let mut isUnifiedAccount: Value = self.safe_bool(unified, Value::Int(1), &[Value::Bool(false)]);
if isUsdcSettled.as_bool() == Some(true) && (!(isUnifiedMargin.as_bool() == Some(true))) && (!(isUnifiedAccount.as_bool() == Some(true))) {
url = crate::value::get_value_k(&get_value(&url, &accessibility), "usdc");
} else {
url = crate::value::get_value_k(&get_value(&url, &accessibility), "contract");
}
} else {
if isSpot.as_bool() == Some(true) {
url = crate::value::get_value_k(&get_value(&url, &accessibility), "spot");
} else if (type_var.as_str() == Some("swap")) || (type_var.as_str() == Some("future")) {
let mut subType: Value = self.handle_sub_type_and_params(methodValue, &[market, params, Value::Str("linear".into())]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
url = get_value(&get_value(&url, &accessibility), &subType);
} else {
// option
url = crate::value::get_value_k(&get_value(&url, &accessibility), "option");
}
}
url = self.implode_hostname(url.clone());
return url;
Value::Null
}
pub fn clean_params(&self, mut params: Value) -> Value {
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("type".into()), Value::Str("subType".into()), Value::Str("settle".into()), Value::Str("defaultSettle".into()), Value::Str("unifiedMargin".into())]), &[]);
return paramsOmitted;
Value::Null
}
/*
* @method
* @name bybit#createOrderWs
* @description create a trade order
* @see https://bybit-exchange.github.io/docs/v5/order/create-order
* @see https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline#createamendcancel-order
* @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 currency you want to trade in units of 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
* @param {string} [params.timeInForce] "GTC", "IOC", "FOK"
* @param {bool} [params.postOnly] true or false whether the order is post-only
* @param {bool} [params.reduceOnly] true or false whether the order is reduce-only
* @param {string} [params.positionIdx] *contracts only* 0 for one-way mode, 1 buy side of hedged mode, 2 sell side of hedged mode
* @param {boolean} [params.isLeverage] *unified spot only* false then spot trading true then margin trading
* @param {string} [params.tpslMode] *contract only* 'full' or 'partial'
* @param {string} [params.mmp] *option only* market maker protection
* @param {string} [params.triggerDirection] *contract only* the direction for trigger orders, 'ascending' or 'descending'
* @param {float} [params.triggerPrice] The price at which a trigger order is triggered at
* @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 {object} [params.takeProfit] *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered
* @param {float} [params.takeProfit.triggerPrice] take profit trigger price
* @param {object} [params.stopLoss] *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered
* @param {float} [params.stopLoss.triggerPrice] stop loss trigger price
* @param {string} [params.trailingAmount] the quote amount to trail away from the current market price
* @param {string} [params.trailingTriggerPrice] the price to trigger a trailing order, default uses the price argument
* @returns {object} 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 orderRequest: Value = self.parent.create_order_request(symbol, type_var, side, amount, &[price, params, Value::Bool(true)]);
let mut url: Value = self.implode_hostname(crate::value::get_value_k(&crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "private"), "trade"));
self.authenticate(url.clone(), &[]).await;
let mut requestId: Value = Value::Str(format!("{}", self.request_id()).into());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("op".to_string(), Value::Str("order.create".into()));
m.insert("reqId".to_string(), requestId.clone());
m.insert("args".to_string(), Value::from(vec![orderRequest]));
m.insert("header".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("X-BAPI-TIMESTAMP".to_string(), Value::Str(format!("{}", self.milliseconds()).into()));
m.insert("X-BAPI-RECV-WINDOW".to_string(), to_string_val(&get_value(&self.options, &Value::Str("recvWindow".into()))));
m
}));
m
});
return self.watch(url, requestId.clone(), &[request, requestId.clone(), Value::Bool(true)]).await;
Value::Null
}
/*
* @method
* @name bybit#editOrderWs
* @description edit a trade order
* @see https://bybit-exchange.github.io/docs/v5/order/amend-order
* @see https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline#createamendcancel-order
* @param {string} id cancel 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 currency you want to trade in units of 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
* @param {float} [params.triggerPrice] The price that a trigger order is triggered at
* @param {float} [params.stopLossPrice] The price that a stop loss order is triggered at
* @param {float} [params.takeProfitPrice] The price that a take profit order is triggered at
* @param {object} [params.takeProfit] *takeProfit object in params* containing the triggerPrice that the attached take profit order will be triggered
* @param {float} [params.takeProfit.triggerPrice] take profit trigger price
* @param {object} [params.stopLoss] *stopLoss object in params* containing the triggerPrice that the attached stop loss order will be triggered
* @param {float} [params.stopLoss.triggerPrice] stop loss trigger price
* @param {string} [params.triggerBy] 'IndexPrice', 'MarkPrice' or 'LastPrice', default is 'LastPrice', required if no initial value for triggerPrice
* @param {string} [params.slTriggerBy] 'IndexPrice', 'MarkPrice' or 'LastPrice', default is 'LastPrice', required if no initial value for stopLoss
* @param {string} [params.tpTriggerby] 'IndexPrice', 'MarkPrice' or 'LastPrice', default is 'LastPrice', required if no initial value for takeProfit
* @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 orderRequest: Value = self.parent.edit_order_request(id, symbol, type_var, side, &[amount, price, params]);
let mut url: Value = self.implode_hostname(crate::value::get_value_k(&crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "private"), "trade"));
self.authenticate(url.clone(), &[]).await;
let mut requestId: Value = Value::Str(format!("{}", self.request_id()).into());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("op".to_string(), Value::Str("order.amend".into()));
m.insert("reqId".to_string(), requestId.clone());
m.insert("args".to_string(), Value::from(vec![orderRequest]));
m.insert("header".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("X-BAPI-TIMESTAMP".to_string(), Value::Str(format!("{}", self.milliseconds()).into()));
m.insert("X-BAPI-RECV-WINDOW".to_string(), to_string_val(&get_value(&self.options, &Value::Str("recvWindow".into()))));
m
}));
m
});
return self.watch(url, requestId.clone(), &[request, requestId.clone(), Value::Bool(true)]).await;
Value::Null
}
/*
* @method
* @name bybit#cancelOrderWs
* @description cancels an open order
* @see https://bybit-exchange.github.io/docs/v5/order/cancel-order
* @see https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline#createamendcancel-order
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.trigger] *spot only* whether the order is a trigger order
* @param {string} [params.orderFilter] *spot only* 'Order' or 'StopOrder' or 'tpslOrder'
* @returns {object} 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;
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrderWs() requires a symbol argument".into()))));
}
let mut orderRequest: Value = self.parent.cancel_order_request(id, &[symbol, params]);
let mut url: Value = self.implode_hostname(crate::value::get_value_k(&crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "private"), "trade"));
self.authenticate(url.clone(), &[]).await;
let mut requestId: Value = Value::Str(format!("{}", self.request_id()).into());
if (matches!(&orderRequest, Value::Dict(__d) if __d.contains_key("orderFilter"))) {
remove(&mut orderRequest, &Value::Str("orderFilter".into()));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("op".to_string(), Value::Str("order.cancel".into()));
m.insert("reqId".to_string(), requestId.clone());
m.insert("args".to_string(), Value::from(vec![orderRequest]));
m.insert("header".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("X-BAPI-TIMESTAMP".to_string(), Value::Str(format!("{}", self.milliseconds()).into()));
m.insert("X-BAPI-RECV-WINDOW".to_string(), to_string_val(&get_value(&self.options, &Value::Str("recvWindow".into()))));
m
}));
m
});
return self.watch(url, requestId.clone(), &[request, requestId.clone(), Value::Bool(true)]).await;
Value::Null
}
/*
* @method
* @name bybit#watchTicker
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/ticker
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/etp-ticker
* @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);
let mut symbolValue: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbolValue).into());
let mut url: Value = self.get_url_by_market_type(&[symbolValue, Value::Bool(false), Value::Str("watchTicker".into()), params.clone()]).await;
let mut paramsValue: Value = self.clean_params(params);
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchTicker", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut topic: Value = self.safe_string_k(options, "name", &[Value::Str("tickers".into())]);
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) && (topic.as_str() != Some("tickers")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" watchTicker() only supports name tickers for contract markets".into()))));
}
topic = Value::Str(format!("{}{}", topic, Value::Str(format!("{}{}", Value::Str(".".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into())).into());
let mut topics: Value = Value::from(vec![topic]);
return self.watch_topics(url, Value::from(vec![messageHash]), topics, &[paramsValue]).await;
Value::Null
}
/*
* @method
* @name bybit#watchTickers
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/ticker
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/etp-ticker
* @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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsValue: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(false)]);
let mut messageHashes: Vec<Value> = Vec::new();
let mut url: Value = self.get_url_by_market_type(&[symbolsValue.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), Value::Bool(false), Value::Str("watchTickers".into()), params.clone()]).await;
let mut paramsValue: Value = self.clean_params(params);
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchTickers", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut topic: Value = self.safe_string_k(options, "name", &[Value::Str("tickers".into())]);
let mut marketIds: Value = self.market_ids(&[symbolsValue.clone()]);
let mut topics: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_185: bool = true;
while { if !__for_first_185 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_185 = false; i.as_f64().unwrap_or(f64::NAN) < ((marketIds.len() as i64) as f64) } {
let mut marketId: Value = marketIds.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
topics.push(Value::Str(format!("{}{}", Value::Str(format!("{}{}", topic, Value::Str(".".into())).into()), marketId).into()));
messageHashes.push(Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbolsValue.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()));
}
}
let mut ticker: Value = self.watch_topics(url, Value::from(messageHashes), Value::from(topics), &[paramsValue]).await;
if self.newUpdates.as_bool() == Some(true) {
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut tickerSymbol: Value = self.safe_string_k(ticker.clone(), "symbol", &[]);
if (tickerSymbol != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&tickerSymbol), ticker); }
}
return result;
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".into()), &[symbolsValue]);
Value::Null
}
/*
* @method
* @name bybit#unWatchTickers
* @description unWatches a price ticker
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/ticker
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/etp-ticker
* @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 un_watch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsValue: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(false)]);
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchTickers", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut topic: Value = self.safe_string_k(options, "name", &[Value::Str("tickers".into())]);
let mut messageHashes: Vec<Value> = Vec::new();
let mut subMessageHashes: Vec<Value> = Vec::new();
let mut marketIds: Value = self.market_ids(&[symbolsValue.clone()]);
let mut topics: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_186: bool = true;
while { if !__for_first_186 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_186 = false; i.as_f64().unwrap_or(f64::NAN) < ((marketIds.len() as i64) as f64) } {
let mut marketId: Value = marketIds.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut symbol: Value = symbolsValue.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);
topics.push(Value::Str(format!("{}{}", Value::Str(format!("{}{}", topic, Value::Str(".".into())).into()), marketId).into()));
subMessageHashes.push(Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbol).into()));
messageHashes.push(Value::Str(format!("{}{}", Value::Str("unsubscribe:ticker:".into()), symbol).into()));
}
}
let mut url: Value = self.get_url_by_market_type(&[symbolsValue.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), Value::Bool(false), Value::Str("watchTickers".into()), params.clone()]).await;
return self.un_watch_topics(url, Value::Str("ticker".into()), symbolsValue, Value::from(messageHashes), Value::from(subMessageHashes), Value::from(topics), &[params]).await;
Value::Null
}
/*
* @method
* @name bybit#unWatchTicker
* @description unWatches a price ticker
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/ticker
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/etp-ticker
* @param {string[]} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn un_watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.un_watch_tickers(&[Value::from(vec![symbol]), params]).await;
Value::Null
}
pub fn handle_ticker(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// linear
// {
// "topic": "tickers.BTCUSDT",
// "type": "snapshot",
// "data": {
// "symbol": "BTCUSDT",
// "tickDirection": "PlusTick",
// "price24hPcnt": "0.017103",
// "lastPrice": "17216.00",
// "prevPrice24h": "16926.50",
// "highPrice24h": "17281.50",
// "lowPrice24h": "16915.00",
// "prevPrice1h": "17238.00",
// "markPrice": "17217.33",
// "indexPrice": "17227.36",
// "openInterest": "68744.761",
// "openInterestValue": "1183601235.91",
// "turnover24h": "1570383121.943499",
// "volume24h": "91705.276",
// "nextFundingTime": "1673280000000",
// "fundingRate": "-0.000212",
// "bid1Price": "17215.50",
// "bid1Size": "84.489",
// "ask1Price": "17216.00",
// "ask1Size": "83.020"
// },
// "cs": 24987956059,
// "ts": 1673272861686
// }
//
// option
// {
// "id": "tickers.BTC-6JAN23-17500-C-2480334983-1672917511074",
// "topic": "tickers.BTC-6JAN23-17500-C",
// "ts": 1672917511074,
// "data": {
// "symbol": "BTC-6JAN23-17500-C",
// "bidPrice": "0",
// "bidSize": "0",
// "bidIv": "0",
// "askPrice": "10",
// "askSize": "5.1",
// "askIv": "0.514",
// "lastPrice": "10",
// "highPrice24h": "25",
// "lowPrice24h": "5",
// "markPrice": "7.86976724",
// "indexPrice": "16823.73",
// "markPriceIv": "0.4896",
// "underlyingPrice": "16815.1",
// "openInterest": "49.85",
// "turnover24h": "446802.8473",
// "volume24h": "26.55",
// "totalVolume": "86",
// "totalTurnover": "1437431",
// "delta": "0.047831",
// "gamma": "0.00021453",
// "vega": "0.81351067",
// "theta": "-19.9115368",
// "predictedDeliveryPrice": "0",
// "change24h": "-0.33333334"
// },
// "type": "snapshot"
// }
//
// spot
// {
// "topic": "tickers.BTCUSDT",
// "ts": 1673853746002,
// "type": "snapshot",
// "cs": 2588407389,
// "data": {
// "symbol": "BTCUSDT",
// "lastPrice": "21109.77",
// "highPrice24h": "21426.99",
// "lowPrice24h": "20575",
// "prevPrice24h": "20704.93",
// "volume24h": "6780.866843",
// "turnover24h": "141946527.22907118",
// "price24hPcnt": "0.0196",
// "usdIndexPrice": "21120.2400136"
// }
// }
//
// lt ticker
// {
// "topic": "tickers_lt.EOS3LUSDT",
// "ts": 1672325446847,
// "type": "snapshot",
// "data": {
// "symbol": "EOS3LUSDT",
// "lastPrice": "0.41477848043290448",
// "highPrice24h": "0.435285472510871305",
// "lowPrice24h": "0.394601507960931382",
// "prevPrice24h": "0.431502290172376349",
// "price24hPcnt": "-0.0388"
// }
// }
// swap delta
// {
// "topic":"tickers.AAVEUSDT",
// "type":"delta",
// "data":{
// "symbol":"AAVEUSDT",
// "bid1Price":"112.89",
// "bid1Size":"2.12",
// "ask1Price":"112.90",
// "ask1Size":"5.02"
// },
// "cs":78039939929,
// "ts":1709210212704
// }
//
let mut topic: Value = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
let mut updateType: Option<String> = (match message.get("type") { 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()) }).as_str().map(str::to_owned);
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut isSpot: bool = self.safe_string_k(data.clone(), "usdIndexPrice", &[]) != Value::Null;
let mut type_var: Value = Value::Str("contract".into());
if isSpot {
type_var = Value::Str("spot".into());
}
let mut symbol: Value = Value::Null;
let mut parsed: Value = Value::Null;
if (updateType.as_deref() == Some("snapshot")) {
parsed = self.parse_ticker(data.clone(), &[]);
symbol = self.safe_string_k(parsed.clone(), "symbol", &[]);
} else if (updateType.as_deref() == Some("delta")) {
let mut topicParts: Value = Value::Array(topic.as_str().map(|__s| __s.split(".").map(|__p| Value::Str(__p.to_string().into())).collect()).unwrap_or_default());
let mut topicLength: Value = Value::Int(topicParts.len() as i64);
let mut marketId: Value = self.safe_string(topicParts, (match (&(topicLength), &(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 }), &[]);
let mut market: Value = self.safe_market(&[marketId, Value::Null, Value::Null, type_var]);
symbol = self.safe_string_k(market, "symbol", &[]);
// update the info in place
let mut ticker: Value = self.safe_dict(self.tickers.clone(), symbol.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawTicker: Value = self.safe_dict_k(ticker, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut merged: Value = self.extend(rawTicker, &[data]);
parsed = self.parse_ticker(merged, &[]);
}
if (parsed == Value::Null) || (symbol == Value::Null) {
return;
}
let mut timestamp: Value = (match message.get("ts") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
add_element_to_object(&mut parsed, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut parsed, &Value::Str("datetime".into()), self.iso8601(timestamp));
if let Value::Dict(__d) = &mut self.tickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), parsed); }
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbol).into());
client.resolve(&[self.tickers.as_map().and_then(|__m| symbol.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null), messageHash]);
}
/*
* @method
* @name bybit#watchBidsAsks
* @description watches best bid & ask for symbols
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/orderbook
* @param {string[]} symbols unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_bids_asks(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsValue: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(false)]);
let mut messageHashes: Vec<Value> = Vec::new();
let mut url: Value = self.get_url_by_market_type(&[symbolsValue.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), Value::Bool(false), Value::Str("watchBidsAsks".into()), params.clone()]).await;
let mut paramsValue: Value = self.clean_params(params);
let mut marketIds: Value = self.market_ids(&[symbolsValue.clone()]);
let mut topics: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_187: bool = true;
while { if !__for_first_187 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_187 = false; i.as_f64().unwrap_or(f64::NAN) < ((marketIds.len() as i64) as f64) } {
let mut marketId: Value = marketIds.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut topic: Value = Value::Str(format!("{}{}", Value::Str("orderbook.1.".into()), marketId).into());
topics.push(topic);
messageHashes.push(Value::Str(format!("{}{}", Value::Str("bidask:".into()), symbolsValue.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()));
}
}
let mut ticker: Value = self.watch_topics(url, Value::from(messageHashes), Value::from(topics), &[paramsValue]).await;
if self.newUpdates.as_bool() == Some(true) {
return ticker;
}
return self.filter_by_array(self.bidsasks.clone(), Value::Str("symbol".into()), &[symbolsValue]);
Value::Null
}
pub fn parse_ws_bid_ask(&self, mut orderbook: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut timestamp: Value = self.safe_integer_k(orderbook.clone(), "timestamp", &[]);
let mut bids: Value = self.sort_by(self.aggregate(get_value(&orderbook, &Value::Str("bids".into()))), Value::Int(0), &[]);
let mut asks: Value = self.sort_by(self.aggregate(get_value(&orderbook, &Value::Str("asks".into()))), Value::Int(0), &[]);
let mut bestBid: Value = self.safe_list(bids, Value::Int(0), &[Value::from(vec![])]);
let mut bestAsk: Value = self.safe_list(asks, Value::Int(0), &[Value::from(vec![])]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_string_k(market.clone(), "symbol", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("ask".to_string(), self.safe_number(bestAsk.clone(), Value::Int(0), &[]));
m.insert("askVolume".to_string(), self.safe_number(bestAsk, Value::Int(1), &[]));
m.insert("bid".to_string(), self.safe_number(bestBid.clone(), Value::Int(0), &[]));
m.insert("bidVolume".to_string(), self.safe_number(bestBid, Value::Int(1), &[]));
m.insert("info".to_string(), orderbook);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name bybit#watchOHLCV
* @description watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/kline
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/etp-kline
* @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 let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("callerMethodName".into(), Value::Str("watchOHLCV".into())); }
let mut result: Value = self.watch_ohlcv_for_symbols(Value::from(vec![Value::from(vec![symbol.clone(), timeframe.clone()])]), &[since, limit, params]).await;
return get_value(&get_value(&result, &symbol), &timeframe);
Value::Null
}
/*
* @method
* @name bybit#watchOHLCVForSymbols
* @description watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/kline
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/etp-kline
* @param {string[][]} symbolsAndTimeframes array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]
* @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 {object} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn watch_ohlcv_for_symbols(&mut self, mut symbolsAndTimeframes: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbols: Value = self.get_list_from_object_values(symbolsAndTimeframes.clone(), Value::Int(0));
let mut marketSymbols: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(false), Value::Bool(true), Value::Bool(true)]);
let mut firstSymbol: Value = marketSymbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut url: Value = self.get_url_by_market_type(&[firstSymbol, Value::Bool(false), Value::Str("watchOHLCVForSymbols".into()), params.clone()]).await;
let mut rawHashes: Vec<Value> = Vec::new();
let mut messageHashes: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_188: bool = true;
while { if !__for_first_188 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_188 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolsAndTimeframes.len() as i64) as f64) } {
let mut data: Value = symbolsAndTimeframes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(data.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
let mut symbolString: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut unfiedTimeframe: Value = data.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut timeframeId: Value = self.safe_string(self.timeframes.clone(), unfiedTimeframe.clone(), &[unfiedTimeframe.clone()]);
rawHashes.push(Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("kline.".into()), timeframeId).into()), Value::Str(".".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
messageHashes.push(Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("ohlcv::".into()), symbolString).into()), Value::Str("::".into())).into()), unfiedTimeframe).into()));
}
}
let mut symboltimeframestoredVariable = self.watch_topics(url, Value::from(messageHashes), Value::from(rawHashes), &[params]).await;
let mut symbol: Value = get_value(&symboltimeframestoredVariable, &Value::Int(0));
let mut timeframe: Value = get_value(&symboltimeframestoredVariable, &Value::Int(1));
let mut stored: Value = get_value(&symboltimeframestoredVariable, &Value::Int(2));
let mut limitResolved: Value = limit.clone();
if self.newUpdates.as_bool() == Some(true) {
limitResolved = stored.get_limit(symbol.clone(), limit);
}
let mut filtered: Value = self.filter_by_since_limit(stored, &[since, limitResolved, Value::Int(0), Value::Bool(true)]);
return self.create_ohlcv_object(symbol, timeframe, filtered);
Value::Null
}
/*
* @method
* @name bybit#unWatchOHLCVForSymbols
* @description unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/kline
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/etp-kline
* @param {string[][]} symbolsAndTimeframes array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn un_watch_ohlcv_for_symbols(&mut self, mut symbolsAndTimeframes: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbols: Value = self.get_list_from_object_values(symbolsAndTimeframes.clone(), Value::Int(0));
let mut marketSymbols: Value = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false), Value::Bool(true), Value::Bool(true)]);
let mut firstSymbol: Value = marketSymbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut url: Value = self.get_url_by_market_type(&[firstSymbol, Value::Bool(false), Value::Str("watchOHLCVForSymbols".into()), params.clone()]).await;
let mut rawHashes: Vec<Value> = Vec::new();
let mut subMessageHashes: Vec<Value> = Vec::new();
let mut messageHashes: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_189: bool = true;
while { if !__for_first_189 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_189 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolsAndTimeframes.len() as i64) as f64) } {
let mut data: Value = symbolsAndTimeframes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(data.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
let mut symbolString: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut unfiedTimeframe: Value = data.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut timeframeId: Value = self.safe_string(self.timeframes.clone(), unfiedTimeframe.clone(), &[unfiedTimeframe.clone()]);
rawHashes.push(Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("kline.".into()), timeframeId).into()), Value::Str(".".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
subMessageHashes.push(Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("ohlcv::".into()), symbolString).into()), Value::Str("::".into())).into()), unfiedTimeframe).into()));
messageHashes.push(Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("unsubscribe::ohlcv::".into()), symbolString).into()), Value::Str("::".into())).into()), unfiedTimeframe).into()));
}
}
let mut subExtension: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbolsAndTimeframes".to_string(), symbolsAndTimeframes);
m
});
return self.un_watch_topics(url, Value::Str("ohlcv".into()), symbols, Value::from(messageHashes), Value::from(subMessageHashes), Value::from(rawHashes), &[params, subExtension]).await;
Value::Null
}
/*
* @method
* @name bybit#unWatchOHLCV
* @description unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/kline
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/etp-kline
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn un_watch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("callerMethodName".into(), Value::Str("watchOHLCV".into())); }
return self.un_watch_ohlcv_for_symbols(Value::from(vec![Value::from(vec![symbol, timeframe])]), &[params]).await;
Value::Null
}
pub fn handle_ohlcv(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "topic": "kline.5.BTCUSDT",
// "data": [
// {
// "start": 1672324800000,
// "end": 1672325099999,
// "interval": "5",
// "open": "16649.5",
// "close": "16677",
// "high": "16677",
// "low": "16608",
// "volume": "2.081",
// "turnover": "34666.4005",
// "confirm": false,
// "timestamp": 1672324988882
// }
// ],
// "ts": 1672324988882,
// "type": "snapshot"
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut topic: Value = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
let mut topicParts: Value = Value::Array(topic.as_str().map(|__s| __s.split(".").map(|__p| Value::Str(__p.to_string().into())).collect()).unwrap_or_default());
let mut topicLength: Value = Value::Int(topicParts.len() as i64);
let mut timeframeId: Value = self.safe_string(topicParts.clone(), Value::Int(1), &[]);
let mut timeframe: Value = self.find_timeframe(timeframeId, &[]);
if (timeframe == Value::Null) {
return;
}
let mut marketId: Value = self.safe_string(topicParts, (match (&(topicLength), &(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 }), &[]);
let mut isSpot: bool = Value::Int(get_value(&client, &Value::Str("url".into())).as_str().and_then(|__s| __s.find("spot")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64);
let mut marketType: Value = Value::Str("contract".into());
if isSpot {
marketType = Value::Str("spot".into());
}
let mut market: Value = self.safe_market(&[marketId, Value::Null, Value::Null, marketType]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut ohlcvsByTimeframe: Value = self.safe_dict(self.ohlcvs.clone(), symbol.clone(), &[]);
if (ohlcvsByTimeframe == Value::Null) {
if let Value::Dict(__d) = &mut self.ohlcvs { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})); }
}
if (self.safe_value(ohlcvsByTimeframe, timeframe.clone(), &[]) == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "OHLCVLimit", &[Value::Int(1000)]);
add_element_to_object(get_value_mut(&mut self.ohlcvs, &symbol), &timeframe, ArrayCacheByTimestamp::new(limit));
}
let mut stored: Value = self.ohlcvs.as_map().and_then(|__m| symbol.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| timeframe.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
{
let mut i: Value = Value::Int(0);
let mut __for_first_190: bool = true;
while { if !__for_first_190 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_190 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut parsed: Value = self.parse_ws_ohlcv(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), &[market.clone()]);
stored.append(parsed);
}
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("ohlcv::".into()), symbol).into()), Value::Str("::".into())).into()), timeframe).into());
let mut resolveData: Value = Value::from(vec![symbol, timeframe, stored]);
client.resolve(&[resolveData, messageHash]);
}
pub fn parse_ws_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let __market_empty = indexmap::IndexMap::new();
let market = market.as_map().unwrap_or(&__market_empty);
//
// {
// "start": 1670363160000,
// "end": 1670363219999,
// "interval": "1",
// "open": "16987.5",
// "close": "16987.5",
// "high": "16988",
// "low": "16987.5",
// "volume": "23.511",
// "turnover": "399396.344",
// "confirm": false,
// "timestamp": 1670363219614
// }
//
let mut isInverse: Value = (match market.get("inverse") { Some(Value::Bool(__b)) => Value::Bool(*__b), _ => Value::Bool(false) });
let mut volumeIndex: Value = Value::Str("volume".into());
if isInverse.as_bool() == Some(true) {
volumeIndex = Value::Str("turnover".into());
}
return Value::from(vec![self.safe_integer_k(ohlcv.clone(), "start", &[]), self.safe_number_k(ohlcv.clone(), "open", &[]), self.safe_number_k(ohlcv.clone(), "high", &[]), self.safe_number_k(ohlcv.clone(), "low", &[]), self.safe_number_k(ohlcv.clone(), "close", &[]), self.safe_number(ohlcv, volumeIndex, &[])]);
Value::Null
}
/*
* @method
* @name bybit#watchOrderBook
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/orderbook
* @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} A dictionary of [order book structures]{@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
}));
return self.watch_order_book_for_symbols(Value::from(vec![symbol]), &[limit, params]).await;
Value::Null
}
/*
* @method
* @name bybit#watchOrderBookForSymbols
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/orderbook
* @param {string[]} symbols unified array of symbols
* @param {int} [limit] the maximum amount of order book entries to return.
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn watch_order_book_for_symbols(&mut self, mut symbols: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsLength: f64 = ((symbols.len() as i64) as f64);
if (symbolsLength == 0.0) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchOrderBookForSymbols() requires a non-empty array of symbols".into()))));
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut url: Value = self.get_url_by_market_type(&[symbolsNormalized.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), Value::Bool(false), Value::Str("watchOrderBook".into()), params.clone()]).await;
let mut paramsValue: Value = self.clean_params(params);
let mut market: Value = self.market(symbolsNormalized.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
let mut defaultLimit: Value = (if (market.as_map().and_then(|__m| __m.get("option")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { Value::Int(100) } else { Value::Int(50) });
let mut limitResolved: Value = (if (limit == Value::Null) { defaultLimit } else { limit.clone() });
if (limit != Value::Null) {
let mut limits: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::from(vec![Value::Int(1), Value::Int(50), Value::Int(200), Value::Int(1000)]));
m.insert("option".to_string(), Value::from(vec![Value::Int(25), Value::Int(100)]));
m.insert("default".to_string(), Value::from(vec![Value::Int(1), Value::Int(50), Value::Int(200), Value::Int(1000)]));
m
});
let mut selectedLimits: Value = self.safe_list2(limits, market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null), Value::Str("default".into()), &[Value::from(vec![])]);
if !(self.in_array(limit.clone(), selectedLimits.clone()).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" watchOrderBookForSymbols(): for ".into())).into()), market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null)).into()), Value::Str(" markets limit can be one of: ".into())).into()), json_stringify(&selectedLimits))));
}
}
let mut topics: Vec<Value> = Vec::new();
let mut messageHashes: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_191: bool = true;
while { if !__for_first_191 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_191 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolsNormalized.len() as i64) as f64) } {
let mut symbol: Value = symbolsNormalized.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.market_id(symbol.clone());
let mut topic: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("orderbook.".into()), Value::Str(format!("{}", limitResolved).into())).into()), Value::Str(".".into())).into()), marketId).into());
topics.push(topic);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbol).into());
messageHashes.push(messageHash);
}
}
let mut orderbook: Value = self.watch_topics(url, Value::from(messageHashes), Value::from(topics), &[paramsValue]).await;
return orderbook.limit();
Value::Null
}
/*
* @method
* @name bybit#unWatchOrderBookForSymbols
* @description unsubscribe from the orderbook channel
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/orderbook
* @param {string[]} symbols unified symbol of the market to unwatch the trades for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.limit] orderbook limit, default is undefined
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn un_watch_order_book_for_symbols(&mut self, mut symbols: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(false)]);
let mut channel: Value = Value::Str("orderbook.".into());
let mut limitParam: Value = self.safe_integer_k(params.clone(), "limit", &[]);
let mut paramsOmitted: Value = (if (limitParam != Value::Null) { self.omit(params.clone(), Value::Str("limit".into()), &[]) } else { params });
let mut defaultLimit: Value = Value::Int(500);
if (limitParam == Value::Null) {
let mut firstMarket: Value = self.market(symbolsNormalized.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
defaultLimit = (if (firstMarket.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { Value::Int(50) } else { Value::Int(500) });
}
let mut limit: Value = (if (limitParam == Value::Null) { defaultLimit } else { limitParam });
channel = Value::Str(format!("{}{}", channel, Value::Str(format!("{}", limit).into())).into());
let mut subMessageHashes: Vec<Value> = Vec::new();
let mut messageHashes: Vec<Value> = Vec::new();
let mut topics: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_192: bool = true;
while { if !__for_first_192 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_192 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolsNormalized.len() as i64) as f64) } {
let mut symbol: Value = symbolsNormalized.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol.clone());
let mut marketId: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut topic: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", channel, Value::Str(".".into())).into()), marketId).into());
messageHashes.push(Value::Str(format!("{}{}", Value::Str("unsubscribe:orderbook:".into()), symbol).into()));
subMessageHashes.push(Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbol).into()));
topics.push(topic);
}
}
let mut url: Value = self.get_url_by_market_type(&[symbolsNormalized.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), Value::Bool(false), Value::Str("watchOrderBook".into()), paramsOmitted.clone()]).await;
return self.un_watch_topics(url, Value::Str("orderbook".into()), symbolsNormalized, Value::from(messageHashes), Value::from(subMessageHashes), Value::from(topics), &[paramsOmitted]).await;
Value::Null
}
/*
* @method
* @name bybit#unWatchOrderBook
* @description unsubscribe from the orderbook channel
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/orderbook
* @param {string} symbol symbol of the market to unwatch the trades for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.limit] orderbook limit, default is undefined
* @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
}));
return self.un_watch_order_book_for_symbols(Value::from(vec![symbol]), &[params]).await;
Value::Null
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "topic": "orderbook.50.BTCUSDT",
// "type": "snapshot",
// "ts": 1672304484978,
// "data": {
// "s": "BTCUSDT",
// "b": [
// ...,
// [
// "16493.50",
// "0.006"
// ],
// [
// "16493.00",
// "0.100"
// ]
// ],
// "a": [
// [
// "16611.00",
// "0.029"
// ],
// [
// "16612.00",
// "0.213"
// ],
// ],
// "u": 18521288,
// "seq": 7961638724
// }
// }
//
let mut topic: Value = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
let mut limit: Option<String> = self.safe_string(Value::Array(topic.as_str().map(|__s| __s.split(".").map(|__p| Value::Str(__p.to_string().into())).collect()).unwrap_or_default()), Value::Int(1), &[]).as_str().map(str::to_owned);
let mut isSpot: bool = Value::Int(get_value(&client, &Value::Str("url".into())).as_str().and_then(|__s| __s.find("spot")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64);
let mut type_var: Option<String> = (match message.get("type") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
let mut isSnapshot: bool = type_var.as_deref() == Some("snapshot");
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "s", &[]);
let mut marketType: Value = Value::Str("contract".into());
if isSpot {
marketType = Value::Str("spot".into());
}
let mut market: Value = self.safe_market(&[marketId, Value::Null, Value::Null, marketType]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = (match message.get("ts") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
if !(matches!((&self.orderbooks, &symbol), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
{ let __be_tmp = self.order_book(&[]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
}
let mut orderbook: Value = self.orderbooks.as_map().and_then(|__m| symbol.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
add_element_to_object(&mut orderbook, &Value::Str("symbol".into()), symbol.clone());
if isSnapshot {
let mut snapshot: Value = self.parse_order_book(data.clone(), symbol.clone(), &[timestamp.clone(), Value::Str("b".into()), Value::Str("a".into())]);
orderbook.reset(snapshot);
} else {
let mut asks: Value = self.safe_list_k(data.clone(), "a", &[Value::from(vec![])]);
let mut bids: Value = self.safe_list_k(data, "b", &[Value::from(vec![])]);
self.handle_deltas(get_value(&orderbook, &Value::Str("asks".into())), asks);
self.handle_deltas(get_value(&orderbook, &Value::Str("bids".into())), bids);
add_element_to_object(&mut orderbook, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut orderbook, &Value::Str("datetime".into()), self.iso8601(timestamp));
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("orderbook".into()), Value::Str(":".into())).into()), symbol).into());
if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), orderbook.clone()); }
client.resolve(&[orderbook, messageHash]);
if (limit.as_deref() == Some("1")) {
let mut bidask: Value = self.parse_ws_bid_ask(self.orderbooks.as_map().and_then(|__m| symbol.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null), &[market]);
let mut newBidsAsks: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if let Value::Dict(__d) = &mut newBidsAsks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), bidask.clone()); }
if let Value::Dict(__d) = &mut self.bidsasks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), bidask); }
client.resolve(&[newBidsAsks, Value::Str(format!("{}{}", Value::Str("bidask:".into()), symbol).into())]);
}
}
pub fn handle_delta(&self, mut bookside: Value, mut delta: Value) {
let mut bidAsk: Value = self.parse_order_book_bid_ask(delta, &[Value::Int(0), Value::Int(1)]);
bookside.store_array(bidAsk);
}
pub fn handle_deltas(&self, mut bookside: Value, mut deltas: Value) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_193: bool = true;
while { if !__for_first_193 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_193 = false; i.as_f64().unwrap_or(f64::NAN) < ((deltas.len() as i64) as f64) } {
self.handle_delta(bookside.clone(), deltas.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));
}
}
}
/*
* @method
* @name bybit#watchTrades
* @description watches information on multiple trades made in a market
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/trade
* @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_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 bybit#watchTradesForSymbols
* @description get the list of most recent trades for a list of symbols
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/trade
* @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;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut symbolsLength: f64 = ((symbolsNormalized.len() as i64) as f64);
if (symbolsLength == 0.0) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchTradesForSymbols() requires a non-empty array of symbols".into()))));
}
let mut paramsValue: Value = self.clean_params(params);
let mut url: Value = self.get_url_by_market_type(&[symbolsNormalized.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), Value::Bool(false), Value::Str("watchTrades".into()), paramsValue.clone()]).await;
let mut topics: Vec<Value> = Vec::new();
let mut messageHashes: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_194: bool = true;
while { if !__for_first_194 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_194 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolsNormalized.len() as i64) as f64) } {
let mut symbol: Value = symbolsNormalized.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol.clone());
let mut topic: Value = Value::Str(format!("{}{}", Value::Str("publicTrade.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
topics.push(topic);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("trade:".into()), symbol).into());
messageHashes.push(messageHash);
}
}
let mut trades: Value = self.watch_topics(url, Value::from(messageHashes), Value::from(topics), &[paramsValue]).await;
let mut first: Value = self.safe_dict(trades.clone(), Value::Int(0), &[]);
let mut tradeSymbol: Value = self.safe_string_k(first, "symbol", &[]);
let mut limitResolved: Value = limit.clone();
if self.newUpdates.as_bool() == Some(true) {
limitResolved = trades.get_limit(tradeSymbol, limit);
}
return self.filter_by_since_limit(trades, &[since, limitResolved, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name bybit#unWatchTradesForSymbols
* @description unsubscribe from the trades channel
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/trade
* @param {string[]} symbols unified symbol of the market to unwatch the trades for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {any} status of the unwatch request
*/
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;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(false), Value::Bool(true)]);
let mut url: Value = self.get_url_by_market_type(&[symbolsNormalized.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), Value::Bool(false), Value::Str("unWatchTradesForSymbols".into()), params.clone()]).await;
let mut messageHashes: Vec<Value> = Vec::new();
let mut topics: Vec<Value> = Vec::new();
let mut subMessageHashes: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_195: bool = true;
while { if !__for_first_195 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_195 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolsNormalized.len() as i64) as f64) } {
let mut symbol: Value = symbolsNormalized.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol.clone());
let mut topic: Value = Value::Str(format!("{}{}", Value::Str("publicTrade.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
topics.push(topic);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:trade:".into()), symbol).into());
messageHashes.push(messageHash);
subMessageHashes.push(Value::Str(format!("{}{}", Value::Str("trade:".into()), symbol).into()));
}
}
return self.un_watch_topics(url, Value::Str("trades".into()), symbolsNormalized, Value::from(messageHashes), Value::from(subMessageHashes), Value::from(topics), &[params]).await;
Value::Null
}
/*
* @method
* @name bybit#unWatchTrades
* @description unsubscribe from the trades channel
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/trade
* @param {string} symbol unified symbol of the market to unwatch the trades for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {any} status of the unwatch request
*/
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);
//
// {
// "topic": "publicTrade.BTCUSDT",
// "type": "snapshot",
// "ts": 1672304486868,
// "data": [
// {
// "T": 1672304486865,
// "s": "BTCUSDT",
// "S": "Buy",
// "v": "0.001",
// "p": "16578.50",
// "L": "PlusTick",
// "i": "20f43950-d8dd-5b31-9112-a178eb6023af",
// "BT": false
// }
// ]
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut topic: Value = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
let mut trades: Value = data;
let mut parts: Value = Value::Array(topic.as_str().map(|__s| __s.split(".").map(|__p| Value::Str(__p.to_string().into())).collect()).unwrap_or_default());
let mut isSpot: bool = Value::Int(get_value(&client, &Value::Str("url".into())).as_str().and_then(|__s| __s.find("spot")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64);
let mut marketType: Value = Value::Str("contract".into());
if isSpot {
marketType = Value::Str("spot".into());
}
let mut marketId: Value = self.safe_string(parts, Value::Int(1), &[]);
let mut market: Value = self.safe_market(&[marketId, Value::Null, Value::Null, marketType]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut stored: Value = self.safe_value(self.trades.clone(), symbol.clone(), &[]);
if (stored == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
stored = ArrayCache::new(limit);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), stored.clone()); }
}
{
let mut j: Value = Value::Int(0);
let mut __for_first_196: bool = true;
while { if !__for_first_196 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_196 = false; j.as_f64().unwrap_or(f64::NAN) < ((trades.len() as i64) as f64) } {
let mut parsed: Value = self.parse_ws_trade(trades.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), &[market.clone()]);
stored.append(parsed);
}
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("trade".into()), Value::Str(":".into())).into()), symbol).into());
client.resolve(&[stored, messageHash]);
}
pub fn parse_ws_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// public
// {
// "T": 1672304486865,
// "s": "BTCUSDT",
// "S": "Buy",
// "v": "0.001",
// "p": "16578.50",
// "L": "PlusTick",
// "i": "20f43950-d8dd-5b31-9112-a178eb6023af",
// "BT": false
// }
//
// spot private
// {
// "e": "ticketInfo",
// "E": "1662348310386",
// "s": "BTCUSDT",
// "q": "0.001007",
// "t": "1662348310373",
// "p": "19842.02",
// "T": "2100000000002220938",
// "o": "1238261807653647872",
// "c": "spotx008",
// "O": "1238225004531834368",
// "a": "533287",
// "A": "642908",
// "m": false,
// "S": "BUY"
// }
//
let mut id: Value = self.safe_string_n(trade.clone(), Value::from(vec![Value::Str("i".into()), Value::Str("T".into()), Value::Str("v".into())]), &[]);
let mut isContract: bool = matches!(&trade, Value::Dict(__d) if __d.contains_key("BT"));
let mut marketType: Value = Value::Str("spot".into());
if isContract {
marketType = Value::Str("contract".into());
}
if (market != Value::Null) {
marketType = self.safe_string_k(market.clone(), "type", &[]);
}
let mut marketId: Value = self.safe_string_k(trade.clone(), "s", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market, Value::Null, marketType]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = self.safe_integer2(trade.clone(), Value::Str("t".into()), Value::Str("T".into()), &[]);
let mut side: Value = self.safe_string_lower_k(trade.clone(), "S", &[]);
let mut takerOrMaker: Value = Value::Null;
let mut m: Value = self.safe_value_k(trade.clone(), "m", &[]);
if (side == Value::Null) {
side = (if ((match &(m) { Value::Bool(__x) => *__x == true, __v => matches!((match __v { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None }), Some(__y) if __y == 1.0) })) { Value::Str("buy".into()) } else { Value::Str("sell".into()) });
} else {
// spot private
takerOrMaker = m.clone();
}
let mut price: Value = self.safe_string_k(trade.clone(), "p", &[]);
let mut amount: Value = self.safe_string2(trade.clone(), Value::Str("q".into()), Value::Str("v".into()), &[]);
let mut orderId: Value = self.safe_string_k(trade.clone(), "o", &[]);
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("info".to_string(), trade);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), symbol);
m.insert("order".to_string(), orderId);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m
}), &[marketResolved]);
Value::Null
}
pub fn get_private_type(&self, mut url: Value) -> Value {
if Value::Int(url.as_str().and_then(|__s| __s.find("spot")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
return Value::Str("spot".into());
} else if Value::Int(url.as_str().and_then(|__s| __s.find("v5/private")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
return Value::Str("unified".into());
} else {
return Value::Str("usdc".into());
}
Value::Null
}
/*
* @method
* @name bybit#watchMyTrades
* @description watches information on multiple trades made by the user
* @see https://bybit-exchange.github.io/docs/v5/websocket/private/execution
* @see https://bybit-exchange.github.io/docs/v5/websocket/private/fast-execution
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.unifiedMargin] use unified margin account
* @param {boolean} [params.executionFast] use fast execution
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-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
}));
let mut method: Value = Value::Str("watchMyTrades".into());
let mut messageHash: Value = Value::Str("myTrades".into());
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolResolved: Value = (if (symbol != Value::Null) { self.symbol(symbol.clone()) } else { symbol.clone() });
if (symbol != Value::Null) {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(format!("{}{}", Value::Str(":".into()), symbolResolved).into())).into());
}
let mut url: Value = self.get_url_by_market_type(&[symbolResolved.clone(), Value::Bool(true), method, params.clone()]).await;
self.authenticate(url.clone(), &[]).await;
let mut topicByMarket: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("ticketInfo".into()));
m.insert("unified".to_string(), Value::Str("execution".into()));
m.insert("usdc".to_string(), Value::Str("user.openapi.perp.trade".into()));
m
});
let mut topic: Value = self.safe_string(topicByMarket, self.get_private_type(url.clone()), &[]);
let mut executionFastparamsExecutionFastVariable = self.handle_option_bool_and_params(params, Value::Str("watchMyTrades".into()), Value::Str("executionFast".into()), &[Value::Bool(false)]);
let mut executionFast: Value = executionFastparamsExecutionFastVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsExecutionFast: Value = executionFastparamsExecutionFastVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if executionFast.as_bool() == Some(true) {
topic = Value::Str("execution.fast".into());
}
let mut trades: Value = self.watch_topics(url, Value::from(vec![messageHash]), Value::from(vec![topic]), &[paramsExecutionFast]).await;
let mut limitResolved: Value = limit.clone();
if self.newUpdates.as_bool() == Some(true) {
limitResolved = trades.get_limit(symbolResolved.clone(), limit);
}
return self.filter_by_symbol_since_limit(trades, &[symbolResolved, since, limitResolved, Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name bybit#unWatchMyTrades
* @description unWatches information on multiple trades made by the user
* @see https://bybit-exchange.github.io/docs/v5/websocket/private/execution
* @see https://bybit-exchange.github.io/docs/v5/websocket/private/fast-execution
* @param {string} symbol unified market symbol of the market orders were made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.unifiedMargin] use unified margin account
* @param {boolean} [params.executionFast] use fast execution
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn un_watch_my_trades(&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
}));
let mut method: Value = Value::Str("watchMyTrades".into());
let mut messageHash: Value = Value::Str("unsubscribe:myTrades".into());
let mut subHash: Value = Value::Str("myTrades".into());
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbol != Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" unWatchMyTrades() does not support a symbol parameter, you must unwatch all my trades".into()))));
}
let mut url: Value = self.get_url_by_market_type(&[symbol, Value::Bool(true), method, params.clone()]).await;
self.authenticate(url.clone(), &[]).await;
let mut topicByMarket: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("ticketInfo".into()));
m.insert("unified".to_string(), Value::Str("execution".into()));
m.insert("usdc".to_string(), Value::Str("user.openapi.perp.trade".into()));
m
});
let mut topic: Value = self.safe_string(topicByMarket, self.get_private_type(url.clone()), &[]);
let mut executionFastparamsExecutionFastVariable = self.handle_option_bool_and_params(params, Value::Str("watchMyTrades".into()), Value::Str("executionFast".into()), &[Value::Bool(false)]);
let mut executionFast: Value = executionFastparamsExecutionFastVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsExecutionFast: Value = executionFastparamsExecutionFastVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if executionFast.as_bool() == Some(true) {
topic = Value::Str("execution.fast".into());
}
return self.un_watch_topics(url, Value::Str("myTrades".into()), Value::from(vec![]), Value::from(vec![messageHash]), Value::from(vec![subHash]), Value::from(vec![topic]), &[paramsExecutionFast]).await;
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);
//
// spot
// {
// "type": "snapshot",
// "topic": "ticketInfo",
// "ts": "1662348310388",
// "data": [
// {
// "e": "ticketInfo",
// "E": "1662348310386",
// "s": "BTCUSDT",
// "q": "0.001007",
// "t": "1662348310373",
// "p": "19842.02",
// "T": "2100000000002220938",
// "o": "1238261807653647872",
// "c": "spotx008",
// "O": "1238225004531834368",
// "a": "533287",
// "A": "642908",
// "m": false,
// "S": "BUY"
// }
// ]
// }
// unified
// {
// "id": "592324803b2785-26fa-4214-9963-bdd4727f07be",
// "topic": "execution",
// "creationTime": 1672364174455,
// "data": [
// {
// "category": "linear",
// "symbol": "XRPUSDT",
// "execFee": "0.005061",
// "execId": "7e2ae69c-4edf-5800-a352-893d52b446aa",
// "execPrice": "0.3374",
// "execQty": "25",
// "execType": "Trade",
// "execValue": "8.435",
// "isMaker": false,
// "feeRate": "0.0006",
// "tradeIv": "",
// "markIv": "",
// "blockTradeId": "",
// "markPrice": "0.3391",
// "indexPrice": "",
// "underlyingPrice": "",
// "leavesQty": "0",
// "orderId": "f6e324ff-99c2-4e89-9739-3086e47f9381",
// "orderLinkId": "",
// "orderPrice": "0.3207",
// "orderQty": "25",
// "orderType": "Market",
// "stopOrderType": "UNKNOWN",
// "side": "Sell",
// "execTime": "1672364174443",
// "isLeverage": "0"
// }
// ]
// }
//
// execution.fast
//
// {
// "topic": "execution.fast",
// "creationTime": 1757405601981,
// "data": [
// {
// "category": "linear",
// "symbol": "BTCUSDT",
// "execId": "ffcac6ac-7571-536d-a28a-847dd7d08a0f",
// "execPrice": "112529.6",
// "execQty": "0.001",
// "orderId": "6e25ab73-7a55-4ae7-adc2-8ea95f167c85",
// "isMaker": false,
// "orderLinkId": "test-00001",
// "side": "Buy",
// "execTime": "1757405601977",
// "seq": 9515624038
// }
// ]
// }
//
let mut topic: Option<String> = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) }).as_str().map(str::to_owned);
let mut spot: bool = topic.as_deref() == Some("ticketInfo");
let mut executionFast: bool = topic.as_deref() == Some("execution.fast");
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
if !(matches!(&data, Value::Arr(_))) {
data = self.safe_list_k(data.clone(), "result", &[Value::from(vec![])]);
}
if (self.myTrades.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCacheBySymbolById::new(limit);
}
let mut trades: Value = self.myTrades.clone();
let mut symbols: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
// the option was renamed from filterExecTypes to execType to mirror
// the exchange's own field name, the old key is still read as a
// fallback for backward compatibility
// see https://github.com/ccxt/ccxt/issues/17244
// and https://github.com/ccxt/ccxt/issues/28181
let mut execTypeOption: Value = self.handle_option(Value::Str("watchMyTrades".into()), Value::Str("execType".into()), &[]);
if (execTypeOption == Value::Null) {
execTypeOption = self.handle_option(Value::Str("watchMyTrades".into()), Value::Str("filterExecTypes".into()), &[]);
}
let mut execTypes: Value = Value::Null;
if matches!(&execTypeOption, Value::Str(_)) {
// a single execution type is accepted as a plain string as well
execTypes = Value::from(vec![execTypeOption.clone()]);
} else {
execTypes = execTypeOption;
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_197: bool = true;
while { if !__for_first_197 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_197 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut rawTrade: 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 parsed: Value = Value::Null;
if spot && !executionFast {
parsed = self.parse_ws_trade(rawTrade.clone(), &[]);
} else {
// filter unified trades
let mut execType: Value = self.safe_string_k(rawTrade.clone(), "execType", &[Value::Str("".into())]);
if executionFast {
execType = Value::Str("Trade".into());
}
if (execTypes != Value::Null) && !(self.in_array(execType, execTypes.clone()).as_bool() == Some(true)) {
continue;
}
parsed = self.parse_trade(rawTrade, &[]);
}
let mut symbol: Value = parsed.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (symbol == Value::Null) {
continue;
}
if let Value::Dict(__d) = &mut symbols { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Bool(true)); }
trades.append(parsed);
}
}
let mut keys: Value = object_keys(&symbols);
{
let mut i: Value = Value::Int(0);
let mut __for_first_198: bool = true;
while { if !__for_first_198 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_198 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut currentMessageHash: Value = Value::Str(format!("{}{}", Value::Str("myTrades:".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(&[trades.clone(), currentMessageHash]);
}
}
// non-symbol specific
let mut messageHash: Value = Value::Str("myTrades".into());
client.resolve(&[trades, messageHash]);
}
/*
* @method
* @name bybit#watchPositions
* @see https://bybit-exchange.github.io/docs/v5/websocket/private/position
* @description watch all open positions
* @param {string[]} [symbols] list of unified market symbols
* @param {int} [since] the earliest time in ms to fetch positions for
* @param {int} [limit] the maximum number of positions to retrieve
* @param {object} params extra parameters specific to the exchange API endpoint
* @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 method: Value = Value::Str("watchPositions".into());
let mut messageHash: Value = Value::Str("".into());
let mut symbolsNormalized: Value = symbols.clone();
if (symbols != Value::Null) && !(self.is_empty(symbols.clone()).as_bool() == Some(true)) {
symbolsNormalized = self.market_symbols(&[symbols]);
}
if (symbolsNormalized != Value::Null) && !(self.is_empty(symbolsNormalized.clone()).as_bool() == Some(true)) {
messageHash = Value::Str(format!("{}{}", Value::Str("::".into()), Value::Str(symbolsNormalized.as_array().map(|__a| __a.iter().map(|__v| __v.to_string()).collect::<Vec<String>>().join(",")).unwrap_or_default().into())).into());
}
let mut firstSymbol: Value = self.safe_string(symbolsNormalized.clone(), Value::Int(0), &[]);
let mut url: Value = self.get_url_by_market_type(&[firstSymbol, Value::Bool(true), method, params.clone()]).await;
messageHash = Value::Str(format!("{}{}", Value::Str("positions".into()), messageHash).into());
let mut client: Value = self.client(&[url.clone()]);
self.authenticate(url.clone(), &[]).await;
self.set_positions_cache(client.clone(), &[symbolsNormalized.clone()]);
let mut cache: Value = self.positions.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)]);
if ((match &(fetchPositionsSnapshot) { Value::Bool(__x) => *__x == true, __v => matches!((match __v { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None }), Some(__y) if __y == 1.0) })) && ((match &(awaitPositionsSnapshot) { Value::Bool(__x) => *__x == true, __v => matches!((match __v { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None }), Some(__y) if __y == 1.0) })) && (cache == Value::Null) {
let mut snapshot: Value = crate::exchange_stubs::ws_await_flight(&client.future(&[Value::Str("fetchPositionsSnapshot".into())])).await;
return self.filter_by_symbols_since_limit(snapshot, &[symbolsNormalized.clone(), since.clone(), limit.clone(), Value::Bool(true)]);
}
let mut topics: Value = Value::from(vec![Value::Str("position".into())]);
let mut newPositions: Value = self.watch_topics(url, Value::from(vec![messageHash]), topics, &[params]).await;
if self.newUpdates.as_bool() == Some(true) {
return newPositions;
}
return self.filter_by_symbols_since_limit(cache, &[symbolsNormalized, since, limit, Value::Bool(true)]);
Value::Null
}
pub fn set_positions_cache(&mut self, mut client: Value, optional_args: &[Value]) {
let mut symbols = get_arg(optional_args, 0, Value::Null);
if (self.positions.clone() != Value::Null) {
return;
}
let mut fetchPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".into()), Value::Str("fetchPositionsSnapshot".into()), &[Value::Bool(true)]);
if (match &(fetchPositionsSnapshot) { Value::Bool(__x) => *__x == true, __v => matches!((match __v { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None }), Some(__y) if __y == 1.0) }) {
let mut messageHash: Value = Value::Str("fetchPositionsSnapshot".into());
if !(in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
client.future(&[messageHash.clone()]);
self.spawn(&[Value::Str("load_positions_snapshot".into()).clone(), client.clone(), messageHash.clone()]);
}
} else {
self.positions = ArrayCacheBySymbolBySide::new(Value::Null);
}
}
pub async fn load_positions_snapshot(&mut self, mut client: Value, mut messageHash: Value) -> Value {
// as only one ws channel gives positions for all types, for snapshot must load all positions
let mut fetchFunctions: Value = Value::from(vec![self.fetch_positions(&[Value::Null, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("swap".into()));
m.insert("subType".to_string(), Value::Str("linear".into()));
m
})]).await, self.fetch_positions(&[Value::Null, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("swap".into()));
m.insert("subType".to_string(), Value::Str("inverse".into()));
m
})]).await]);
let mut promises: Value = promise_all(&fetchFunctions).await;
self.positions = ArrayCacheBySymbolBySide::new(Value::Null);
let mut cache: Value = self.positions.clone();
{
let mut i: Value = Value::Int(0);
let mut __for_first_200: bool = true;
while { if !__for_first_200 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_200 = false; i.as_f64().unwrap_or(f64::NAN) < ((promises.len() as i64) as f64) } {
let mut positions: Value = promises.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 ii: Value = Value::Int(0);
let mut __for_first_199: bool = true;
while { if !__for_first_199 { if let Value::Int(n) = &mut ii { *n += 1; } } __for_first_199 = false; ii.as_f64().unwrap_or(f64::NAN) < ((positions.len() as i64) as f64) } {
let mut position: Value = positions.as_array().and_then(|__arr| match &ii { 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);
cache.append(position);
}
}
}
}
// don't remove the future from the .futures cache
if (in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
let mut future: Value = get_value(&get_value(&client, &Value::Str("futures".into())), &messageHash);
future.resolve(&[cache.clone()]);
client.resolve(&[cache, Value::Str("position".into())]);
}
Value::Null
}
pub fn handle_positions(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// topic: 'position',
// id: '504b2671629b08e3c4f6960382a59363:3bc4028023786545:0:01',
// creationTime: 1694566055295,
// data: [{
// bustPrice: '15.00',
// category: 'inverse',
// createdTime: '1670083436351',
// cumRealisedPnl: '0.00011988',
// entryPrice: '19358.58553268',
// leverage: '10',
// liqPrice: '15.00',
// markPrice: '25924.00',
// positionBalance: '0.0000156',
// positionIdx: 0,
// positionMM: '0.001',
// positionIM: '0.0000015497',
// positionStatus: 'Normal',
// positionValue: '0.00015497',
// riskId: 1,
// riskLimitValue: '150',
// side: 'Buy',
// size: '3',
// stopLoss: '0.00',
// symbol: 'BTCUSD',
// takeProfit: '0.00',
// tpslMode: 'Full',
// tradeMode: 0,
// autoAddMargin: 1,
// trailingStop: '0.00',
// unrealisedPnl: '0.00003925',
// updatedTime: '1694566055293',
// adlRankIndicator: 3
// }]
// }
//
// each account is connected to a different endpoint
// and has exactly one subscriptionhash which is the account type
if (self.positions.clone() == Value::Null) {
self.positions = ArrayCacheBySymbolBySide::new(Value::Null);
}
let mut cache: Value = self.positions.clone();
let mut newPositions: Value = Value::from(vec![]);
let mut rawPositions: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
{
let mut i: Value = Value::Int(0);
let mut __for_first_201: bool = true;
while { if !__for_first_201 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_201 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawPositions.len() as i64) as f64) } {
let mut rawPosition: Value = rawPositions.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 side: Option<String> = self.safe_string_k(position.clone(), "side", &[]).as_str().map(str::to_owned);
// hacky solution to handle closing positions
// without crashing, we should handle this properly later
if let Value::Arr(__a) = &mut newPositions { std::sync::Arc::make_mut(__a).push(position.clone()); }
if (side.is_none()) || (side.as_deref() == Some("")) {
// closing update, adding both sides to "reset" both sides
// since we don't know which side is being closed
add_element_to_object(&mut position, &Value::Str("side".into()), Value::Str("long".into()));
cache.append(position.clone());
add_element_to_object(&mut position, &Value::Str("side".into()), Value::Str("short".into()));
cache.append(position.clone());
add_element_to_object(&mut position, &Value::Str("side".into()), Value::Null);
} else {
// regular update
cache.append(position);
}
}
}
let mut messageHashes: Value = self.find_message_hashes(client.clone(), Value::Str("positions::".into()));
{
let mut i: Value = Value::Int(0);
let mut __for_first_202: bool = true;
while { if !__for_first_202 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_202 = 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 = Value::Array(messageHash.as_str().map(|__s| __s.split("::").map(|__p| Value::Str(__p.to_string().into())).collect()).unwrap_or_default());
let mut symbolsString: Value = parts.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut symbols: Value = Value::Array(symbolsString.as_str().map(|__s| __s.split(",").map(|__p| Value::Str(__p.to_string().into())).collect()).unwrap_or_default());
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, Value::Str("positions".into())]);
}
/*
* @method
* @name bybit#unWatchPositions
* @description unWatches all open positions
* @see https://bybit-exchange.github.io/docs/v5/websocket/private/position
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} status of the unwatch request
*/
pub async fn un_watch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut method: Value = Value::Str("watchPositions".into());
let mut messageHash: Value = Value::Str("unsubscribe:positions".into());
let mut subHash: Value = Value::Str("positions".into());
if (symbols != Value::Null) && !(self.is_empty(symbols.clone()).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" unWatchPositions() does not support a symbol parameter, you must unwatch all orders".into()))));
}
let mut url: Value = self.get_url_by_market_type(&[Value::Null, Value::Bool(true), method, params.clone()]).await;
self.authenticate(url.clone(), &[]).await;
let mut topics: Value = Value::from(vec![Value::Str("position".into())]);
return self.un_watch_topics(url, Value::Str("positions".into()), symbols, Value::from(vec![messageHash]), Value::from(vec![subHash]), topics, &[params]).await;
Value::Null
}
/*
* @method
* @name bybit#watchLiquidations
* @description watch the public liquidations of a trading pair
* @see https://bybit-exchange.github.io/docs/v5/websocket/public/all-liquidation
* @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
* @param {string} [params.method] exchange specific method, supported: liquidation, allLiquidation
* @returns {object} an array of [liquidation structures]{@link https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure}
*/
pub async fn watch_liquidations(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut symbolValue: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut url: Value = self.get_url_by_market_type(&[symbolValue.clone(), Value::Bool(false), Value::Str("watchLiquidations".into()), params.clone()]).await;
let mut methodparamsMethodVariable = self.handle_option_string_and_params(self.clean_params(params), Value::Str("watchLiquidations".into()), Value::Str("method".into()), &[Value::Str("allLiquidation".into())]);
let mut method: Value = methodparamsMethodVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMethod: Value = methodparamsMethodVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("liquidations::".into()), symbolValue).into());
let mut topic: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", method, Value::Str(".".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut newLiquidation: Value = self.watch_topics(url, Value::from(vec![messageHash]), Value::from(vec![topic]), &[paramsMethod]).await;
if self.newUpdates.as_bool() == Some(true) {
return newLiquidation;
}
return self.filter_by_symbols_since_limit(self.liquidations.clone(), &[Value::from(vec![symbolValue]), 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);
//
// {
// "data": {
// "price": "0.03803",
// "side": "Buy",
// "size": "1637",
// "symbol": "GALAUSDT",
// "updatedTime": 1673251091822
// },
// "topic": "liquidation.GALAUSDT",
// "ts": 1673251091822,
// "type": "snapshot"
// }
//
// {
// "topic": "allLiquidation.ROSEUSDT",
// "type": "snapshot",
// "ts": 1739502303204,
// "data": [
// {
// "T": 1739502302929,
// "s": "ROSEUSDT",
// "S": "Sell",
// "v": "20000",
// "p": "0.04499"
// }
// ]
// }
//
if (matches!(&message.get("data").cloned().unwrap_or(Value::Null), Value::Arr(_))) {
let mut rawLiquidations: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
{
let mut i: Value = Value::Int(0);
let mut __for_first_203: bool = true;
while { if !__for_first_203 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_203 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawLiquidations.len() as i64) as f64) } {
let mut rawLiquidation: Value = self.safe_dict(rawLiquidations.clone(), i.clone(), &[]);
let mut marketId: Value = self.safe_string_k(rawLiquidation.clone(), "s", &[]);
let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, Value::Str("".into()), Value::Str("contract".into())]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut liquidation: Value = self.parse_ws_liquidation(rawLiquidation.clone(), &[market.clone()]);
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.clone());
}
let mut cache: Value = self.liquidations.clone();
cache.append(liquidation.clone());
client.resolve(&[Value::from(vec![liquidation.clone()]), Value::Str("liquidations".into())]);
client.resolve(&[Value::from(vec![liquidation.clone()]), Value::Str(format!("{}{}", Value::Str("liquidations::".into()), symbol).into())]);
}
}
} else {
let mut rawLiquidation: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(rawLiquidation.clone(), "symbol", &[]);
let mut market: Value = self.safe_market(&[marketId, Value::Null, Value::Str("".into()), Value::Str("contract".into())]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut liquidation: Value = self.parse_ws_liquidation(rawLiquidation, &[market]);
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();
cache.append(liquidation.clone());
client.resolve(&[Value::from(vec![liquidation.clone()]), Value::Str("liquidations".into())]);
client.resolve(&[Value::from(vec![liquidation]), Value::Str(format!("{}{}", Value::Str("liquidations::".into()), symbol).into())]);
}
}
pub fn parse_ws_liquidation(&self, mut liquidation: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "price": "0.03803",
// "side": "Buy",
// "size": "1637",
// "symbol": "GALAUSDT",
// "updatedTime": 1673251091822
// }
//
// {
// "T": 1739502302929,
// "s": "ROSEUSDT",
// "S": "Sell",
// "v": "20000",
// "p": "0.04499"
// }
//
let mut marketId: Value = self.safe_string2(liquidation.clone(), Value::Str("symbol".into()), Value::Str("s".into()), &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market, Value::Str("".into()), Value::Str("contract".into())]);
let mut timestamp: Value = self.safe_integer2(liquidation.clone(), Value::Str("updatedTime".into()), Value::Str("T".into()), &[]);
return self.safe_liquidation(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), liquidation.clone());
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("contracts".to_string(), self.safe_number2(liquidation.clone(), Value::Str("size".into()), Value::Str("v".into()), &[]));
m.insert("contractSize".to_string(), self.safe_number_k(marketResolved, "contractSize", &[]));
m.insert("price".to_string(), self.safe_number2(liquidation.clone(), Value::Str("price".into()), Value::Str("p".into()), &[]));
m.insert("side".to_string(), self.safe_string_lower2(liquidation, Value::Str("side".into()), Value::Str("S".into()), &[]));
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
}
/*
* @method
* @name bybit#watchOrders
* @description watches information on multiple orders made by the user
* @see https://bybit-exchange.github.io/docs/v5/websocket/private/order
* @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 {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 method: Value = Value::Str("watchOrders".into());
let mut messageHash: Value = Value::Str("orders".into());
let mut symbolResolved: Value = (if (symbol != Value::Null) { self.symbol(symbol.clone()) } else { symbol.clone() });
if (symbol != Value::Null) {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(format!("{}{}", Value::Str(":".into()), symbolResolved).into())).into());
}
let mut url: Value = self.get_url_by_market_type(&[symbolResolved.clone(), Value::Bool(true), method, params.clone()]).await;
self.authenticate(url.clone(), &[]).await;
let mut topicsByMarket: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::from(vec![Value::Str("order".into()), Value::Str("stopOrder".into())]));
m.insert("unified".to_string(), Value::from(vec![Value::Str("order".into())]));
m.insert("usdc".to_string(), Value::from(vec![Value::Str("user.openapi.perp.order".into())]));
m
});
let mut topics: Value = self.safe_list(topicsByMarket, self.get_private_type(url.clone()), &[]);
let mut orders: Value = self.watch_topics(url, Value::from(vec![messageHash]), topics, &[params]).await;
let mut limitResolved: Value = limit.clone();
if self.newUpdates.as_bool() == Some(true) {
limitResolved = orders.get_limit(symbolResolved.clone(), limit);
}
return self.filter_by_symbol_since_limit(orders, &[symbolResolved, since, limitResolved, Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name bybit#unWatchOrders
* @description unWatches information on multiple orders made by the user
* @see https://bybit-exchange.github.io/docs/v5/websocket/private/order
* @param {string} symbol unified market symbol of the market orders were made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.unifiedMargin] use unified margin account
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn un_watch_orders(&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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut method: Value = Value::Str("watchOrders".into());
let mut messageHash: Value = Value::Str("unsubscribe:orders".into());
let mut subHash: Value = Value::Str("orders".into());
if (symbol != Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" unWatchOrders() does not support a symbol parameter, you must unwatch all orders".into()))));
}
let mut url: Value = self.get_url_by_market_type(&[symbol, Value::Bool(true), method, params.clone()]).await;
self.authenticate(url.clone(), &[]).await;
let mut topicsByMarket: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::from(vec![Value::Str("order".into()), Value::Str("stopOrder".into())]));
m.insert("unified".to_string(), Value::from(vec![Value::Str("order".into())]));
m.insert("usdc".to_string(), Value::from(vec![Value::Str("user.openapi.perp.order".into())]));
m
});
let mut topics: Value = self.safe_list(topicsByMarket, self.get_private_type(url.clone()), &[]);
return self.un_watch_topics(url, Value::Str("orders".into()), Value::from(vec![]), Value::from(vec![messageHash]), Value::from(vec![subHash]), topics, &[params]).await;
Value::Null
}
pub fn handle_order_ws(&self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "reqId":"1",
// "retCode":0,
// "retMsg":"OK",
// "op":"order.create",
// "data":{
// "orderId":"1673523595617593600",
// "orderLinkId":"1673523595617593601"
// },
// "header":{
// "X-Bapi-Limit":"20",
// "X-Bapi-Limit-Status":"19",
// "X-Bapi-Limit-Reset-Timestamp":"1714235558880",
// "Traceid":"584a06d373f2fdcb3a4dfdd81d27df11",
// "Timenow":"1714235558881"
// },
// "connId":"cojidqec0hv9fgvhtbt0-40e"
// }
//
let mut messageHash: Value = (match message.get("reqId") { 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 data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut order: Value = self.parse_order(data, &[]);
client.resolve(&[order, messageHash]);
}
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);
//
// spot
// {
// "type": "snapshot",
// "topic": "order",
// "ts": "1662348310441",
// "data": [
// {
// "e": "order",
// "E": "1662348310441",
// "s": "BTCUSDT",
// "c": "spotx008",
// "S": "BUY",
// "o": "MARKET_OF_QUOTE",
// "f": "GTC",
// "q": "20",
// "p": "0",
// "X": "CANCELED",
// "i": "1238261807653647872",
// "M": "1238225004531834368",
// "l": "0.001007",
// "z": "0.001007",
// "L": "19842.02",
// "n": "0",
// "N": "BTC",
// "u": true,
// "w": true,
// "m": false,
// "O": "1662348310368",
// "Z": "19.98091414",
// "A": "0",
// "C": false,
// "v": "0",
// "d": "NO_LIQ",
// "t": "2100000000002220938"
// }
// ]
// }
// unified
// {
// "id": "5923240c6880ab-c59f-420b-9adb-3639adc9dd90",
// "topic": "order",
// "creationTime": 1672364262474,
// "data": [
// {
// "symbol": "ETH-30DEC22-1400-C",
// "orderId": "5cf98598-39a7-459e-97bf-76ca765ee020",
// "side": "Sell",
// "orderType": "Market",
// "cancelType": "UNKNOWN",
// "price": "72.5",
// "qty": "1",
// "orderIv": "",
// "timeInForce": "IOC",
// "orderStatus": "Filled",
// "orderLinkId": "",
// "lastPriceOnCreated": "",
// "reduceOnly": false,
// "leavesQty": "",
// "leavesValue": "",
// "cumExecQty": "1",
// "cumExecValue": "75",
// "avgPrice": "75",
// "blockTradeId": "",
// "positionIdx": 0,
// "cumExecFee": "0.358635",
// "createdTime": "1672364262444",
// "updatedTime": "1672364262457",
// "rejectReason": "EC_NoError",
// "stopOrderType": "",
// "triggerPrice": "",
// "takeProfit": "",
// "stopLoss": "",
// "tpTriggerBy": "",
// "slTriggerBy": "",
// "triggerDirection": 0,
// "triggerBy": "",
// "closeOnTrigger": false,
// "category": "option"
// }
// ]
// }
//
if (self.orders.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCacheBySymbolById::new(limit);
}
let mut orders: Value = self.orders.clone();
let mut rawOrders: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut first: Value = self.safe_dict(rawOrders.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut category: Option<String> = self.safe_string_k(first, "category", &[]).as_str().map(str::to_owned);
let mut isSpot: bool = category.as_deref() == Some("spot");
if !isSpot {
rawOrders = self.safe_value_k(rawOrders.clone(), "result", &[rawOrders.clone()]);
}
let mut symbols: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_204: bool = true;
while { if !__for_first_204 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_204 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawOrders.len() as i64) as f64) } {
let mut parsed: Value = self.parse_order(rawOrders.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 (isSpot) {
// parsed = this.parseWsSpotOrder (rawOrders[i]);
// } else {
// parsed = this.parseOrder (rawOrders[i]);
// }
let mut symbol: Value = parsed.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (symbol == Value::Null) {
continue;
}
if let Value::Dict(__d) = &mut symbols { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Bool(true)); }
orders.append(parsed);
}
}
let mut symbolsArray: Value = object_keys(&symbols);
{
let mut i: Value = Value::Int(0);
let mut __for_first_205: bool = true;
while { if !__for_first_205 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_205 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolsArray.len() as i64) as f64) } {
let mut currentMessageHash: Value = Value::Str(format!("{}{}", Value::Str("orders:".into()), symbolsArray.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(&[orders.clone(), currentMessageHash]);
}
}
let mut messageHash: Value = Value::Str("orders".into());
client.resolve(&[orders, messageHash]);
}
/*
* @method
* @name bybit#watchBalance
* @description watch balance and get the amount of funds available for trading or funds locked in orders
* @see https://bybit-exchange.github.io/docs/v5/websocket/private/wallet
* @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 method: Value = Value::Str("watchBalance".into());
let mut messageHash: Value = Value::Str("balances".into());
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("watchBalance".into()), &[Value::Null, params]);
let mut type_var: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("watchBalance".into()), &[Value::Null, paramsMarketType]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut unified: Value = self.parent.is_unified_enabled(&[]).await;
let mut isUnifiedMargin: Value = self.safe_bool(unified.clone(), Value::Int(0), &[Value::Bool(false)]);
let mut isUnifiedAccount: Value = self.safe_bool(unified, Value::Int(1), &[Value::Bool(false)]);
let mut url: Value = self.get_url_by_market_type(&[Value::Null, Value::Bool(true), method, paramsSubType.clone()]).await;
self.authenticate(url.clone(), &[]).await;
let mut topicByMarket: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("outboundAccountInfo".into()));
m.insert("unified".to_string(), Value::Str("wallet".into()));
m
});
if isUnifiedAccount.as_bool() == Some(true) {
// unified account
if (subType.as_str() == Some("inverse")) {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(":contract".into())).into());
} else {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(":unified".into())).into());
}
}
if (!(isUnifiedMargin.as_bool() == Some(true))) && (!(isUnifiedAccount.as_bool() == Some(true))) {
// normal account using v5
if (type_var.as_str() == Some("spot")) {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(":spot".into())).into());
} else {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(":contract".into())).into());
}
}
if isUnifiedMargin.as_bool() == Some(true) {
// unified margin account using v5
if (type_var.as_str() == Some("spot")) {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(":spot".into())).into());
} else {
if (subType.as_str() == Some("linear")) {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(":unified".into())).into());
} else {
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(":contract".into())).into());
}
}
}
let mut topics: Value = Value::from(vec![self.safe_string(topicByMarket, self.get_private_type(url.clone()), &[])]);
return self.watch_topics(url, Value::from(vec![messageHash]), topics, &[paramsSubType]).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
// {
// "type": "snapshot",
// "topic": "outboundAccountInfo",
// "ts": "1662107217641",
// "data": [
// {
// "e": "outboundAccountInfo",
// "E": "1662107217640",
// "T": true,
// "W": true,
// "D": true,
// "B": [
// {
// "a": "USDT",
// "f": "176.81254174",
// "l": "201.575"
// }
// ]
// }
// ]
// }
// unified
// {
// "id": "5923242c464be9-25ca-483d-a743-c60101fc656f",
// "topic": "wallet",
// "creationTime": 1672364262482,
// "data": [
// {
// "accountIMRate": "0.016",
// "accountMMRate": "0.003",
// "totalEquity": "12837.78330098",
// "totalWalletBalance": "12840.4045924",
// "totalMarginBalance": "12837.78330188",
// "totalAvailableBalance": "12632.05767702",
// "totalPerpUPL": "-2.62129051",
// "totalInitialMargin": "205.72562486",
// "totalMaintenanceMargin": "39.42876721",
// "coin": [
// {
// "coin": "USDC",
// "equity": "200.62572554",
// "usdValue": "200.62572554",
// "walletBalance": "201.34882644",
// "availableToWithdraw": "0",
// "availableToBorrow": "1500000",
// "borrowAmount": "0",
// "accruedInterest": "0",
// "totalOrderIM": "0",
// "totalPositionIM": "202.99874213",
// "totalPositionMM": "39.14289747",
// "unrealisedPnl": "74.2768991",
// "cumRealisedPnl": "-209.1544627",
// "bonus": "0"
// },
// {
// "coin": "BTC",
// "equity": "0.06488393",
// "usdValue": "1023.08402268",
// "walletBalance": "0.06488393",
// "availableToWithdraw": "0.06488393",
// "availableToBorrow": "2.5",
// "borrowAmount": "0",
// "accruedInterest": "0",
// "totalOrderIM": "0",
// "totalPositionIM": "0",
// "totalPositionMM": "0",
// "unrealisedPnl": "0",
// "cumRealisedPnl": "0",
// "bonus": "0"
// },
// {
// "coin": "ETH",
// "equity": "0",
// "usdValue": "0",
// "walletBalance": "0",
// "availableToWithdraw": "0",
// "availableToBorrow": "26",
// "borrowAmount": "0",
// "accruedInterest": "0",
// "totalOrderIM": "0",
// "totalPositionIM": "0",
// "totalPositionMM": "0",
// "unrealisedPnl": "0",
// "cumRealisedPnl": "0",
// "bonus": "0"
// },
// {
// "coin": "USDT",
// "equity": "11726.64664904",
// "usdValue": "11613.58597018",
// "walletBalance": "11728.54414904",
// "availableToWithdraw": "11723.92075829",
// "availableToBorrow": "2500000",
// "borrowAmount": "0",
// "accruedInterest": "0",
// "totalOrderIM": "0",
// "totalPositionIM": "2.72589075",
// "totalPositionMM": "0.28576575",
// "unrealisedPnl": "-1.8975",
// "cumRealisedPnl": "0.64782276",
// "bonus": "0"
// },
// {
// "coin": "EOS3L",
// "equity": "215.0570412",
// "usdValue": "0",
// "walletBalance": "215.0570412",
// "availableToWithdraw": "215.0570412",
// "availableToBorrow": "0",
// "borrowAmount": "0",
// "accruedInterest": "",
// "totalOrderIM": "0",
// "totalPositionIM": "0",
// "totalPositionMM": "0",
// "unrealisedPnl": "0",
// "cumRealisedPnl": "0",
// "bonus": "0"
// },
// {
// "coin": "BIT",
// "equity": "1.82",
// "usdValue": "0.48758257",
// "walletBalance": "1.82",
// "availableToWithdraw": "1.82",
// "availableToBorrow": "0",
// "borrowAmount": "0",
// "accruedInterest": "",
// "totalOrderIM": "0",
// "totalPositionIM": "0",
// "totalPositionMM": "0",
// "unrealisedPnl": "0",
// "cumRealisedPnl": "0",
// "bonus": "0"
// }
// ],
// "accountType": "UNIFIED"
// }
// ]
// }
//
if (self.balance.clone() == Value::Null) {
self.balance = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
let mut messageHash: Value = Value::Str("balance".into());
let mut topic: Option<String> = (match message.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
let mut info: Value = Value::Null;
let mut rawBalances: Value = Value::from(vec![]);
let mut account: Value = Value::Null;
if (topic.as_deref() == Some("outboundAccountInfo")) {
account = Value::Str("spot".into());
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
{
let mut i: Value = Value::Int(0);
let mut __for_first_206: bool = true;
while { if !__for_first_206 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_206 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut B: Value = self.safe_list(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), Value::Str("B".into()), &[Value::from(vec![])]);
rawBalances = self.array_concat(rawBalances.clone(), B);
}
}
info = rawBalances.clone();
}
if (topic.as_deref() == Some("wallet")) {
let mut data: Value = (match message.get("data") { Some(__v) if !matches!(__v, Value::Null) && !matches!(__v, Value::Str(__s) if __s.is_empty()) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
{
let mut i: Value = Value::Int(0);
let mut __for_first_207: bool = true;
while { if !__for_first_207 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_207 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&data).as_f64().unwrap_or(f64::NAN) } {
let mut result: Value = self.safe_dict(data.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
account = self.safe_string_lower_k(result.clone(), "accountType", &[]);
rawBalances = self.array_concat(rawBalances.clone(), self.safe_list_k(result, "coin", &[Value::from(vec![])]));
}
}
info = data;
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_208: bool = true;
while { if !__for_first_208 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_208 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawBalances.len() as i64) as f64) } {
self.parse_ws_balance(rawBalances.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), &[account.clone()]);
}
}
if (account != Value::Null) {
if (self.safe_dict(self.balance.clone(), account.clone(), &[]) == Value::Null) {
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&account), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})); }
}
add_element_to_object(get_value_mut(&mut self.balance, &account), &Value::Str("info".into()), info.clone());
let mut timestamp: Value = (match message.get("ts") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
add_element_to_object(get_value_mut(&mut self.balance, &account), &Value::Str("timestamp".into()), timestamp.clone());
{ let __be_tmp = self.iso8601(timestamp.clone()); add_element_to_object(get_value_mut(&mut self.balance, &account), &Value::Str("datetime".into()), __be_tmp); };
{ let __be_tmp = self.safe_balance(get_value(&self.balance, &account)); if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&account), __be_tmp); } }
messageHash = Value::Str(format!("{}{}", Value::Str("balances:".into()), account).into());
client.resolve(&[self.balance.as_map().and_then(|__m| account.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null), messageHash.clone()]);
} else {
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert("info".into(), info); }
let mut timestamp: Value = (match message.get("ts") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
if 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); } }
{ let __t = self.safe_balance(self.balance.clone()); self.balance = __t; }
messageHash = Value::Str("balances".into());
client.resolve(&[self.balance.clone(), messageHash]);
}
}
pub fn parse_ws_balance(&mut self, mut balance: Value, optional_args: &[Value]) {
let mut accountType = get_arg(optional_args, 0, Value::Null);
//
// spot
// {
// "a": "USDT",
// "f": "176.81254174",
// "l": "201.575"
// }
// unified
// {
// "coin": "BTC",
// "equity": "0.06488393",
// "usdValue": "1023.08402268",
// "walletBalance": "0.06488393",
// "availableToWithdraw": "0.06488393",
// "availableToBorrow": "2.5",
// "borrowAmount": "0",
// "accruedInterest": "0",
// "totalOrderIM": "0",
// "totalPositionIM": "0",
// "totalPositionMM": "0",
// "unrealisedPnl": "0",
// "cumRealisedPnl": "0",
// "bonus": "0"
// }
//
let mut account: Value = self.account();
let mut currencyId: Value = self.safe_string2(balance.clone(), Value::Str("a".into()), Value::Str("coin".into()), &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_n(balance.clone(), Value::from(vec![Value::Str("availableToWithdraw".into()), Value::Str("f".into()), Value::Str("free".into())]), &[])); }
let mut used: Value = self.safe_string2(balance.clone(), Value::Str("l".into()), Value::Str("locked".into()), &[]);
if (used != Value::Null) {
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), used); }
} else {
// the unified account wallet stream has no locked field, the margin
// lives in the per coin initial margin fields, so the used amount
// is derived from those, see https://github.com/ccxt/ccxt/issues/24365
let mut totalPositionIm: Value = self.safe_string_k(balance.clone(), "totalPositionIM", &[Value::Str("0".into())]);
let mut totalOrderIm: Value = self.safe_string_k(balance.clone(), "totalOrderIM", &[Value::Str("0".into())]);
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), crate::precise::Precise::stringAdd(&totalPositionIm, &totalOrderIm)); }
}
// on the unified rows the free amount and the margin are both measured
// against the equity, which includes the unrealized pnl, so the equity
// is the consistent total, the spot rows fall back to the wallet balance
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string2(balance.clone(), Value::Str("equity".into()), Value::Str("walletBalance".into()), &[])); }
if (accountType != Value::Null) {
if (self.safe_dict(self.balance.clone(), accountType.clone(), &[]) == Value::Null) {
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&accountType), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})); }
}
if (accountType != Value::Null) && (code != Value::Null) {
add_element_to_object(get_value_mut(&mut self.balance, &accountType), &code, account.clone());
}
} else {
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); }
}
}
}
pub async fn watch_topics(&mut self, mut url: Value, mut messageHashes: Value, mut topics: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut client: Value = self.client(&[url.clone()]);
let mut newTopics: Vec<Value> = Vec::new();
let mut topicsLength: Value = get_array_length(&topics);
let mut messageHashesLength: Value = Value::Int(messageHashes.len() as i64);
if (topicsLength.as_f64() == messageHashesLength.as_f64()) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_209: bool = true;
while { if !__for_first_209 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_209 = false; i.as_f64().unwrap_or(f64::NAN) < topicsLength.as_f64().unwrap_or(f64::NAN) } {
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);
if !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash)) {
newTopics.push(get_value(&topics, &i));
}
}
}
} else {
// watchOrders spot: two topics, one hash. Collect topics already
// recorded on any subscription so a later call with a new hash
// does not resend already-subscribed topics.
let mut subscribedTopics: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut subscriptionHashes: Value = object_keys(&get_value(&client, &Value::Str("subscriptions".into())));
{
let mut i: Value = Value::Int(0);
let mut __for_first_211: bool = true;
while { if !__for_first_211 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_211 = false; i.as_f64().unwrap_or(f64::NAN) < ((subscriptionHashes.len() as i64) as f64) } {
let mut existing: Value = self.safe_dict(get_value(&client, &Value::Str("subscriptions".into())), subscriptionHashes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut recordedTopics: Value = self.safe_list_k(existing, "topics", &[Value::from(vec![])]);
let mut recordedLength: f64 = ((recordedTopics.len() as i64) as f64);
{
let mut j: Value = Value::Int(0);
let mut __for_first_210: bool = true;
while { if !__for_first_210 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_210 = false; j.as_f64().unwrap_or(f64::NAN) < recordedLength } {
add_element_to_object(&mut subscribedTopics, &recordedTopics.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), Value::Bool(true));
}
}
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_212: bool = true;
while { if !__for_first_212 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_212 = false; i.as_f64().unwrap_or(f64::NAN) < topicsLength.as_f64().unwrap_or(f64::NAN) } {
let mut topic: Value = get_value(&topics, &i);
let mut topic: Value = get_value(&topics, &i);
if !(matches!((&subscribedTopics, &topic), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
newTopics.push(topic.clone());
}
}
}
}
let mut message: Value = Value::Null;
let mut subscription: Value = Value::Null;
let mut newTopicsLength: f64 = ((newTopics.len() as i64) as f64);
if newTopicsLength > ((0i64) as f64) {
let mut reqId: Value = self.request_id();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("op".to_string(), Value::Str("subscribe".into()));
m.insert("req_id".to_string(), reqId.clone());
m.insert("args".to_string(), Value::from(newTopics.clone()));
m
});
message = self.extend(request, &[params]);
subscription = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), reqId);
m.insert("topics".to_string(), Value::from(newTopics));
m
});
}
return self.watch_multiple(url, messageHashes.clone(), &[message, messageHashes.clone(), subscription]).await;
Value::Null
}
pub async fn un_watch_topics(&mut self, mut url: Value, mut topic: Value, mut symbols: Value, mut messageHashes: Value, mut subMessageHashes: Value, mut topics: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut subExtension = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut reqId: Value = self.request_id();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("op".to_string(), Value::Str("unsubscribe".into()));
m.insert("req_id".to_string(), reqId.clone());
m.insert("args".to_string(), topics);
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), reqId);
m.insert("topic".to_string(), topic);
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]);
let __ws_arg_0 = self.extend(subscription, &[subExtension]);
return self.watch_multiple(url, messageHashes.clone(), &[message, messageHashes.clone(), __ws_arg_0]).await;
Value::Null
}
pub async fn authenticate(&mut self, mut url: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
let mut messageHash: Value = Value::Str("authenticated".into());
let mut client: Value = self.client(&[url.clone()]);
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) {
let mut expiresInt: Value = (match (&(self.milliseconds()), &(Value::Int(10000))) { (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 });
let mut expires: Value = self.number_to_string(expiresInt);
let mut path: Value = Value::Str("GET/realtime".into());
let mut auth: Value = Value::Str(format!("{}{}", path, expires).into());
let mut signature: Value = self.hmac(self.encode(auth), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[Value::Str("hex".into())]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("op".to_string(), Value::Str("auth".into()));
m.insert("args".to_string(), Value::from(vec![self.apiKey.clone(), expires, signature]));
m
});
let mut message: Value = self.extend(request, &[params]);
self.watch(url, messageHash.clone(), &[message, messageHash.clone()]).await;
}
return crate::exchange_stubs::ws_await_flight(&future).await;
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;
//
// {
// "success": false,
// "ret_msg": "error:invalid op",
// "conn_id": "5e079fdd-9c7f-404d-9dbf-969d650838b5",
// "request": { op: '', args: null }
// }
//
// auth error
//
// {
// "success": false,
// "ret_msg": "error:USVC1111",
// "conn_id": "e73770fb-a0dc-45bd-8028-140e20958090",
// "request": {
// "op": "auth",
// "args": [
// "9rFT6uR4uz9Imkw4Wx",
// "1653405853543",
// "542e71bd85597b4db0290f0ce2d13ed1fd4bb5df3188716c1e9cc69a879f7889"
// ]
// }
//
// { code: '-10009', desc: "Invalid period!" }
//
// {
// "reqId":"1",
// "retCode":170131,
// "retMsg":"Insufficient balance.",
// "op":"order.create",
// "data":{
//
// },
// "header":{
// "X-Bapi-Limit":"20",
// "X-Bapi-Limit-Status":"19",
// "X-Bapi-Limit-Reset-Timestamp":"1714236608944",
// "Traceid":"3d7168a137bf32a947b7e5e6a575ac7f",
// "Timenow":"1714236608946"
// },
// "connId":"cojifin88smerbj9t560-406"
// }
//
let mut code: Value = self.safe_string_n(message.clone(), Value::from(vec![Value::Str("code".into()), Value::Str("ret_code".into()), Value::Str("retCode".into())]), &[]);
let _try_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if (code != Value::Null) && (code.as_str() != Some("0")) {
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), json_stringify(&message)).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), code.clone(), feedback.clone());
let mut msg: Value = self.safe_string2(message.clone(), Value::Str("retMsg".into()), Value::Str("ret_msg".into()), &[]);
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), msg.clone(), feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
let mut success: Value = (match __pro_message.get("success").cloned() { Some(__v) if matches!(__v, Value::Bool(_)) => __v, _ => Value::Null });
if (success != Value::Null) && (!(success.as_bool() == Some(true))) {
let mut ret_msg: Value = (match __pro_message.get("ret_msg").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut request: Value = (match __pro_message.get("request").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut op: Value = self.safe_string_k(request.clone(), "op", &[]);
if (op.as_str() == Some("auth")) {
panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", Value::Str("Authentication failed: ".into()), ret_msg)));
} else {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), ret_msg)));
}
}
return Value::Bool(false);
#[allow(unreachable_code)] { Value::Null }}));
match _try_result { Ok(__try_ok) => { if !matches!(__try_ok, Value::Null) { return __try_ok; } return Value::Null; } Err(_try_err) => { let error: Value = panic_to_value(_try_err);
let mut reqId: Value = self.safe_string2(message.clone(), Value::Str("req_id".into()), Value::Str("reqId".into()), &[]);
let mut foundSubscription: bool = false;
if (reqId != 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_213: bool = true;
while { if !__for_first_213 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_213 = 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;
}
let mut subscription: Value = self.safe_dict(get_value(&client, &Value::Str("subscriptions".into())), messageHash.clone(), &[]);
let mut subId: Value = self.safe_string_k(subscription, "id", &[]);
if (reqId == subId) {
foundSubscription = true;
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
client.reject(&[Value::from(error.clone()), messageHash]);
}
}
}
}
if !foundSubscription {
if (reqId != Value::Null) {
client.reject(&[Value::from(error.clone()), reqId.clone()]);
} else if is_instance(&error, &Value::Str("AuthenticationError".into())) {
let mut authenticatedHash: Value = Value::Str("authenticated".into());
client.reject(&[Value::from(error.clone()), authenticatedHash.clone()]);
if (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &authenticatedHash)) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &authenticatedHash);
}
let mut op: Value = (match __pro_message.get("op").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 (op != Value::Null) && (op.as_str() != Some("auth")) {
// an operation response that carries no reqId, e.g. bybit
// omits it on some permission rejections of trade ops,
// would leave the awaiting future pending forever, and
// since nothing on this client can proceed without
// authentication, reject everything pending, mirroring the
// behavior of unattributable non auth errors, see
// https://github.com/ccxt/ccxt/issues/29361
client.reject(&[Value::from(error.clone())]);
}
} else {
client.reject(&[Value::from(error), reqId]);
}
}
return Value::Bool(true);
} }
Value::Null
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
let mut topic: Value = self.safe_string2(message.clone(), Value::Str("topic".into()), Value::Str("op".into()), &[Value::Str("".into())]);
if (self.handle_error_message(client.clone(), message.clone()).as_bool() == Some(true)) {
return;
}
// contract pong
let mut ret_msg: Option<String> = (match __pro_message.get("ret_msg").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (ret_msg.as_deref() == Some("pong")) || (topic.as_str() == Some("pong")) {
self.handle_pong(client.clone(), message.clone());
return;
}
// spot pong
let mut pong: Value = (match __pro_message.get("pong").cloned() { Some(Value::Int(__n)) => Value::Int(__n), Some(Value::Float(__f)) => Value::Int(__f as i64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
if (pong != Value::Null) {
self.handle_pong(client.clone(), message.clone());
return;
}
// pong
let mut event: Option<String> = (match __pro_message.get("event").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (event.as_deref() == Some("sub")) || (topic.as_str() == Some("subscribe")) {
self.handle_subscription_status(client.clone(), message.clone());
return;
}
let mut methods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderbook".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("kline".to_string(), Value::Str("handle_ohlcv".into()).clone());
m.insert("order".to_string(), Value::Str("handle_order".into()).clone());
m.insert("stopOrder".to_string(), Value::Str("handle_order".into()).clone());
m.insert("ticker".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("trade".to_string(), Value::Str("handle_trades".into()).clone());
m.insert("publicTrade".to_string(), Value::Str("handle_trades".into()).clone());
m.insert("depth".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("wallet".to_string(), Value::Str("handle_balance".into()).clone());
m.insert("outboundAccountInfo".to_string(), Value::Str("handle_balance".into()).clone());
m.insert("execution".to_string(), Value::Str("handle_my_trades".into()).clone());
m.insert("execution.fast".to_string(), Value::Str("handle_my_trades".into()).clone());
m.insert("ticketInfo".to_string(), Value::Str("handle_my_trades".into()).clone());
m.insert("user.openapi.perp.trade".to_string(), Value::Str("handle_my_trades".into()).clone());
m.insert("position".to_string(), Value::Str("handle_positions".into()).clone());
m.insert("liquidation".to_string(), Value::Str("handle_liquidation".into()).clone());
m.insert("allLiquidation".to_string(), Value::Str("handle_liquidation".into()).clone());
m.insert("pong".to_string(), Value::Str("handle_pong".into()).clone());
m.insert("order.create".to_string(), Value::Str("handle_order_ws".into()).clone());
m.insert("order.amend".to_string(), Value::Str("handle_order_ws".into()).clone());
m.insert("order.cancel".to_string(), Value::Str("handle_order_ws".into()).clone());
m.insert("auth".to_string(), Value::Str("handle_authenticate".into()).clone());
m.insert("unsubscribe".to_string(), Value::Str("handle_un_subscribe".into()).clone());
m
});
let mut exacMethod: Value = self.safe_value(methods.clone(), topic.clone(), &[]);
if (exacMethod != Value::Null) {
self.dispatch_ws_handler(&exacMethod, &[client.clone(), message.clone()]);
return;
}
// 'order' is a substring of 'orderbook', so an orderbook topic like
// 'orderbook.50.BTCUSDT' could be wrongly captured by the 'order' key in a
// first-match loop (in Go map iteration order is randomized). Check the
// orderbook prefix explicitly, then fall back to a simple first-match.
if Value::Int(topic.as_str().and_then(|__s| __s.find("orderbook")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_order_book(client.clone(), message.clone());
return;
}
let mut keys: Value = Value::Array(methods.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default());
{
let mut i: Value = Value::Int(0);
let mut __for_first_214: bool = true;
while { if !__for_first_214 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_214 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut key: Value = keys.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if Value::Int(topic.as_str().zip(key.as_str()).and_then(|(__s, __n)| __s.find(__n)).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
let mut method: Value = methods.as_map().and_then(|__m| key.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
self.dispatch_ws_handler(&method, &[client.clone(), message.clone()]);
return;
}
}
}
// unified auth acknowledgement
let mut type_var: Option<String> = (match __pro_message.get("type").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (type_var.as_deref() == Some("AUTH_RESP")) {
self.handle_authenticate(client, message.clone());
}
}
pub fn ping(&mut self, mut client: Value) -> Value {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("req_id".to_string(), self.request_id());
m.insert("op".to_string(), Value::Str("ping".into()));
m
});
Value::Null
}
pub fn handle_pong(&self, mut client: Value, mut message: Value) -> Value {
//
// {
// "success": true,
// "ret_msg": "pong",
// "conn_id": "db3158a0-8960-44b9-a9de-ac350ee13158",
// "request": { op: "ping", args: null }
// }
//
// { pong: 1653296711335 }
//
//
// {
// "req_id": "2",
// "op": "pong",
// "args": [ "1757405570352" ],
// "conn_id": "d266o6hqo29sqmnq4vk0-1yus1"
// }
//
let __ws_arg_1 = self.milliseconds();
crate::set_value(&mut client, &Value::Str("lastPong".into()), self.safe_integer_k(message.clone(), "pong", &[__ws_arg_1]));
return message;
Value::Null
}
pub fn handle_authenticate(&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;
//
// {
// "success": true,
// "ret_msg": '',
// "op": "auth",
// "conn_id": "ce3dpomvha7dha97tvp0-2xh"
// }
//
// {
// "retCode":0,
// "retMsg":"OK",
// "op":"auth",
// "connId":"cojifin88smerbj9t560-404"
// }
//
// {
// "success": true,
// "ret_msg": "",
// "op": "auth",
// "conn_id": "d266o6hqo29sqmnq4vk0-1yus1"
// }
//
let mut success: Value = (match __pro_message.get("success").cloned() { Some(__v) if matches!(__v, Value::Bool(_)) => __v, _ => Value::Null });
let mut code: Value = (match __pro_message.get("retCode").cloned() { Some(Value::Int(__n)) => Value::Int(__n), Some(Value::Float(__f)) => Value::Int(__f as i64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
let mut messageHash: Value = Value::Str("authenticated".into());
if (success.as_bool() == Some(true)) || (code.as_f64() == Some(0.0)) {
let mut future: Value = self.safe_value(get_value(&client, &Value::Str("futures".into())), messageHash.clone(), &[]);
future.resolve(&[Value::Bool(true)]);
} else {
let mut error = Value::from(crate::exchange_errors::authentication_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), json_stringify(&message))));
client.reject(&[Value::from(error), messageHash.clone()]);
if (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash)) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
}
}
return message;
Value::Null
}
pub fn handle_subscription_status(&self, mut client: Value, mut message: Value) -> Value {
return message;
Value::Null
}
pub fn handle_un_subscribe(&mut self, mut client: Value, mut message: Value) -> Value {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {"success":true,"ret_msg":"","conn_id":"7188110e-6908-41e9-b863-6365127e92ad","req_id":"3","op":"unsubscribe"}
//
// client.subscription will be something like:
// {
// "publicTrade.LTCUSDT":true,
// "publicTrade.ADAUSDT":true,
// "unsubscribe:trade:LTC/USDT:USDT": {
// "id":4,
// "subHash": "trade:LTC/USDT"
// },
// }
let mut reqId: Value = (match __pro_message.get("req_id").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut keys: Value = object_keys(&get_value(&client, &Value::Str("subscriptions".into())));
{
let mut i: Value = Value::Int(0);
let mut __for_first_216: bool = true;
while { if !__for_first_216 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_216 = 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 (messageHash.as_str().is_some_and(|__s| __s.starts_with("unsubscribe"))) {
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 (reqId != subId) {
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_215: bool = true;
while { if !__for_first_215 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_215 = 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 = self.safe_string(subMessageHashes.clone(), j.clone(), &[]);
let mut usePrefix: Value = Value::Bool((subHash.as_str() == Some("orders")) || (subHash.as_str() == Some("myTrades")) || (subHash.as_str() == Some("positions")));
self.clean_unsubscription(client.clone(), subHash, unsubHash, &[usePrefix]);
}
}
self.clean_cache(subscription);
}
}
}
return message;
Value::Null
}
}