// 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 CexCore {
pub parent: crate::exchanges::cex::CexCore,
}
impl CexCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::cex::CexCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = CexCore::describe(self);
self.initialize_properties(described);
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for CexCore {
fn nonce(&self, ) -> crate::Value {
crate::exchange::DerivedExchange::nonce(&self.parent)
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_ticker(&self.parent, ticker, market)
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_trade(&self.parent, trade, market)
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_order(&self.parent, order, market)
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_market(&self.parent, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_ohlcv(&self.parent, ohlcv, market)
}
fn parse_order_book(&self, ob: crate::Value, symbol: crate::Value, ts: crate::Value, bk: crate::Value, ak: crate::Value, pk: crate::Value, ak2: crate::Value, ck: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_order_book(&self.parent, ob, symbol, ts, bk, ak, pk, ak2, ck)
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_balance(&self.parent, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_position(&self.parent, position, market)
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_funding_rate(&self.parent, rate, market)
}
fn parse_deposit(&self, tx: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_deposit(&self.parent, tx, currency)
}
fn parse_deposit_address(&self, depositAddress: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_deposit_address(&self.parent, depositAddress, currency)
}
fn parse_last_price(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_last_price(&self.parent, entry, market)
}
fn parse_withdrawal(&self, tx: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_withdrawal(&self.parent, tx, currency)
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_ledger_entry(&self.parent, entry, currency)
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_transfer(&self.parent, transfer, currency)
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_currency(&self.parent, currency)
}
fn parse_bid_ask(&self, bidask: crate::Value, price_key: crate::Value, amount_key: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_bid_ask(&self.parent, bidask, price_key, amount_key, market)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_open_interest(&self.parent, interest, market)
}
fn parse_liquidation(&self, liquidation: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_liquidation(&self.parent, liquidation, market)
}
fn parse_funding_rate_history(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_funding_rate_history(&self.parent, entry, market)
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_margin_modification(&self.parent, data, market)
}
fn parse_account(&self, account: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_account(&self.parent, account)
}
fn parse_my_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_my_trade(&self.parent, trade, market)
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_transaction(&self.parent, transaction, currency)
}
fn parse_borrow_interest(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_borrow_interest(&self.parent, info, market)
}
fn parse_adl_rank(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_adl_rank(&self.parent, info, market)
}
fn parse_income(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_income(&self.parent, info, market)
}
fn parse_greeks(&self, greeks: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_greeks(&self.parent, greeks, market)
}
fn parse_margin_mode(&self, margin_mode: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_margin_mode(&self.parent, margin_mode, market)
}
fn parse_conversion(&self, conversion: crate::Value, from_currency: crate::Value, to_currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_conversion(&self.parent, conversion, from_currency, to_currency)
}
fn parse_borrow_rate(&self, info: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_borrow_rate(&self.parent, info, currency)
}
fn parse_leverage(&self, leverage: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_leverage(&self.parent, leverage, market)
}
fn parse_market_leverage_tiers(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_market_leverage_tiers(&self.parent, info, market)
}
fn parse_deposit_withdraw_fee(&self, fee: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_deposit_withdraw_fee(&self.parent, fee, currency)
}
fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_prediction_trade(&self.parent, trade, market)
}
fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_prediction_order(&self.parent, order, market)
}
fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_prediction_position(&self.parent, position, market)
}
fn create_expired_option_market(&self, symbol: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::create_expired_option_market(&self.parent, symbol)
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::sign(&self.parent, path, api, method, params, headers, body)
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::handle_errors(&self.parent, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for CexCore {
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[..]).await,
"cancel_order_ws" => self.cancel_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders_ws" => self.cancel_orders_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_order_ws" => self.create_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"currency_from_precision" => self.currency_from_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"edit_order_ws" => self.edit_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"fetch_balance_ws" => self.fetch_balance_ws(&args[..]).await,
"fetch_open_orders_ws" => self.fetch_open_orders_ws(&args[..]).await,
"fetch_order_ws" => self.fetch_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_ticker_ws" => self.fetch_ticker_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"from_precision" => self.from_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_connected" => self.handle_connected(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_ohlcv24" => self.handle_ohlcv24(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"pair_to_symbol" => self.pair_to_symbol(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ws_old_trade" => self.parse_ws_old_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_order_update" => self.parse_ws_order_update(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_ticker" => self.parse_ws_ticker(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())..]),
"request_id" => self.request_id(),
"watch_balance" => self.watch_balance(&args[..]).await,
"watch_my_trades" => self.watch_my_trades(&args[..]).await,
"watch_ohlcv" => self.watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_tickers" => self.watch_tickers(&args[..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
// 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 CexCore {
/// 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 },
"cancel_orders_ws" => { crate::exchange_stubs::enqueue_spawn("cancel_orders_ws", args.to_vec()); crate::Value::Null },
"create_order_ws" => { crate::exchange_stubs::enqueue_spawn("create_order_ws", args.to_vec()); crate::Value::Null },
"currency_from_precision" => self.currency_from_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"edit_order_ws" => { crate::exchange_stubs::enqueue_spawn("edit_order_ws", args.to_vec()); crate::Value::Null },
"fetch_balance_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_balance_ws", args.to_vec()); crate::Value::Null },
"fetch_open_orders_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_open_orders_ws", args.to_vec()); crate::Value::Null },
"fetch_order_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_order_ws", args.to_vec()); crate::Value::Null },
"fetch_ticker_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_ticker_ws", args.to_vec()); crate::Value::Null },
"from_precision" => self.from_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_authentication_message" => { self.handle_authentication_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_balance" => { self.handle_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_connected" => self.handle_connected(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(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_init_ohlcv" => { self.handle_init_ohlcv(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_ohlcv1m" => { self.handle_ohlcv1m(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_ohlcv24" => self.handle_ohlcv24(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_order_book_snapshot" => { self.handle_order_book_snapshot(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book_update" => { self.handle_order_book_update(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_update" => { self.handle_order_update(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_orders_snapshot" => { self.handle_orders_snapshot(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_ticker" => { self.handle_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_trade" => { self.handle_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_trades_inner" => { self.handle_trades_inner(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_trades_snapshot" => { self.handle_trades_snapshot(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_transaction" => { self.handle_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"pair_to_symbol" => self.pair_to_symbol(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ws_old_trade" => self.parse_ws_old_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_order_update" => self.parse_ws_order_update(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_ticker" => self.parse_ws_ticker(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())..]),
"request_id" => self.request_id(),
"resolve_data" => { self.resolve_data(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"watch_balance" => { crate::exchange_stubs::enqueue_spawn("watch_balance", args.to_vec()); crate::Value::Null },
"watch_my_trades" => { crate::exchange_stubs::enqueue_spawn("watch_my_trades", args.to_vec()); crate::Value::Null },
"watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("watch_ohlcv", args.to_vec()); crate::Value::Null },
"watch_order_book" => { crate::exchange_stubs::enqueue_spawn("watch_order_book", args.to_vec()); crate::Value::Null },
"watch_orders" => { crate::exchange_stubs::enqueue_spawn("watch_orders", args.to_vec()); crate::Value::Null },
"watch_ticker" => { crate::exchange_stubs::enqueue_spawn("watch_ticker", args.to_vec()); crate::Value::Null },
"watch_tickers" => { crate::exchange_stubs::enqueue_spawn("watch_tickers", args.to_vec()); crate::Value::Null },
"watch_trades" => { crate::exchange_stubs::enqueue_spawn("watch_trades", args.to_vec()); crate::Value::Null },
_ => crate::Value::Null,
}
}
}
impl std::ops::Deref for CexCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for CexCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl CexCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.parent.describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Bool(true));
m.insert("watchBalance".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m.insert("watchTradesForSymbols".to_string(), Value::Bool(false));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOHLCV".to_string(), Value::Bool(true));
m.insert("watchPosition".to_string(), Value::Null);
m.insert("createOrderWs".to_string(), Value::Bool(true));
m.insert("editOrderWs".to_string(), Value::Bool(true));
m.insert("cancelOrderWs".to_string(), Value::Bool(true));
m.insert("cancelOrdersWs".to_string(), Value::Bool(true));
m.insert("fetchOrderWs".to_string(), Value::Bool(true));
m.insert("fetchOpenOrdersWs".to_string(), Value::Bool(true));
m.insert("fetchTickerWs".to_string(), Value::Bool(true));
m.insert("fetchBalanceWs".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::Str("wss://ws.cex.io/ws".into()));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("watchTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), Value::Null);
m
}));
m
}));
m.insert("streaming".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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 to_string_val(&requestId);
Value::Null
}
/*
* @method
* @name cex#watchBalance
* @description watch balance and get the amount of funds available for trading or funds locked in orders
* @see https://cex.io/websocket-api#get-balance
* @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
}));
self.authenticate(&[params.clone()]).await;
let mut messageHash: Value = self.request_id();
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);
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("get-balance".into()));
m.insert("data".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("oid".to_string(), self.request_id());
m
});
let mut request: Value = self.deep_extend(subscribe, &[params]);
return self.watch(url, messageHash.clone(), &[request.clone(), messageHash.clone(), request.clone()]).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);
//
// {
// "e": "get-balance",
// "data": {
// "balance": {
// "BTC": "0.00000000",
// "USD": "0.00",
// ...
// },
// "obalance": {
// "BTC": "0.00000000",
// "USD": "0.00",
// ...
// },
// "time": 1663761159605
// },
// "oid": 1,
// "ok": "ok"
// }
//
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 freeBalance: Value = self.safe_dict_k(data.clone(), "balance", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut usedBalance: Value = self.safe_dict_k(data.clone(), "obalance", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data);
m
});
let mut currencyIds: Value = object_keys(&freeBalance);
{
let mut i: Value = Value::Int(0);
let mut __for_first_227: bool = true;
while { if !__for_first_227 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_227 = false; i.as_f64().unwrap_or(f64::NAN) < ((currencyIds.len() as i64) as f64) } {
let mut currencyId: Value = currencyIds.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut account: Value = self.account();
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string(freeBalance.clone(), currencyId.clone(), &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_string(usedBalance.clone(), currencyId.clone(), &[])); }
let mut code: Value = self.safe_currency_code(currencyId, &[]);
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
}
}
{ let __t = self.safe_balance(result); self.balance = __t; }
let mut messageHash: Value = (match message.get("oid") { 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 });
client.resolve(&[self.balance.clone(), messageHash]);
}
/*
* @method
* @name cex#watchTrades
* @description get the list of most recent trades for a particular symbol. Note: can only watch one symbol at a time.
* @see https://cex.io/websocket-api#old-pair-room
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut currentSymbol: Value = self.safe_string(self.options.as_map().and_then(|__m| __m.get("watchTrades")).cloned().unwrap_or(Value::Null), Value::Str("symbol".into()), &[]);
if (currentSymbol != Value::Null) && (currentSymbol.as_str() != symbol.as_str()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" : this exchange only supports watching trades for one symbol per instance. You should either set .options[\"watchTrades\"][\"symbol\"] to new symbol, or create a new instance".into()))));
}
add_element_to_object(get_value_mut(&mut self.options, &Value::Str("watchTrades".into())), &Value::Str("symbol".into()), symbol.clone());
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut 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);
let mut messageHash: Value = Value::Str("trades".into());
let mut subscriptionHash: Value = Value::Str(format!("{}{}", Value::Str("old:".into()), symbol).into());
let mut client: Value = self.safe_value(self.clients.clone(), url.clone(), &[]);
if (client != Value::Null) {
let mut subscriptionKeys: Value = object_keys(&get_value(&client, &Value::Str("subscriptions".into())));
{
let mut i: Value = Value::Int(0);
let mut __for_first_228: bool = true;
while { if !__for_first_228 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_228 = false; i.as_f64().unwrap_or(f64::NAN) < ((subscriptionKeys.len() as i64) as f64) } {
let mut subscriptionKey: Value = subscriptionKeys.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 (subscriptionKey.as_str() == subscriptionHash.as_str()) {
continue;
}
subscriptionKey = subscriptionKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(0); let __j = __l.min(3); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
if (subscriptionKey.as_str() == Some("old")) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" watchTrades() only supports watching one symbol at a time.".into()))));
}
}
}
}
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("subscribe".into()));
m.insert("rooms".to_string(), Value::from(vec![Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("pair-".into()), market.as_map().and_then(|__m| __m.get("base")).cloned().unwrap_or(Value::Null)).into()), Value::Str("-".into())).into()), market.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null)).into())]));
m
});
let mut request: Value = self.deep_extend(message, &[params]);
let mut trades: Value = self.watch(url, messageHash, &[request, subscriptionHash]).await;
return self.filter_by_since_limit(trades, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
pub fn handle_trades_snapshot(&mut self, mut client: Value, mut message: Value) {
//
// {
// "e": "history",
// "data": [
// 'buy:1710255706095:444444:71222.2:14892622'
// 'sell:1710255658251:42530:71300:14892621'
// 'buy:1710252424241:87913:72800:14892620'
// ... timestamp descending
// ]
// }
//
self.handle_trades_inner(client, message);
}
pub fn parse_ws_old_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// snapshot trade
// "sell:1665467367741:3888551:19058.8:14541219"
//
// update trade
// ['buy', '1665467516704', '98070', "19057.7", "14541220"]
//
if !(matches!(&trade, Value::Arr(_))) {
trade = split(&trade, &Value::Str(":".into()));
}
let mut side: Value = self.safe_string(trade.clone(), Value::Int(0), &[]);
let mut timestamp: Value = self.safe_integer(trade.clone(), Value::Int(1), &[]);
let mut amount: Value = self.safe_string(trade.clone(), Value::Int(2), &[]);
let mut price: Value = self.safe_string(trade.clone(), Value::Int(3), &[]);
let mut id: Value = self.safe_string(trade.clone(), Value::Int(4), &[]);
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade);
m.insert("id".to_string(), id);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), self.safe_string_k(market.clone(), "symbol", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("order".to_string(), Value::Null);
m.insert("takerOrMaker".to_string(), Value::Null);
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
}), &[market]);
Value::Null
}
pub fn handle_trade(&mut self, mut client: Value, mut message: Value) {
//
// {
// "e": "history-update",
// "data": [
// ['buy', '1665467516704', '98070', "19057.7", "14541220"]
// ]
// }
//
self.handle_trades_inner(client, message);
}
pub fn handle_trades_inner(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut symbol: Value = self.safe_string(self.options.as_map().and_then(|__m| __m.get("watchTrades")).cloned().unwrap_or(Value::Null), Value::Str("symbol".into()), &[]);
if (symbol == Value::Null) {
return;
}
if !(in_op(&self.trades, &symbol)) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ArrayCache::new(limit)); }
}
let mut stored: Value = get_value(&self.trades, &symbol);
let mut market: Value = self.market(symbol.clone());
let mut dataLength: Value = Value::Int(data.len() as i64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_229: bool = true;
while { if !__for_first_229 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_229 = false; i.as_f64().unwrap_or(f64::NAN) < dataLength.as_f64().unwrap_or(f64::NAN) } {
let mut index: Value = (match (&((match (&(dataLength), &(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 })), &(i)) { (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 rawTrade: Value = get_value(&data, &index);
let mut rawTrade: Value = get_value(&data, &index);
let mut parsed: Value = self.parse_ws_old_trade(rawTrade, &[market.clone()]);
stored.append(parsed);
}
}
let mut messageHash: Value = Value::Str("trades".into());
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), stored); }
client.resolve(&[get_value(&self.trades, &symbol), messageHash]);
}
/*
* @method
* @name cex#watchTicker
* @see https://cex.io/websocket-api#ticker-subscription
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.method] public or private
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut 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);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbol).into());
let mut method: Option<String> = self.safe_string_k(params.clone(), "method", &[Value::Str("private".into())]).as_str().map(str::to_owned); // default to private because the specified ticker is received quicker
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("subscribe".into()));
m.insert("rooms".to_string(), Value::from(vec![Value::Str("tickers".into())]));
m
});
let mut subscriptionHash: Value = Value::Str("tickers".into());
if (method.as_deref() == Some("private")) {
self.authenticate(&[]).await;
message = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("ticker".into()));
m.insert("data".to_string(), Value::from(vec![market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null), market.as_map().and_then(|__m| __m.get("quoteId")).cloned().unwrap_or(Value::Null)]));
m.insert("oid".to_string(), self.request_id());
m
});
subscriptionHash = Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbol).into());
}
let mut request: Value = self.deep_extend(message, &[params]);
return self.watch(url, messageHash, &[request, subscriptionHash]).await;
Value::Null
}
/*
* @method
* @name cex#watchTickers
* @see https://cex.io/websocket-api#ticker-subscription
* @description watches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @param {string[]|undefined} symbols unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone()]);
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);
let mut messageHash: Value = Value::Str("tickers".into());
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("subscribe".into()));
m.insert("rooms".to_string(), Value::from(vec![Value::Str("tickers".into())]));
m
});
let mut request: Value = self.deep_extend(message, &[params.clone()]);
let mut ticker: Value = self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
let mut tickerSymbol: Value = crate::value::get_value_k(&ticker, "symbol");
if (symbols != Value::Null) && !(self.in_array(tickerSymbol.clone(), symbols.clone()).as_bool() == Some(true)) {
return Box::pin(self.watch_tickers(&[symbols.clone(), params])).await;
}
if is_true(&self.newUpdates) {
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
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()), &[symbols]);
Value::Null
}
/*
* @method
* @name cex#fetchTickerWs
* @see https://docs.cex.io/#ws-api-ticker-deprecated
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_ticker_ws(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
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);
let mut messageHash: Value = self.request_id();
let mut request: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("ticker".into()));
m.insert("oid".to_string(), messageHash.clone());
m.insert("data".to_string(), Value::from(vec![market.as_map().and_then(|__m| __m.get("base")).cloned().unwrap_or(Value::Null), market.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null)]));
m
}), &[params]);
return self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).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);
//
// {
// "e": "tick",
// "data": {
// "symbol1": "LRC",
// "symbol2": "USD",
// "price": "0.305",
// "open24": "0.301",
// "volume": "241421.641700"
// }
// }
//
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 ticker: Value = self.parse_ws_ticker(data, &[]);
let mut symbol: Value = ticker.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (symbol == Value::Null) {
return;
}
if let Value::Dict(__d) = &mut self.tickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker.clone()); }
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbol).into());
client.resolve(&[ticker.clone(), messageHash.clone()]);
client.resolve(&[ticker.clone(), Value::Str("tickers".into())]);
messageHash = (match message.get("oid") { 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 });
if (messageHash != Value::Null) {
client.resolve(&[ticker, messageHash]);
}
}
pub fn parse_ws_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// public
// {
// "symbol1": "LRC",
// "symbol2": "USD",
// "price": "0.305",
// "open24": "0.301",
// "volume": "241421.641700"
// }
// private
// {
// "timestamp": "1663764969",
// "low": "18756.3",
// "high": "19200",
// "last": "19200",
// "volume": "0.94735907",
// "volume30d": "64.61299999",
// "bid": 19217.2,
// "ask": 19247.5,
// "priceChange": "44.3",
// "priceChangePercentage": "0.23",
// "pair": ["BTC", "USDT"]
// }
let mut pair: Value = self.safe_list_k(ticker.clone(), "pair", &[Value::from(vec![])]);
let mut baseId: Value = self.safe_string_k(ticker.clone(), "symbol1", &[]);
if (baseId == Value::Null) {
baseId = self.safe_string(pair.clone(), Value::Int(0), &[]);
}
let mut quoteId: Value = self.safe_string_k(ticker.clone(), "symbol2", &[]);
if (quoteId == Value::Null) {
quoteId = self.safe_string(pair, Value::Int(1), &[]);
}
let mut base: Value = self.safe_currency_code(baseId, &[]);
let mut quote: Value = self.safe_currency_code(quoteId, &[]);
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
let mut timestamp: Value = self.safe_integer_k(ticker.clone(), "timestamp", &[]);
if (timestamp != Value::Null) {
timestamp = (match (&(timestamp), &(Value::Int(1000))) { (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 });
}
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("high".to_string(), self.safe_string_k(ticker.clone(), "high", &[]));
m.insert("low".to_string(), self.safe_string_k(ticker.clone(), "low", &[]));
m.insert("bid".to_string(), self.safe_string_k(ticker.clone(), "bid", &[]));
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), self.safe_string_k(ticker.clone(), "ask", &[]));
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), self.safe_string_k(ticker.clone(), "open24", &[]));
m.insert("close".to_string(), Value::Null);
m.insert("last".to_string(), self.safe_string2(ticker.clone(), Value::Str("price".into()), Value::Str("last".into()), &[]));
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), self.safe_string_k(ticker.clone(), "priceChange", &[]));
m.insert("percentage".to_string(), self.safe_string_k(ticker.clone(), "priceChangePercentage", &[]));
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), self.safe_string_k(ticker.clone(), "volume", &[]));
m.insert("info".to_string(), ticker);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name cex#fetchBalanceWs
* @see https://docs.cex.io/#ws-api-get-balance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @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 fetch_balance_ws(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.authenticate(&[]).await;
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);
let mut messageHash: Value = self.request_id();
let mut request: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("get-balance".into()));
m.insert("oid".to_string(), messageHash.clone());
m
}), &[params]);
return self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
Value::Null
}
/*
* @method
* @name cex#watchOrders
* @description get the list of orders associated with the user. Note: In CEX.IO system, orders can be present in trade engine or in archive database. There can be time periods (~2 seconds or more), when order is done/canceled, but still not moved to archive database. That means, you cannot see it using calls: archived-orders/open-orders.
* @see https://docs.cex.io/#ws-api-open-orders
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchOrders() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.authenticate(&[params.clone()]).await;
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);
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orders:".into()), symbol).into());
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("open-orders".into()));
m.insert("data".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pair".to_string(), Value::from(vec![market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null), market.as_map().and_then(|__m| __m.get("quoteId")).cloned().unwrap_or(Value::Null)]));
m
}));
m.insert("oid".to_string(), symbol.clone());
m
});
let mut request: Value = self.deep_extend(message, &[params]);
let mut orders: Value = self.watch(url, messageHash.clone(), &[request.clone(), messageHash.clone(), request.clone()]).await;
if is_true(&self.newUpdates) {
limit = orders.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_symbol_since_limit(orders, &[symbol, since, limit, Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name cex#watchMyTrades
* @description get the list of trades associated with the user. Note: In CEX.IO system, orders can be present in trade engine or in archive database. There can be time periods (~2 seconds or more), when order is done/canceled, but still not moved to archive database. That means, you cannot see it using calls: archived-orders/open-orders.
* @see https://docs.cex.io/#ws-api-open-orders
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchMyTrades() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.authenticate(&[params.clone()]).await;
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);
let mut market: Value = self.market(symbol);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("myTrades:".into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into());
let mut subscriptionHash: Value = Value::Str(format!("{}{}", Value::Str("orders:".into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into());
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("open-orders".into()));
m.insert("data".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pair".to_string(), Value::from(vec![market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null), market.as_map().and_then(|__m| __m.get("quoteId")).cloned().unwrap_or(Value::Null)]));
m
}));
m.insert("oid".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m
});
let mut request: Value = self.deep_extend(message, &[params]);
let mut orders: Value = self.watch(url, messageHash, &[request.clone(), subscriptionHash, request.clone()]).await;
return self.filter_by_symbol_since_limit(orders, &[market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), since, limit]);
Value::Null
}
pub fn handle_transaction(&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 data: Value = (match __pro_message.get("data").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
let mut symbol2: Option<String> = self.safe_string_k(data, "symbol2", &[]).as_str().map(str::to_owned);
if (symbol2.is_none()) {
return;
}
self.handle_order_update(client.clone(), message.clone());
self.handle_my_trades(client, message);
}
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);
//
// {
// "e": "tx",
// "data": {
// "d": "order:59091012956:a:USD",
// "c": "user:up105393824:a:USD",
// "a": "0.01",
// "ds": 0,
// "cs": "15.27",
// "user": "up105393824",
// "symbol": "USD",
// "order": 59091012956,
// "amount": "-18.49",
// "type": "buy",
// "time": "2022-09-24T19:36:18.466Z",
// "balance": "15.27",
// "id": "59091012966"
// }
// }
// {
// "e": "tx",
// "data": {
// "d": "order:59091012956:a:BTC",
// "c": "user:up105393824:a:BTC",
// "a": "0.00096420",
// "ds": 0,
// "cs": "0.00096420",
// "user": "up105393824",
// "symbol": "BTC",
// "symbol2": "USD",
// "amount": "0.00096420",
// "buy": 59091012956,
// "order": 59091012956,
// "sell": 59090796005,
// "price": 19135,
// "type": "buy",
// "time": "2022-09-24T19:36:18.466Z",
// "balance": "0.00096420",
// "fee_amount": "0.05",
// "id": "59091012962"
// }
// }
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 stored: Value = self.myTrades.clone();
if (stored == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
stored = ArrayCacheBySymbolById::new(limit);
self.myTrades = stored.clone();
}
let mut trade: Value = self.parse_ws_trade(data, &[]);
stored.append(trade.clone());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("myTrades:".into()), trade.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).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);
//
// {
// "d": "order:59091012956:a:BTC",
// "c": "user:up105393824:a:BTC",
// "a": "0.00096420",
// "ds": 0,
// "cs": "0.00096420",
// "user": "up105393824",
// "symbol": "BTC",
// "symbol2": "USD",
// "amount": "0.00096420",
// "buy": 59091012956,
// "order": 59091012956,
// "sell": 59090796005,
// "price": 19135,
// "type": "buy",
// "time": "2022-09-24T19:36:18.466Z",
// "balance": "0.00096420",
// "fee_amount": "0.05",
// "id": "59091012962"
// }
// Note symbol and symbol2 are inverse on sell and amount is in symbol currency.
//
let mut side: Value = self.safe_string_k(trade.clone(), "type", &[]);
let mut price: Value = self.safe_string_k(trade.clone(), "price", &[]);
let mut datetime: Value = self.safe_string_k(trade.clone(), "time", &[]);
let mut baseId: Value = self.safe_string_k(trade.clone(), "symbol", &[]);
let mut quoteId: Value = self.safe_string_k(trade.clone(), "symbol2", &[]);
let mut base: Value = self.safe_currency_code(baseId, &[]);
let mut quote: Value = self.safe_currency_code(quoteId, &[]);
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
let mut amount: Value = self.safe_string_k(trade.clone(), "amount", &[]);
if (side.as_str() == Some("sell")) {
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", quote, Value::Str("/".into())).into()), base).into());
amount = crate::precise::Precise::stringDiv(&amount, &price); // due to rounding errors amount in not exact to trade
}
let mut parsedTrade: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "id", &[]));
m.insert("order".to_string(), self.safe_string_k(trade.clone(), "order", &[]));
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), Value::Null);
m.insert("price".to_string(), price);
m.insert("cost".to_string(), Value::Null);
m.insert("amount".to_string(), amount);
m.insert("fee".to_string(), Value::Null);
m
});
let mut fee: Value = self.safe_string_k(trade, "fee_amount", &[]);
if (fee != Value::Null) {
if let Value::Dict(__d) = &mut parsedTrade { std::sync::Arc::make_mut(__d).insert("fee".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), fee);
m.insert("currency".to_string(), quote);
m.insert("rate".to_string(), Value::Null);
m
})); }
}
return self.safe_trade(parsedTrade, &[market]);
Value::Null
}
pub fn handle_order_update(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// partialExecution
// {
// "e": "order",
// "data": {
// "id": "150714937",
// "remains": "1000000",
// "price": "17513",
// "amount": 2000000, As Precision
// "time": "1654506118448",
// "type": "buy",
// "pair": {
// "symbol1": "BTC",
// "symbol2": "USD"
// },
// "fee": "0.15"
// }
// }
// canceled order
// {
// "e": "order",
// "data": {
// "id": "6310857",
// "remains": "200000000"
// "fremains": "2.00000000"
// "cancel": true,
// "pair": {
// "symbol1": "BTC",
// "symbol2": "USD"
// }
// }
// }
// fulfilledOrder
// {
// "e": "order",
// "data": {
// "id": "59098421630",
// "remains": "0",
// "pair": {
// "symbol1": "BTC",
// "symbol2": "USD"
// }
// }
// }
// {
// "e": "tx",
// "data": {
// "d": "order:59425993014:a:BTC",
// "c": "user:up105393824:a:BTC",
// "a": "0.00098152",
// "ds": 0,
// "cs": "0.00098152",
// "user": "up105393824",
// "symbol": "BTC",
// "symbol2": "USD",
// "amount": "0.00098152",
// "buy": 59425993014,
// "order": 59425993014,
// "sell": 59425986168,
// "price": 19306.6,
// "type": "buy",
// "time": "2022-10-02T01:11:15.148Z",
// "balance": "0.00098152",
// "fee_amount": "0.05",
// "id": "59425993020"
// }
// }
//
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 isTransaction: bool = (match message.get("e") { 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() == Some("tx");
let mut orderId: Value = self.safe_string2(data.clone(), Value::Str("id".into()), Value::Str("order".into()), &[]);
let mut remains: Value = self.safe_string_k(data.clone(), "remains", &[]);
let mut baseId: Value = self.safe_string_k(data.clone(), "symbol", &[]);
let mut quoteId: Value = self.safe_string_k(data.clone(), "symbol2", &[]);
let mut pair: Value = self.safe_dict_k(data.clone(), "pair", &[]);
if (pair != Value::Null) {
baseId = self.safe_string_k(pair.clone(), "symbol1", &[]);
quoteId = self.safe_string_k(pair, "symbol2", &[]);
}
let mut base: Value = self.safe_currency_code(baseId, &[]);
let mut quote: Value = self.safe_currency_code(quoteId, &[]);
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
let mut market: Value = self.safe_market(&[symbol.clone()]);
remains = self.currency_from_precision(base, remains.clone());
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 storedOrders: Value = self.orders.clone();
let mut ordersBySymbol: Value = self.safe_dict(storedOrders.hashmap(), symbol.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut order: Value = self.safe_value(ordersBySymbol, orderId, &[]);
if (order == Value::Null) {
order = self.parse_ws_order_update(data.clone(), &[market]);
}
add_element_to_object(&mut order, &Value::Str("remaining".into()), remains);
let mut canceled: Value = self.safe_bool_k(data.clone(), "cancel", &[Value::Bool(false)]);
if (canceled.as_bool() == Some(true)) {
add_element_to_object(&mut order, &Value::Str("status".into()), Value::Str("canceled".into()));
}
if isTransaction {
add_element_to_object(&mut order, &Value::Str("status".into()), Value::Str("closed".into()));
}
let mut fee: Value = self.safe_number_k(data.clone(), "fee", &[]);
if (fee != Value::Null) {
add_element_to_object(&mut order, &Value::Str("fee".into()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), fee);
m.insert("currency".to_string(), quote);
m.insert("rate".to_string(), Value::Null);
m
}));
}
let mut timestamp: Value = self.safe_integer_k(data, "time", &[]);
add_element_to_object(&mut order, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut order, &Value::Str("datetime".into()), self.iso8601(timestamp));
order = self.safe_order(order.clone(), &[]);
storedOrders.append(order);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orders:".into()), symbol).into());
client.resolve(&[storedOrders, messageHash]);
}
pub fn parse_ws_order_update(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "id": "150714937",
// "remains": "1000000",
// "price": "17513",
// "amount": 2000000, As Precision
// "time": "1654506118448",
// "type": "buy",
// "pair": {
// "symbol1": "BTC",
// "symbol2": "USD"
// },
// "fee": "0.15"
// }
// transaction
// {
// "d": "order:59425993014:a:BTC",
// "c": "user:up105393824:a:BTC",
// "a": "0.00098152",
// "ds": 0,
// "cs": "0.00098152",
// "user": "up105393824",
// "symbol": "BTC",
// "symbol2": "USD",
// "amount": "0.00098152",
// "buy": 59425993014,
// "order": 59425993014,
// "sell": 59425986168,
// "price": 19306.6,
// "type": "buy",
// "time": "2022-10-02T01:11:15.148Z",
// "balance": "0.00098152",
// "fee_amount": "0.05",
// "id": "59425993020"
// }
//
let mut isTransaction: bool = self.safe_string_k(order.clone(), "d", &[]) != Value::Null;
let mut remainsPrecision: Value = self.safe_string_k(order.clone(), "remains", &[]);
let mut remaining: Value = Value::Null;
if (remainsPrecision != Value::Null) {
if (market == Value::Null) {
return Value::Null;
}
remaining = self.currency_from_precision(market.as_map().and_then(|__m| __m.get("base")).cloned().unwrap_or(Value::Null), remainsPrecision);
}
let mut amount: Value = self.safe_string_k(order.clone(), "amount", &[]);
if !isTransaction {
if (market == Value::Null) {
return Value::Null;
}
self.currency_from_precision(market.as_map().and_then(|__m| __m.get("base")).cloned().unwrap_or(Value::Null), amount.clone());
}
let mut baseId: Value = self.safe_string_k(order.clone(), "symbol", &[]);
let mut quoteId: Value = self.safe_string_k(order.clone(), "symbol2", &[]);
let mut pair: Value = self.safe_dict_k(order.clone(), "pair", &[]);
if (pair != Value::Null) {
baseId = self.safe_string_k(order.clone(), "symbol1", &[]);
quoteId = self.safe_string_k(order.clone(), "symbol2", &[]);
}
let mut base: Value = self.safe_currency_code(baseId, &[]);
let mut quote: Value = self.safe_currency_code(quoteId, &[]);
let mut symbol: Value = Value::Null;
if (base != Value::Null) && (quote != Value::Null) {
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
}
market = self.safe_market(&[symbol.clone(), market.clone()]);
let mut time: Value = self.safe_integer_k(order.clone(), "time", &[]);
let mut timestamp: Value = time.clone();
if isTransaction {
timestamp = self.parse8601(time);
}
let mut canceled: Value = self.safe_bool_k(order.clone(), "cancel", &[Value::Bool(false)]);
let mut status: Value = Value::Str("open".into());
if (canceled.as_bool() == Some(true)) {
status = Value::Str("canceled".into());
} else if isTransaction {
status = Value::Str("closed".into());
}
let mut parsedOrder: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string2(order.clone(), Value::Str("id".into()), Value::Str("order".into()), &[]));
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("info".to_string(), order.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), Value::Null);
m.insert("timeInForce".to_string(), Value::Null);
m.insert("postOnly".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_k(order.clone(), "type", &[]));
m.insert("price".to_string(), self.safe_number_k(order.clone(), "price", &[]));
m.insert("stopPrice".to_string(), Value::Null);
m.insert("triggerPrice".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("cost".to_string(), Value::Null);
m.insert("amount".to_string(), amount);
m.insert("filled".to_string(), Value::Null);
m.insert("remaining".to_string(), remaining);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.safe_number2(order.clone(), Value::Str("fee".into()), Value::Str("fee_amount".into()), &[]));
m.insert("currency".to_string(), quote);
m.insert("rate".to_string(), Value::Null);
m
}));
m.insert("trades".to_string(), Value::Null);
m
});
if isTransaction {
if let Value::Dict(__d) = &mut parsedOrder { std::sync::Arc::make_mut(__d).insert("trades".into(), self.parse_ws_trade(order, &[market.clone()])); }
}
return self.safe_order(parsedOrder, &[market]);
Value::Null
}
pub fn from_precision(&self, mut amount: Value, mut scale: Value) -> Value {
if (amount == Value::Null) {
return Value::Null;
}
let mut precise = Precise::new(amount);
{ let __sv_tmp = self.sum(&[get_value(&precise, &Value::Str("decimals".into())), scale]); crate::set_value(&mut precise, &Value::Str("decimals".into()), __sv_tmp); }
precise.reduce();
return to_string_val(&precise);
Value::Null
}
pub fn currency_from_precision(&self, mut currency: Value, mut amount: Value) -> Value {
let mut scale: Value = self.safe_integer_k(get_value(&self.currencies, ¤cy), "precision", &[Value::Int(0)]);
return self.from_precision(amount, scale);
Value::Null
}
pub fn handle_orders_snapshot(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "e": "open-orders",
// "data": [{
// "id": "59098421631",
// "time": "1664062285425",
// "type": "buy",
// "price": "18920",
// "amount": "0.00100000",
// "pending": "0.00100000"
// }],
// "oid": 1,
// "ok": "ok"
// }
//
let mut symbol: Value = (match message.get("oid") { 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 }); // symbol is set as requestId in watchOrders
let mut rawOrders: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut myOrders: Value = self.orders.clone();
if (myOrders == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
myOrders = ArrayCacheBySymbolById::new(limit);
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_230: bool = true;
while { if !__for_first_230 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_230 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawOrders.len() as i64) as f64) } {
let mut rawOrder: Value = 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);
let mut market: Value = self.safe_market(&[symbol.clone()]);
let mut order: Value = self.parse_order(rawOrder, &[market]);
add_element_to_object(&mut order, &Value::Str("status".into()), Value::Str("open".into()));
myOrders.append(order);
}
}
self.orders = myOrders.clone();
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orders:".into()), symbol).into());
let mut ordersLength: Value = get_array_length(&myOrders);
if ordersLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
client.resolve(&[myOrders, messageHash]);
}
}
/*
* @method
* @name cex#watchOrderBook
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://trade.cex.io/docs/#websocket-public-api-calls-order-book-subscribe
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.authenticate(&[]).await;
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut 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);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbol).into());
let mut depth: Value = (if (limit == Value::Null) { Value::Int(0) } else { limit.clone() });
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("order-book-subscribe".into()));
m.insert("data".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pair".to_string(), Value::from(vec![market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null), market.as_map().and_then(|__m| __m.get("quoteId")).cloned().unwrap_or(Value::Null)]));
m.insert("subscribe".to_string(), Value::Bool(true));
m.insert("depth".to_string(), depth);
m
}));
m.insert("oid".to_string(), self.request_id());
m
});
let mut request: Value = self.deep_extend(subscribe, &[params]);
let mut orderbook: Value = self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
return orderbook.limit();
Value::Null
}
pub fn handle_order_book_snapshot(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "e": "order-book-subscribe",
// "data": {
// "timestamp": 1663762032,
// "timestamp_ms": 1663762031680,
// "bids": [
// [ 241.947, 155.91626 ],
// [ 241, 154 ],
// ],
// "asks": [
// [ 242.947, 155.91626 ],
// [ 243, 154 ], ],
// "pair": "BTC:USDT",
// "id": 616267120,
// "sell_total": "13.59066946",
// "buy_total": "163553.625948"
// },
// "oid": "1",
// "ok": "ok"
// }
//
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 pair: Value = self.safe_string_k(data.clone(), "pair", &[]);
let mut symbol: Value = self.pair_to_symbol(pair);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbol).into());
let mut timestamp: Value = self.safe_integer2(data.clone(), Value::Str("timestamp_ms".into()), Value::Str("timestamp".into()), &[]);
let mut incrementalId: Value = self.safe_integer_k(data.clone(), "id", &[]);
let mut orderbook: Value = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut snapshot: Value = self.parse_order_book(data, symbol.clone(), &[timestamp, Value::Str("bids".into()), Value::Str("asks".into())]);
add_element_to_object(&mut snapshot, &Value::Str("nonce".into()), incrementalId.clone());
orderbook.reset(snapshot);
add_element_to_object(get_value_mut(&mut self.options, &Value::Str("orderbook".into())), &symbol, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("incrementalId".to_string(), incrementalId);
m
}));
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]);
}
pub fn pair_to_symbol(&self, mut pair: Value) -> Value {
let mut parts: Value = split(&pair, &Value::Str(":".into()));
let mut baseId: Value = self.safe_string(parts.clone(), Value::Int(0), &[]);
let mut quoteId: Value = self.safe_string(parts, Value::Int(1), &[]);
let mut base: Value = self.safe_currency_code(baseId, &[]);
let mut quote: Value = self.safe_currency_code(quoteId, &[]);
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
return symbol;
Value::Null
}
pub fn handle_order_book_update(&self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "e": "md_update",
// "data": {
// "id": 616267121,
// "pair": "BTC:USDT",
// "time": 1663762031719,
// "bids": [],
// "asks": [
// [122, 23]
// ]
// }
// }
//
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 incrementalId: Value = self.safe_integer_k(data.clone(), "id", &[]);
let mut pair: Value = self.safe_string_k(data.clone(), "pair", &[Value::Str("".into())]);
let mut symbol: Value = self.pair_to_symbol(pair);
let mut storedOrderBook: Value = self.safe_value(self.orderbooks.clone(), symbol.clone(), &[]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbol).into());
if !is_equal(&incrementalId, &add(&storedOrderBook.as_map().and_then(|__m| __m.get("nonce")).cloned().unwrap_or(Value::Null), &Value::Int(1))) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
client.reject(&[Value::Str(format!("{}{}", self.id.clone(), Value::Str(" watchOrderBook() skipped a message".into())).into()), messageHash.clone()]);
return;
}
let mut timestamp: Value = self.safe_integer_k(data.clone(), "time", &[]);
let mut asks: Value = self.safe_list_k(data.clone(), "asks", &[Value::from(vec![])]);
let mut bids: Value = self.safe_list_k(data, "bids", &[Value::from(vec![])]);
self.handle_deltas(storedOrderBook.as_map().and_then(|__m| __m.get("asks")).cloned().unwrap_or(Value::Null), asks);
self.handle_deltas(storedOrderBook.as_map().and_then(|__m| __m.get("bids")).cloned().unwrap_or(Value::Null), bids);
add_element_to_object(&mut storedOrderBook, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut storedOrderBook, &Value::Str("datetime".into()), self.iso8601(timestamp));
add_element_to_object(&mut storedOrderBook, &Value::Str("nonce".into()), incrementalId);
client.resolve(&[storedOrderBook, messageHash]);
}
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_231: bool = true;
while { if !__for_first_231 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_231 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&deltas).as_f64().unwrap_or(f64::NAN) } {
self.handle_delta(bookside.clone(), get_value(&deltas, &i));
}
}
}
/*
* @method
* @name cex#watchOHLCV
* @see https://cex.io/websocket-api#minute-data
* @description watches historical candlestick data containing the open, high, low, and close price, and the volume of a market. It will return the last 120 minutes with the selected timeframe and then 1m candle updates after that.
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents.
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn watch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ohlcv:".into()), symbol).into());
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);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("init-ohlcv".into()));
m.insert("i".to_string(), timeframe);
m.insert("rooms".to_string(), Value::from(vec![Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("pair-".into()), market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null)).into()), Value::Str("-".into())).into()), market.as_map().and_then(|__m| __m.get("quoteId")).cloned().unwrap_or(Value::Null)).into())]));
m
});
let __ws_arg_0 = self.extend(request, &[params]);
let mut ohlcv: Value = self.watch(url, messageHash.clone(), &[__ws_arg_0, messageHash.clone()]).await;
if is_true(&self.newUpdates) {
limit = ohlcv.get_limit(symbol, limit.clone());
}
return self.filter_by_since_limit(ohlcv, &[since, limit, Value::Int(0), Value::Bool(true)]);
Value::Null
}
pub fn handle_init_ohlcv(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "e": "init-ohlcv-data",
// "data": [
// [
// 1663660680,
// "19396.4",
// "19396.4",
// "19396.4",
// "19396.4",
// "1262861"
// ],
// ...
// ],
// "pair": "BTC:USDT"
// }
//
let mut pair: Value = (match message.get("pair") { 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 });
if (pair == Value::Null) {
return;
}
let mut parts: Value = split(&pair, &Value::Str(":".into()));
let mut baseId: Value = self.safe_string(parts.clone(), Value::Int(0), &[]);
let mut quoteId: Value = self.safe_string(parts, Value::Int(1), &[]);
let mut base: Value = self.safe_currency_code(baseId, &[]);
let mut quote: Value = self.safe_currency_code(quoteId, &[]);
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
let mut market: Value = self.safe_market(&[symbol.clone()]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ohlcv:".into()), symbol).into());
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut limit: Value = self.safe_integer_k(self.options.clone(), "OHLCVLimit", &[Value::Int(1000)]);
let mut stored = ArrayCacheByTimestamp::new(limit);
let mut sorted: Value = self.sort_by(data, Value::Int(0), &[]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_232: bool = true;
while { if !__for_first_232 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_232 = false; i.as_f64().unwrap_or(f64::NAN) < ((sorted.len() as i64) as f64) } {
stored.append(self.parse_ohlcv(sorted.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()]));
}
}
if !(in_op(&self.ohlcvs, &symbol)) {
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
})); }
}
add_element_to_object(get_value_mut(&mut self.ohlcvs, &symbol), &Value::Str("unknown".into()), stored.clone());
client.resolve(&[stored, messageHash]);
}
pub fn handle_ohlcv24(&self, mut client: Value, mut message: Value) -> Value {
return message;
Value::Null
}
pub fn handle_ohlcv1m(&self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "e": "ohlcv1m",
// "data": {
// "pair": "BTC:USD",
// "time": "1665436800",
// "o": "19279.6",
// "h": "19279.6",
// "l": "19266.7",
// "c": "19266.7",
// "v": 3343884,
// "d": 3343884
// }
// }
//
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 pair: Value = self.safe_string_k(data.clone(), "pair", &[]);
let mut symbol: Value = self.pair_to_symbol(pair);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ohlcv:".into()), symbol).into());
let mut ohlcv: Value = Value::from(vec![self.safe_timestamp_k(data.clone(), "time", &[]), self.safe_number_k(data.clone(), "o", &[]), self.safe_number_k(data.clone(), "h", &[]), self.safe_number_k(data.clone(), "l", &[]), self.safe_number_k(data.clone(), "c", &[]), self.safe_number_k(data, "v", &[])]);
let mut stored: Value = self.safe_value(self.ohlcvs.clone(), symbol, &[]);
stored.append(ohlcv);
client.resolve(&[stored, messageHash]);
}
pub fn handle_ohlcv(&self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "e": "ohlcv",
// "data": [
// [1665461100, '19068.2', '19068.2', '19068.2', "19068.2", 268478]
// ],
// "pair": "BTC:USD"
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut pair: Value = (match message.get("pair") { 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 symbol: Value = self.pair_to_symbol(pair);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ohlcv:".into()), symbol).into());
// const stored = this.safeValue (this.ohlcvs, symbol);
let mut stored: Value = get_value(&self.ohlcvs, &symbol).as_map().and_then(|__m| __m.get("unknown")).cloned().unwrap_or(Value::Null);
{
let mut i: Value = Value::Int(0);
let mut __for_first_233: bool = true;
while { if !__for_first_233 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_233 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut ohlcv: Value = Value::from(vec![self.safe_timestamp(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::Int(0), &[]), self.safe_number(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::Int(1), &[]), self.safe_number(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::Int(2), &[]), self.safe_number(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::Int(3), &[]), self.safe_number(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::Int(4), &[]), self.safe_number(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::Int(5), &[])]);
stored.append(ohlcv);
}
}
let mut dataLength: f64 = ((data.len() as i64) as f64);
if dataLength > ((0i64) as f64) {
client.resolve(&[stored, messageHash]);
}
}
/*
* @method
* @name cex#fetchOrderWs
* @description fetches information on an order made by the user
* @see https://docs.cex.io/#ws-api-get-order
* @param {string} id the order id
* @param {string} symbol not used by cex fetchOrder
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_order_ws(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.authenticate(&[]).await;
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut data: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), to_string_val(&id));
m
}), &[params]);
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);
let mut messageHash: Value = self.request_id();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("get-order".into()));
m.insert("oid".to_string(), messageHash.clone());
m.insert("data".to_string(), data);
m
});
let mut response: Value = self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
return self.parse_order(response, &[market]);
Value::Null
}
/*
* @method
* @name cex#fetchOpenOrdersWs
* @see https://docs.cex.io/#ws-api-open-orders
* @description fetch all unfilled currently open orders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_orders_ws(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenOrdersWs requires a symbol.".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.authenticate(&[]).await;
let mut market: Value = self.market(symbol);
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);
let mut messageHash: Value = self.request_id();
let mut data: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pair".to_string(), Value::from(vec![market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null), market.as_map().and_then(|__m| __m.get("quoteId")).cloned().unwrap_or(Value::Null)]));
m
}), &[params.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("open-orders".into()));
m.insert("oid".to_string(), messageHash.clone());
m.insert("data".to_string(), data);
m
});
let mut response: Value = self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
return self.parse_orders(response, &[market, since, limit, params]);
Value::Null
}
/*
* @method
* @name cex#createOrderWs
* @see https://docs.cex.io/#ws-api-order-placement
* @description create a trade 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 {boolean} [params.maker_only] Optional, maker only places an order only if offers best sell (<= max) or buy(>= max) price for this pair, if not order placement will be rejected with an error - "Order is not maker"
* @returns {object} an [order structure]{@link https://docs.ccxt.com/en/latest/manual.html#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 (price == Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrderWs requires a price argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.authenticate(&[]).await;
let mut market: Value = self.market(symbol);
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);
let mut messageHash: Value = self.request_id();
let mut data: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pair".to_string(), Value::from(vec![market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null), market.as_map().and_then(|__m| __m.get("quoteId")).cloned().unwrap_or(Value::Null)]));
m.insert("amount".to_string(), amount);
m.insert("price".to_string(), price);
m.insert("type".to_string(), side);
m
}), &[params]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("place-order".into()));
m.insert("oid".to_string(), messageHash.clone());
m.insert("data".to_string(), data);
m
});
let mut rawOrder: Value = self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
return self.parse_order(rawOrder, &[market]);
Value::Null
}
/*
* @method
* @name cex#editOrderWs
* @description edit a trade order
* @see https://docs.cex.io/#ws-api-cancel-replace
* @param {string} id order id
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of the currency you want to trade in units of the base currency
* @param {float|undefined} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/en/latest/manual.html#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 (amount == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires a amount argument".into()))));
}
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires a price argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.authenticate(&[]).await;
let mut market: Value = self.market(symbol);
let mut data: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pair".to_string(), Value::from(vec![market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null), market.as_map().and_then(|__m| __m.get("quoteId")).cloned().unwrap_or(Value::Null)]));
m.insert("type".to_string(), side);
m.insert("amount".to_string(), amount);
m.insert("price".to_string(), price);
m.insert("order_id".to_string(), id);
m
}), &[params]);
let mut messageHash: Value = self.request_id();
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);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("cancel-replace-order".into()));
m.insert("oid".to_string(), messageHash.clone());
m.insert("data".to_string(), data);
m
});
let mut response: Value = self.watch(url, messageHash.clone(), &[request, messageHash.clone(), messageHash.clone()]).await;
return self.parse_order(response, &[market]);
Value::Null
}
/*
* @method
* @name cex#cancelOrderWs
* @see https://docs.cex.io/#ws-api-order-cancel
* @description cancels an open order
* @param {string} id order id
* @param {string} symbol not used by cancelOrder ()
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn 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;
}
self.authenticate(&[]).await;
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut data: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
}), &[params]);
let mut messageHash: Value = self.request_id();
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);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("cancel-order".into()));
m.insert("oid".to_string(), messageHash.clone());
m.insert("data".to_string(), data);
m
});
let mut response: Value = self.watch(url, messageHash.clone(), &[request, messageHash.clone(), messageHash.clone()]).await;
return self.parse_order(response, &[market]);
Value::Null
}
/*
* @method
* @name cex#cancelOrdersWs
* @description cancel multiple orders
* @see https://docs.cex.io/#ws-api-mass-cancel-place
* @param {string[]} ids order ids
* @param {string} symbol not used by cancelOrders()
* @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 cancel_orders_ws(&mut self, mut ids: 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 (symbol != Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" cancelOrderWs does not allow filtering by symbol".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.authenticate(&[]).await;
let mut messageHash: Value = self.request_id();
let mut data: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cancel-orders".to_string(), ids);
m
}), &[params.clone()]);
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);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("mass-cancel-place-orders".into()));
m.insert("oid".to_string(), messageHash.clone());
m.insert("data".to_string(), data);
m
});
let mut response: Value = self.watch(url, messageHash.clone(), &[request, messageHash.clone(), messageHash.clone()]).await;
//
// {
// "cancel-orders": [{
// "order_id": 69202557979,
// "fremains": "0.15000000"
// }],
// "place-orders": [],
// "placed-cancelled": []
// }
//
let mut canceledOrders: Value = self.safe_list_k(response, "cancel-orders", &[]);
return self.parse_orders(canceledOrders, &[Value::Null, Value::Null, Value::Null, params]);
Value::Null
}
pub fn resolve_data(&self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// "e": "open-orders",
// "data": [
// {
// "id": "2477098",
// "time": "1435927928618",
// "type": "buy",
// "price": "241.9477",
// "amount": "0.02000000",
// "pending": "0.02000000"
// },
// ...
// ],
// "oid": "1435927928274_9_open-orders",
// "ok": "ok"
// }
//
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::Null });
let mut messageHash: Value = (match message.get("oid") { 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 });
client.resolve(&[data, messageHash]);
}
pub fn handle_connected(&self, mut client: Value, mut message: Value) -> Value {
return message;
Value::Null
}
pub fn handle_error_message(&self, mut client: Value, mut message: Value) -> Value {
let _try_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut data: Value = self.safe_dict_k(message.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut error: Value = self.safe_string_k(data.clone(), "error", &[]);
let mut event: Value = self.safe_string_k(message.clone(), "e", &[Value::Str("".into())]);
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), event).into()), Value::Str(" ".into())).into()), error).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), error.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), error.clone(), feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
#[allow(unreachable_code)] { Value::Null }}));
if let Err(_try_err) = _try_result { let error: Value = panic_to_value(_try_err);
let mut messageHash: Value = self.safe_string_k(message.clone(), "oid", &[]);
let mut future: Value = self.safe_value(get_value(&client, &Value::Str("futures".into())), messageHash.clone(), &[]);
if (future != Value::Null) {
client.reject(&[Value::from(error.clone()), messageHash]);
return Value::Bool(true);
} else {
panic!("{}", error);
}
}
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 ok: Option<String> = (match __pro_message.get("ok").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 (ok.as_deref() == Some("error")) {
self.handle_error_message(client.clone(), message.clone());
return;
}
let mut event: Value = (match __pro_message.get("e").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 handlers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("auth".to_string(), Value::Str("handle_authentication_message".into()).clone());
m.insert("connected".to_string(), Value::Str("handle_connected".into()).clone());
m.insert("tick".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("ticker".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("init-ohlcv-data".to_string(), Value::Str("handle_init_ohlcv".into()).clone());
m.insert("ohlcv24".to_string(), Value::Str("handle_ohlcv24".into()).clone());
m.insert("ohlcv1m".to_string(), Value::Str("handle_ohlcv1m".into()).clone());
m.insert("ohlcv".to_string(), Value::Str("handle_ohlcv".into()).clone());
m.insert("get-balance".to_string(), Value::Str("handle_balance".into()).clone());
m.insert("order-book-subscribe".to_string(), Value::Str("handle_order_book_snapshot".into()).clone());
m.insert("md_update".to_string(), Value::Str("handle_order_book_update".into()).clone());
m.insert("open-orders".to_string(), Value::Str("resolve_data".into()).clone());
m.insert("order".to_string(), Value::Str("handle_order_update".into()).clone());
m.insert("history-update".to_string(), Value::Str("handle_trade".into()).clone());
m.insert("history".to_string(), Value::Str("handle_trades_snapshot".into()).clone());
m.insert("tx".to_string(), Value::Str("handle_transaction".into()).clone());
m.insert("place-order".to_string(), Value::Str("resolve_data".into()).clone());
m.insert("cancel-replace-order".to_string(), Value::Str("resolve_data".into()).clone());
m.insert("cancel-order".to_string(), Value::Str("resolve_data".into()).clone());
m.insert("mass-cancel-place-orders".to_string(), Value::Str("resolve_data".into()).clone());
m.insert("get-order".to_string(), Value::Str("resolve_data".into()).clone());
m
});
let mut handler: Value = self.safe_value(handlers, event.clone(), &[]);
if (handler != Value::Null) {
self.dispatch_ws_handler(&handler, &[client, message.clone()]);
}
}
pub fn handle_authentication_message(&self, mut client: Value, mut message: Value) {
//
// {
// "e": "auth",
// "data": {
// "ok": "ok"
// },
// "ok": "ok",
// "timestamp":1448034593
// }
//
let mut future: Value = self.safe_value(get_value(&client, &Value::Str("futures".into())), Value::Str("authenticated".into()), &[]);
if (future != Value::Null) {
future.resolve(&[Value::Bool(true)]);
}
}
pub async fn authenticate(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut 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);
let mut client: Value = self.client(&[url.clone()]);
let mut messageHash: Value = Value::Str("authenticated".into());
let mut future: Value = client.reusable_future(Value::Str("authenticated".into()));
let mut authenticated: Value = self.safe_value(get_value(&client, &Value::Str("subscriptions".into())), messageHash.clone(), &[]);
if (authenticated == Value::Null) {
self.check_required_credentials(&[]);
let mut nonce: Value = to_string_val(&self.seconds());
let mut auth: Value = Value::Str(format!("{}{}", nonce, self.apiKey.clone()).into());
let mut signature: Value = self.hmac(self.encode(auth), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("e".to_string(), Value::Str("auth".into()));
m.insert("auth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("key".to_string(), self.apiKey.clone());
m.insert("signature".to_string(), to_upper(&signature));
m.insert("timestamp".to_string(), nonce);
m
}));
m
});
let __ws_arg_1 = self.extend(request, &[params]);
self.watch(url, messageHash.clone(), &[__ws_arg_1, messageHash.clone()]).await;
}
return crate::exchange_stubs::ws_await_flight(&future).await;
Value::Null
}
}