// 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 CoinbaseCore {
pub parent: crate::exchanges::coinbase::CoinbaseCore,
}
impl CoinbaseCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::coinbase::CoinbaseCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = CoinbaseCore::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 CoinbaseCore {
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 CoinbaseCore {
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 {
"create_ws_auth" => self.create_ws_auth(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_heartbeats" => self.handle_heartbeats(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_subscription_status" => self.handle_subscription_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_ws_order" => self.parse_ws_order(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())..]),
"subscribe" => self.subscribe(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"subscribe_multiple" => self.subscribe_multiple(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"un_subscribe" => self.un_subscribe(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"un_subscribe_multiple" => self.un_subscribe_multiple(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"un_watch_order_book" => self.un_watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_orders" => self.un_watch_orders(&args[..]).await,
"un_watch_ticker" => self.un_watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_tickers" => self.un_watch_tickers(&args[..]).await,
"un_watch_trades" => self.un_watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_trades_for_symbols" => self.un_watch_trades_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book_for_symbols" => self.watch_order_book_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_tickers" => self.watch_tickers(&args[..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_trades_for_symbols" => self.watch_trades_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
// Go-style inheritance: an un-overridden method dispatches to the parent core.
_ => crate::exchange_generated::ExchangeBase::call_dynamic(&mut self.parent, method, args).await,
}
})
}
}
impl CoinbaseCore {
/// 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 {
"create_ws_auth" => self.create_ws_auth(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_heartbeats" => self.handle_heartbeats(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order" => { self.handle_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book" => { self.handle_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book_helper" => { self.handle_order_book_helper(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_subscription_status" => self.handle_subscription_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_tickers" => { self.handle_tickers(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_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 },
"parse_ws_order" => self.parse_ws_order(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())..]),
"subscribe" => { crate::exchange_stubs::enqueue_spawn("subscribe", args.to_vec()); crate::Value::Null },
"subscribe_multiple" => { crate::exchange_stubs::enqueue_spawn("subscribe_multiple", args.to_vec()); crate::Value::Null },
"try_resolve_usdc" => { self.try_resolve_usdc(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"un_subscribe" => { crate::exchange_stubs::enqueue_spawn("un_subscribe", args.to_vec()); crate::Value::Null },
"un_subscribe_multiple" => { crate::exchange_stubs::enqueue_spawn("un_subscribe_multiple", args.to_vec()); crate::Value::Null },
"un_watch_order_book" => { crate::exchange_stubs::enqueue_spawn("un_watch_order_book", args.to_vec()); crate::Value::Null },
"un_watch_orders" => { crate::exchange_stubs::enqueue_spawn("un_watch_orders", args.to_vec()); crate::Value::Null },
"un_watch_ticker" => { crate::exchange_stubs::enqueue_spawn("un_watch_ticker", args.to_vec()); crate::Value::Null },
"un_watch_tickers" => { crate::exchange_stubs::enqueue_spawn("un_watch_tickers", args.to_vec()); crate::Value::Null },
"un_watch_trades" => { crate::exchange_stubs::enqueue_spawn("un_watch_trades", args.to_vec()); crate::Value::Null },
"un_watch_trades_for_symbols" => { crate::exchange_stubs::enqueue_spawn("un_watch_trades_for_symbols", args.to_vec()); crate::Value::Null },
"watch_order_book" => { crate::exchange_stubs::enqueue_spawn("watch_order_book", args.to_vec()); crate::Value::Null },
"watch_order_book_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_order_book_for_symbols", args.to_vec()); crate::Value::Null },
"watch_orders" => { crate::exchange_stubs::enqueue_spawn("watch_orders", args.to_vec()); crate::Value::Null },
"watch_ticker" => { crate::exchange_stubs::enqueue_spawn("watch_ticker", args.to_vec()); crate::Value::Null },
"watch_tickers" => { crate::exchange_stubs::enqueue_spawn("watch_tickers", args.to_vec()); crate::Value::Null },
"watch_trades" => { crate::exchange_stubs::enqueue_spawn("watch_trades", args.to_vec()); crate::Value::Null },
"watch_trades_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_trades_for_symbols", args.to_vec()); crate::Value::Null },
_ => crate::Value::Null,
}
}
}
impl std::ops::Deref for CoinbaseCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for CoinbaseCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl CoinbaseCore {
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("cancelAllOrdersWs".to_string(), Value::Bool(false));
m.insert("cancelOrdersWs".to_string(), Value::Bool(false));
m.insert("cancelOrderWs".to_string(), Value::Bool(false));
m.insert("createOrderWs".to_string(), Value::Bool(false));
m.insert("editOrderWs".to_string(), Value::Bool(false));
m.insert("fetchBalanceWs".to_string(), Value::Bool(false));
m.insert("fetchOpenOrdersWs".to_string(), Value::Bool(false));
m.insert("fetchOrderWs".to_string(), Value::Bool(false));
m.insert("fetchTradesWs".to_string(), Value::Bool(false));
m.insert("watchBalance".to_string(), Value::Bool(false));
m.insert("watchMyTrades".to_string(), Value::Bool(false));
m.insert("watchOHLCV".to_string(), Value::Bool(false));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOrderBookForSymbols".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m.insert("watchTradesForSymbols".to_string(), Value::Bool(true));
m.insert("unWatchTicker".to_string(), Value::Bool(true));
m.insert("unWatchTickers".to_string(), Value::Bool(true));
m.insert("unWatchTrades".to_string(), Value::Bool(true));
m.insert("unWatchOrders".to_string(), Value::Bool(true));
m.insert("unWatchTradesForSymbols".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Str("wss://advanced-trade-ws.coinbase.com".into()));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tradesLimit".to_string(), Value::Int(1000));
m.insert("ordersLimit".to_string(), Value::Int(1000));
m.insert("myTradesLimit".to_string(), Value::Int(1000));
m.insert("sides".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("bid".to_string(), Value::Str("bids".into()));
m.insert("offer".to_string(), Value::Str("asks".into()));
m
}));
m
}));
m
})]);
Value::Null
}
/*
* @ignore
* @method
* @description subscribes to a websocket channel
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-overview#subscribe
* @param {string} name the name of the channel
* @param {boolean} isPrivate whether the channel is private or not
* @param {string} [symbol] unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} subscription to a websocket channel
*/
pub async fn subscribe(&mut self, mut name: Value, mut isPrivate: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
let mut messageHash: Value = name.clone();
let mut productIds: Value = Value::from(vec![]);
if (matches!(&symbol, Value::Arr(_))) {
let mut symbols: Value = self.market_symbols(&[symbol.clone()]);
let mut marketIds: Value = self.market_ids(&[symbols.clone()]);
if (marketIds == Value::Null) {
productIds = Value::from(vec![]);
} else {
productIds = marketIds;
}
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", messageHash, Value::Str("::".into())).into()), join(&symbols, &Value::Str(",".into()))).into());
} else if (symbol != Value::Null) {
market = self.market(symbol.clone());
messageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", name, Value::Str("::".into())).into()), symbol).into());
productIds = Value::from(vec![market.as_map().and_then(|__m| __m.get("id")).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 subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("subscribe".into()));
m.insert("product_ids".to_string(), productIds.clone());
m.insert("channel".to_string(), name.clone());
m
});
if is_true(&isPrivate) {
let __ws_arg_0 = self.create_ws_auth(name, productIds);
subscribe = self.extend(subscribe.clone(), &[__ws_arg_0]);
}
return self.watch(url, messageHash.clone(), &[subscribe, messageHash.clone()]).await;
Value::Null
}
/*
* @ignore
* @method
* @description unSubscribes to a websocket channel
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-overview#subscribe
* @param {string} topic unified topic
* @param {string} name the name of the channel
* @param {boolean} isPrivate whether the channel is private or not
* @param {string} [symbol] unified market symbol
* @returns {object} subscription to a websocket channel
*/
pub async fn un_subscribe(&mut self, mut topic: Value, mut name: Value, mut isPrivate: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if matches!(self.safe_bool_k(self.options.clone(), "unSubscriptionPending", &[Value::Bool(false)]), Value::Bool(true)) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" another unSubscription is pending, coinbase does not support concurrent unSubscriptions".into()))));
}
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("unSubscriptionPending".into(), Value::Bool(true)); }
let mut market: Value = Value::Null;
let mut watchMessageHash: Value = name.clone();
let mut unWatchMessageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), name).into());
let mut productIds: Value = Value::from(vec![]);
if (matches!(&symbol, Value::Arr(_))) {
let mut symbols: Value = self.market_symbols(&[symbol.clone()]);
let mut marketIds: Value = self.market_ids(&[symbols.clone()]);
if (marketIds == Value::Null) {
productIds = Value::from(vec![]);
} else {
productIds = marketIds;
}
watchMessageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", watchMessageHash, Value::Str("::".into())).into()), join(&symbols, &Value::Str(",".into()))).into());
unWatchMessageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", unWatchMessageHash, Value::Str("::".into())).into()), join(&symbols, &Value::Str(",".into()))).into());
} else if (symbol != Value::Null) {
market = self.market(symbol.clone());
watchMessageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", name, Value::Str("::".into())).into()), symbol).into());
unWatchMessageHash = Value::Str(format!("{}{}", Value::Str(format!("{}{}", unWatchMessageHash, Value::Str("::".into())).into()), symbol).into());
productIds = Value::from(vec![market.as_map().and_then(|__m| __m.get("id")).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);
// '{"type": "unsubscribe", "product_ids": ["BTC-USD", "ETH-USD"], "channel": "ticker"}'
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("unsubscribe".into()));
m.insert("product_ids".to_string(), productIds.clone());
m.insert("channel".to_string(), name.clone());
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("messageHashes".to_string(), Value::from(vec![unWatchMessageHash.clone()]));
m.insert("subMessageHashes".to_string(), Value::from(vec![watchMessageHash]));
m.insert("topic".to_string(), topic);
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("symbols".to_string(), Value::from(vec![symbol]));
m
});
if is_true(&isPrivate) {
let __ws_arg_1 = self.create_ws_auth(name, productIds);
message = self.extend(message.clone(), &[__ws_arg_1]);
}
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("unSubscription".into(), subscription.clone()); }
let mut res: Value = self.watch(url, unWatchMessageHash.clone(), &[message, unWatchMessageHash.clone(), subscription]).await;
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("unSubscriptionPending".into(), Value::Bool(false)); }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("unSubscription".into(), Value::Null); }
return res;
Value::Null
}
/*
* @ignore
* @method
* @description subscribes to a websocket channel
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-overview#subscribe
* @param {string} name the name of the channel
* @param {boolean} isPrivate whether the channel is private or not
* @param {string[]} [symbols] unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} subscription to a websocket channel
*/
pub async fn subscribe_multiple(&mut self, mut name: Value, mut isPrivate: Value, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut productIds: Value = Value::from(vec![]);
let mut messageHashes: Value = Value::from(vec![]);
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false)]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_254: bool = true;
while { if !__for_first_254 { 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_254 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol.clone());
let mut marketId: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
append_to_array(&mut productIds, marketId);
append_to_array(&mut messageHashes, Value::Str(format!("{}{}", Value::Str(format!("{}{}", name, Value::Str("::".into())).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 subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("subscribe".into()));
m.insert("product_ids".to_string(), productIds.clone());
m.insert("channel".to_string(), name.clone());
m
});
if is_true(&isPrivate) {
let __ws_arg_2 = self.create_ws_auth(name, productIds);
subscribe = self.extend(subscribe.clone(), &[__ws_arg_2]);
}
return self.watch_multiple(url, messageHashes.clone(), &[subscribe, messageHashes.clone()]).await;
Value::Null
}
/*
* @ignore
* @method
* @description unsubscribes to a websocket channel
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-overview#subscribe
* @param {string} topic unified topic
* @param {string} name the name of the channel
* @param {boolean} isPrivate whether the channel is private or not
* @param {string[]} [symbols] unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} subscription to a websocket channel
*/
pub async fn un_subscribe_multiple(&mut self, mut topic: Value, mut name: Value, mut isPrivate: Value, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if matches!(self.safe_bool_k(self.options.clone(), "unSubscriptionPending", &[Value::Bool(false)]), Value::Bool(true)) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" another unSubscription is pending, coinbase does not support concurrent unSubscriptions".into()))));
}
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("unSubscriptionPending".into(), Value::Bool(true)); }
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut productIds: Value = Value::from(vec![]);
let mut watchMessageHashes: Value = Value::from(vec![]);
let mut unWatchMessageHashes: Value = Value::from(vec![]);
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false)]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_255: bool = true;
while { if !__for_first_255 { 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_255 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol.clone());
let mut marketId: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
append_to_array(&mut productIds, marketId);
append_to_array(&mut watchMessageHashes, Value::Str(format!("{}{}", Value::Str(format!("{}{}", name, Value::Str("::".into())).into()), symbol).into()));
append_to_array(&mut unWatchMessageHashes, Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), name).into()), Value::Str("::".into())).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 message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("unsubscribe".into()));
m.insert("product_ids".to_string(), productIds.clone());
m.insert("channel".to_string(), name.clone());
m
});
if is_true(&isPrivate) {
let __ws_arg_3 = self.create_ws_auth(name, productIds);
message = self.extend(message.clone(), &[__ws_arg_3]);
}
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("messageHashes".to_string(), unWatchMessageHashes.clone());
m.insert("subMessageHashes".to_string(), watchMessageHashes);
m.insert("topic".to_string(), topic);
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("symbols".to_string(), symbols);
m
});
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("unSubscription".into(), subscription.clone()); }
let mut res: Value = self.watch_multiple(url, unWatchMessageHashes.clone(), &[message, unWatchMessageHashes.clone(), subscription]).await;
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("unSubscriptionPending".into(), Value::Bool(false)); }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("unSubscription".into(), Value::Null); }
return res;
Value::Null
}
pub fn create_ws_auth(&mut self, mut name: Value, mut productIds: Value) -> Value {
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut timestamp: Value = self.number_to_string(self.seconds());
self.check_required_credentials(&[]);
let mut isCloudAPiKey: bool = (Value::Int(self.apiKey.as_str().and_then(|__s| __s.find("organizations/")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64)) || (starts_with(&self.secret, &Value::Str("-----BEGIN".into())));
let mut auth: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", timestamp, name).into()), join(&productIds, &Value::Str(",".into()))).into());
if !isCloudAPiKey {
if let Value::Dict(__d) = &mut subscribe { std::sync::Arc::make_mut(__d).insert("api_key".into(), self.apiKey.clone()); }
if let Value::Dict(__d) = &mut subscribe { std::sync::Arc::make_mut(__d).insert("timestamp".into(), timestamp); }
if let Value::Dict(__d) = &mut subscribe { std::sync::Arc::make_mut(__d).insert("signature".into(), self.hmac(self.encode(auth), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[])); }
} else {
if (starts_with(&self.apiKey, &Value::Str("-----BEGIN".into()))) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" apiKey should contain the name (eg: organizations/3b910e93....) and not the public key".into()))));
}
let mut currentToken: Option<String> = self.safe_string_k(self.options.clone(), "wsToken", &[]).as_str().map(str::to_owned);
let mut tokenTimestamp: Value = self.safe_integer_k(self.options.clone(), "wsTokenTimestamp", &[Value::Int(0)]);
let mut seconds: Value = self.seconds();
if (currentToken.is_none()) || (match (&(tokenTimestamp), &(Value::Int(120))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }).as_f64().unwrap_or(f64::NAN) < seconds.as_f64().unwrap_or(f64::NAN) {
// we should generate new token
let mut token: Value = self.parent.create_auth_token(seconds.clone(), &[]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("wsToken".into(), token); }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("wsTokenTimestamp".into(), seconds); }
}
if let Value::Dict(__d) = &mut subscribe { std::sync::Arc::make_mut(__d).insert("jwt".into(), self.safe_string_k(self.options.clone(), "wsToken", &[])); }
}
return subscribe;
Value::Null
}
/*
* @method
* @name coinbase#watchTicker
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#ticker-channel
* @param {string} [symbol] unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("ticker".into());
return self.subscribe(name, Value::Bool(false), &[symbol, params]).await;
Value::Null
}
/*
* @method
* @name coinbase#unWatchTicker
* @description stops watching a price ticker
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#ticker-channel
* @param {string} [symbol] unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn un_watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("ticker".into());
return self.un_subscribe(Value::Str("ticker".into()), name, Value::Bool(false), &[symbol]).await;
Value::Null
}
/*
* @method
* @name coinbase#watchTickers
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#ticker-batch-channel
* @param {string[]} [symbols] unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbols == Value::Null) {
symbols = self.symbols.clone();
}
let mut name: Value = Value::Str("ticker_batch".into());
let mut ticker: Value = self.subscribe_multiple(name, Value::Bool(false), &[symbols, params]).await;
if is_true(&self.newUpdates) {
let mut tickers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut symbol: Value = crate::value::get_value_k(&ticker, "symbol");
if let Value::Dict(__d) = &mut tickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker); }
return tickers;
}
return self.tickers.clone();
Value::Null
}
/*
* @method
* @name coinbase#unWatchTickers
* @description stop watching
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#ticker-batch-channel
* @param {string[]} [symbols] unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn un_watch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbols == Value::Null) {
symbols = self.symbols.clone();
}
return self.un_subscribe_multiple(Value::Str("ticker".into()), Value::Str("ticker_batch".into()), Value::Bool(false), &[symbols]).await;
Value::Null
}
pub fn handle_tickers(&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;
//
// {
// "channel": "ticker",
// "client_id": "",
// "timestamp": "2023-02-09T20:30:37.167359596Z",
// "sequence_num": 0,
// "events": [
// {
// "type": "snapshot",
// "tickers": [
// {
// "type": "ticker",
// "product_id": "BTC-USD",
// "price": "21932.98",
// "volume_24_h": "16038.28770938",
// "low_24_h": "21835.29",
// "high_24_h": "23011.18",
// "low_52_w": "15460",
// "high_52_w": "48240",
// "price_percent_chg_24_h": "-4.15775596190603"
// new as of 2024-04-12
// "best_bid":"21835.29",
// "best_bid_quantity": "0.02000000",
// "best_ask":"23011.18",
// "best_ask_quantity": "0.01500000"
// }
// ]
// }
// ]
// }
//
// {
// "channel": "ticker_batch",
// "client_id": "",
// "timestamp": "2023-03-01T12:15:18.382173051Z",
// "sequence_num": 0,
// "events": [
// {
// "type": "snapshot",
// "tickers": [
// {
// "type": "ticker",
// "product_id": "DOGE-USD",
// "price": "0.08212",
// "volume_24_h": "242556423.3",
// "low_24_h": "0.07989",
// "high_24_h": "0.08308",
// "low_52_w": "0.04908",
// "high_52_w": "0.1801",
// "price_percent_chg_24_h": "0.50177456859626"
// new as of 2024-04-12
// "best_bid":"0.07989",
// "best_bid_quantity": "500.0",
// "best_ask":"0.08308",
// "best_ask_quantity": "300.0"
// }
// ]
// }
// ]
// }
//
// note! seems coinbase might also send empty data like:
//
// {
// "channel": "ticker_batch",
// "client_id": "",
// "timestamp": "2024-05-24T18:22:24.546809523Z",
// "sequence_num": 1,
// "events": [
// {
// "type": "snapshot",
// "tickers": [
// {
// "type": "ticker",
// "product_id": "",
// "price": "",
// "volume_24_h": "",
// "low_24_h": "",
// "high_24_h": "",
// "low_52_w": "",
// "high_52_w": "",
// "price_percent_chg_24_h": ""
// }
// ]
// }
// ]
// }
//
//
let mut channel: Value = (match __pro_message.get("channel").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut events: Value = (match __pro_message.get("events").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
let mut datetime: Value = self.safe_string_k(message, "timestamp", &[]);
let mut timestamp: Value = self.parse8601(datetime.clone());
let mut newTickers: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_257: bool = true;
while { if !__for_first_257 { 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_257 = false; i.as_f64().unwrap_or(f64::NAN) < ((events.len() as i64) as f64) } {
let mut tickersObj: Value = events.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 tickers: Value = self.safe_list_k(tickersObj, "tickers", &[Value::from(vec![])]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_256: bool = true;
while { if !__for_first_256 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_256 = false; j.as_f64().unwrap_or(f64::NAN) < ((tickers.len() as i64) as f64) } {
let mut ticker: Value = tickers.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut wsMarketId: Option<String> = self.safe_string_k(ticker.clone(), "product_id", &[]).as_str().map(str::to_owned);
if (wsMarketId.is_none()) {
continue;
}
let mut result: Value = self.parse_ws_ticker(ticker, &[]);
add_element_to_object(&mut result, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut result, &Value::Str("datetime".into()), datetime.clone());
let mut symbol: Value = result.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut self.tickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), result.clone()); }
}
append_to_array(&mut newTickers, result.clone());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", channel, Value::Str("::".into())).into()), symbol).into());
client.resolve(&[result.clone(), messageHash.clone()]);
self.try_resolve_usdc(client.clone(), messageHash, result);
}
}
}
}
}
pub fn parse_ws_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "type": "ticker",
// "product_id": "DOGE-USD",
// "price": "0.08212",
// "volume_24_h": "242556423.3",
// "low_24_h": "0.07989",
// "high_24_h": "0.08308",
// "low_52_w": "0.04908",
// "high_52_w": "0.1801",
// "price_percent_chg_24_h": "0.50177456859626"
// new as of 2024-04-12
// "best_bid":"0.07989",
// "best_bid_quantity": "500.0",
// "best_ask":"0.08308",
// "best_ask_quantity": "300.0"
// }
//
let mut marketId: Value = self.safe_string_k(ticker.clone(), "product_id", &[]);
let mut timestamp: Value = Value::Null;
let mut last: Value = self.safe_number_k(ticker.clone(), "price", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), ticker.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market, Value::Str("-".into())]));
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_24_h", &[]));
m.insert("low".to_string(), self.safe_string_k(ticker.clone(), "low_24_h", &[]));
m.insert("bid".to_string(), self.safe_string_k(ticker.clone(), "best_bid", &[]));
m.insert("bidVolume".to_string(), self.safe_string_k(ticker.clone(), "best_bid_quantity", &[]));
m.insert("ask".to_string(), self.safe_string_k(ticker.clone(), "best_ask", &[]));
m.insert("askVolume".to_string(), self.safe_string_k(ticker.clone(), "best_ask_quantity", &[]));
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last);
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), self.safe_string_k(ticker.clone(), "price_percent_chg_24_h", &[]));
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), self.safe_string_k(ticker, "volume_24_h", &[]));
m.insert("quoteVolume".to_string(), Value::Null);
m
}), &[]);
Value::Null
}
/*
* @method
* @name coinbase#watchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#market-trades-channel
* @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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbol = self.symbol(symbol.clone());
let mut name: Value = Value::Str("market_trades".into());
let mut trades: Value = self.subscribe(name, Value::Bool(false), &[symbol.clone(), params]).await;
if is_true(&self.newUpdates) {
limit = trades.get_limit(symbol, limit.clone());
}
return self.filter_by_since_limit(trades, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name coinbase#unWatchTrades
* @description stops watching the list of most recent trades for a particular symbol
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#market-trades-channel
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn un_watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("market_trades".into());
return self.un_subscribe(Value::Str("trades".into()), name, Value::Bool(false), &[symbol]).await;
Value::Null
}
/*
* @method
* @name coinbase#watchTradesForSymbols
* @description get the list of most recent trades for a particular symbol
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#market-trades-channel
* @param {string[]} symbols unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_trades_for_symbols(&mut self, mut symbols: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("market_trades".into());
let mut trades: Value = self.subscribe_multiple(name, Value::Bool(false), &[symbols, params]).await;
if is_true(&self.newUpdates) {
let mut first: Value = self.safe_dict(trades.clone(), Value::Int(0), &[]);
let mut tradeSymbol: Value = self.safe_string_k(first, "symbol", &[]);
limit = trades.get_limit(tradeSymbol, limit.clone());
}
return self.filter_by_since_limit(trades, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name coinbase#unWatchTradesForSymbols
* @description get the list of most recent trades for a particular symbol
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#market-trades-channel
* @param {string[]} symbols unified symbol of the market to fetch trades for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn un_watch_trades_for_symbols(&mut self, mut symbols: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("market_trades".into());
return self.un_subscribe_multiple(Value::Str("trades".into()), name, Value::Bool(false), &[symbols, params]).await;
Value::Null
}
/*
* @method
* @name coinbase#watchOrders
* @description watches information on multiple orders made by the user
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#user-channel
* @param {string} [symbol] unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn watch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("user".into());
let mut orders: Value = self.subscribe(name, Value::Bool(true), &[symbol.clone(), params]).await;
if is_true(&self.newUpdates) {
limit = orders.get_limit(symbol, limit.clone());
}
return self.filter_by_since_limit(orders, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name coinbase#unWatchOrders
* @description stops watching information on multiple orders made by the user
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#user-channel
* @param {string} [symbol] unified market symbol of the market orders were made in
* @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 un_watch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("user".into());
return self.un_subscribe(Value::Str("orders".into()), name, Value::Bool(true), &[self.symbol(symbol.clone())]).await;
Value::Null
}
/*
* @method
* @name coinbase#watchOrderBook
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#level2-channel
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("level2".into());
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 orderbook: Value = self.subscribe(name, Value::Bool(false), &[symbol, params]).await;
return orderbook.limit();
Value::Null
}
/*
* @method
* @name coinbase#unWatchOrderBook
* @description stops watching information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#level2-channel
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn un_watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbol = self.symbol(symbol.clone());
let mut name: Value = Value::Str("level2".into());
return self.un_subscribe(Value::Str("orderbook".into()), name, Value::Bool(false), &[symbol]).await;
Value::Null
}
/*
* @method
* @name coinbase#watchOrderBookForSymbols
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#level2-channel
* @param {string[]} symbols unified array of symbols
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn watch_order_book_for_symbols(&mut self, mut symbols: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut name: Value = Value::Str("level2".into());
let mut orderbook: Value = self.subscribe_multiple(name, Value::Bool(false), &[symbols, params]).await;
return orderbook.limit();
Value::Null
}
pub fn handle_trade(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "channel": "market_trades",
// "client_id": "",
// "timestamp": "2023-02-09T20:19:35.39625135Z",
// "sequence_num": 0,
// "events": [
// {
// "type": "snapshot",
// "trades": [
// {
// "trade_id": "000000000",
// "product_id": "ETH-USD",
// "price": "1260.01",
// "size": "0.3",
// "side": "BUY",
// "time": "2019-08-14T20:42:27.265Z",
// }
// ]
// }
// ]
// }
//
let mut events: Value = (match message.get("events") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::Null });
if (events == Value::Null) {
return;
}
let mut event: Value = self.safe_dict(events.clone(), Value::Int(0), &[]);
let mut trades: Value = self.safe_list_k(event, "trades", &[]);
let mut trade: Value = self.safe_dict(trades.clone(), Value::Int(0), &[]);
let mut marketId: Value = self.safe_string_k(trade, "product_id", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("market_trades::".into()), symbol).into());
let mut tradesArray: Value = self.safe_value(self.trades.clone(), symbol.clone(), &[]);
if (tradesArray == Value::Null) {
let mut tradesLimit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
tradesArray = ArrayCacheBySymbolById::new(tradesLimit);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), tradesArray.clone()); }
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_259: bool = true;
while { if !__for_first_259 { 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_259 = false; i.as_f64().unwrap_or(f64::NAN) < ((events.len() as i64) as f64) } {
let mut currentEvent: Value = events.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 currentTrades: Value = self.safe_list_k(currentEvent, "trades", &[]);
if (currentTrades == Value::Null) {
continue;
}
// coinbase sends trades newest-first, append them in reverse so the cache stays sorted by ascending timestamp
let mut tradesLength: Value = Value::Int(currentTrades.len() as i64);
{
let mut j: Value = Value::Int(0);
let mut __for_first_258: bool = true;
while { if !__for_first_258 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_258 = false; j.as_f64().unwrap_or(f64::NAN) < tradesLength.as_f64().unwrap_or(f64::NAN) } {
let mut item: Value = get_value(¤tTrades, &(match (&((match (&(tradesLength), &(j)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })), &(Value::Int(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 }));
tradesArray.append(self.parse_trade(item, &[]));
}
}
}
}
client.resolve(&[tradesArray.clone(), messageHash.clone()]);
self.try_resolve_usdc(client, messageHash, tradesArray);
}
pub fn handle_order(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "channel": "user",
// "client_id": "",
// "timestamp": "2023-02-09T20:33:57.609931463Z",
// "sequence_num": 0,
// "events": [
// {
// "type": "snapshot",
// "orders": [
// {
// "order_id": "XXX",
// "client_order_id": "YYY",
// "cumulative_quantity": "0",
// "leaves_quantity": "0.000994",
// "avg_price": "0",
// "total_fees": "0",
// "status": "OPEN",
// "product_id": "BTC-USD",
// "creation_time": "2022-12-07T19:42:18.719312Z",
// "order_side": "BUY",
// "order_type": "Limit"
// },
// ]
// }
// ]
// }
//
let mut events: Value = (match message.get("events") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::Null });
if (events == Value::Null) {
return;
}
let mut marketIds: Value = Value::from(vec![]);
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 i: Value = Value::Int(0);
let mut __for_first_261: bool = true;
while { if !__for_first_261 { 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_261 = false; i.as_f64().unwrap_or(f64::NAN) < ((events.len() as i64) as f64) } {
let mut event: Value = events.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 responseOrders: Value = self.safe_list_k(event, "orders", &[]);
if (responseOrders == Value::Null) {
continue;
}
{
let mut j: Value = Value::Int(0);
let mut __for_first_260: bool = true;
while { if !__for_first_260 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_260 = false; j.as_f64().unwrap_or(f64::NAN) < ((responseOrders.len() as i64) as f64) } {
let mut responseOrder: Value = responseOrders.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut parsed: Value = self.parse_ws_order(responseOrder.clone(), &[]);
let mut cachedOrders: Value = self.orders.clone();
let mut marketId: Value = self.safe_string_k(responseOrder, "product_id", &[]);
if (marketId != Value::Null) {
if !(in_op(&marketIds, &marketId)) {
append_to_array(&mut marketIds, marketId.clone());
}
}
cachedOrders.append(parsed);
}
}
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_262: bool = true;
while { if !__for_first_262 { 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_262 = false; i.as_f64().unwrap_or(f64::NAN) < ((marketIds.len() as i64) as f64) } {
let mut marketId: Value = marketIds.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut symbol: Value = self.safe_symbol(marketId, &[]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("user::".into()), symbol).into());
client.resolve(&[self.orders.clone(), messageHash.clone()]);
self.try_resolve_usdc(client.clone(), messageHash, self.orders.clone());
}
}
client.resolve(&[self.orders.clone(), Value::Str("user".into())]);
}
pub fn parse_ws_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "order_id": "XXX",
// "client_order_id": "YYY",
// "cumulative_quantity": "0",
// "leaves_quantity": "0.000994",
// "avg_price": "0",
// "total_fees": "0",
// "status": "OPEN",
// "product_id": "BTC-USD",
// "creation_time": "2022-12-07T19:42:18.719312Z",
// "order_side": "BUY",
// "order_type": "Limit"
// }
//
let mut id: Value = self.safe_string_k(order.clone(), "order_id", &[]);
let mut clientOrderId: Value = self.safe_string_k(order.clone(), "client_order_id", &[]);
let mut marketId: Value = self.safe_string_k(order.clone(), "product_id", &[]);
let mut datetime: Value = self.safe_string2(order.clone(), Value::Str("time".into()), Value::Str("creation_time".into()), &[]);
market = self.safe_market(&[marketId, market.clone()]);
let mut stopPrice: Value = self.safe_string_k(order.clone(), "stop_price", &[]);
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("symbol".to_string(), self.safe_string_k(market.clone(), "symbol", &[]));
m.insert("id".to_string(), id);
m.insert("clientOrderId".to_string(), clientOrderId);
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime);
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("type".to_string(), self.safe_string_k(order.clone(), "order_type", &[]));
m.insert("timeInForce".to_string(), Value::Null);
m.insert("postOnly".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_lower2(order.clone(), Value::Str("side".into()), Value::Str("order_side".into()), &[]));
m.insert("price".to_string(), self.safe_string_k(order.clone(), "limit_price", &[]));
m.insert("stopPrice".to_string(), stopPrice.clone());
m.insert("triggerPrice".to_string(), stopPrice);
m.insert("amount".to_string(), self.safe_string_k(order.clone(), "cumulative_quantity", &[]));
m.insert("cost".to_string(), self.omit_zero(self.safe_string_k(order.clone(), "filled_value", &[])));
m.insert("average".to_string(), self.safe_string_k(order.clone(), "avg_price", &[]));
m.insert("filled".to_string(), self.safe_string_k(order.clone(), "cumulative_quantity", &[]));
m.insert("remaining".to_string(), self.safe_string_k(order.clone(), "leaves_quantity", &[]));
m.insert("status".to_string(), self.parent.parse_order_status(self.safe_string_k(order.clone(), "status", &[])));
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.safe_string_k(order, "total_fees", &[]));
m.insert("currency".to_string(), self.safe_string_k(market, "quote", &[]));
m
}));
m.insert("trades".to_string(), Value::Null);
m
}), &[]);
Value::Null
}
pub fn handle_order_book_helper(&self, mut orderbook: Value, mut updates: Value) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_263: bool = true;
while { if !__for_first_263 { 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_263 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&updates).as_f64().unwrap_or(f64::NAN) } {
let mut trade: Value = get_value(&updates, &i);
let mut trade: Value = get_value(&updates, &i);
let mut sideId: Value = self.safe_string_k(trade.clone(), "side", &[]);
let mut side: Value = self.safe_string(self.options.as_map().and_then(|__m| __m.get("sides")).cloned().unwrap_or(Value::Null), sideId, &[]);
let mut price: Value = self.safe_number_k(trade.clone(), "price_level", &[]);
let mut amount: Value = self.safe_number_k(trade, "new_quantity", &[]);
let mut orderbookSide: Value = self.safe_value(orderbook.clone(), side, &[]);
orderbookSide.store(price, amount);
}
}
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value) {
//
// {
// "channel": "l2_data",
// "client_id": "",
// "timestamp": "2023-02-09T20:32:50.714964855Z",
// "sequence_num": 0,
// "events": [
// {
// "type": "snapshot",
// "product_id": "BTC-USD",
// "updates": [
// {
// "side": "bid",
// "event_time": "1970-01-01T00:00:00Z",
// "price_level": "21921.74",
// "new_quantity": "0.06317902"
// },
// {
// "side": "bid",
// "event_time": "1970-01-01T00:00:00Z",
// "price_level": "21921.3",
// "new_quantity": "0.02"
// },
// ]
// }
// ]
// }
//
let mut events: Value = self.safe_list_k(message.clone(), "events", &[]);
if (events == Value::Null) {
return;
}
let mut datetime: Value = self.safe_string_k(message, "timestamp", &[]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_264: bool = true;
while { if !__for_first_264 { 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_264 = false; i.as_f64().unwrap_or(f64::NAN) < ((events.len() as i64) as f64) } {
let mut event: Value = events.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 updates: Value = self.safe_list_k(event.clone(), "updates", &[Value::from(vec![])]);
let mut marketId: Value = self.safe_string_k(event.clone(), "product_id", &[]);
// sometimes we subscribe to BTC/USDC and coinbase returns BTC/USD, as they are aliases
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("level2::".into()), symbol).into());
let mut subscription: Value = self.safe_dict(get_value(&client, &Value::Str("subscriptions".into())), messageHash.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut limit: Value = self.safe_integer_k(subscription, "limit", &[]);
let mut type_var: Option<String> = self.safe_string_k(event, "type", &[]).as_str().map(str::to_owned);
if (type_var.as_deref() == Some("snapshot")) {
{ let __be_tmp = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), limit]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
}
// unknown bug, can't reproduce, but sometimes orderbook is undefined
if !(in_op(&self.orderbooks, &symbol)) && is_equal(&get_value(&self.orderbooks, &symbol), &Value::Null) {
continue;
}
let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
self.handle_order_book_helper(orderbook.clone(), updates);
add_element_to_object(&mut orderbook, &Value::Str("timestamp".into()), self.parse8601(datetime.clone()));
add_element_to_object(&mut orderbook, &Value::Str("datetime".into()), datetime.clone());
add_element_to_object(&mut orderbook, &Value::Str("symbol".into()), symbol);
client.resolve(&[orderbook.clone(), messageHash.clone()]);
self.try_resolve_usdc(client.clone(), messageHash, orderbook);
}
}
}
pub fn try_resolve_usdc(&self, mut client: Value, mut messageHash: Value, mut result: Value) {
if (ends_with(&messageHash, &Value::Str("/USD".into()))) || (ends_with(&messageHash, &Value::Str("-USD".into()))) {
client.resolve(&[result, Value::Str(format!("{}{}", messageHash, Value::Str("C".into())).into())]); // when subscribing to BTC/USDC and coinbase returns BTC/USD, so resolve USDC too
}
}
pub fn handle_subscription_status(&mut self, mut client: Value, mut message: Value) -> Value {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "type": "subscriptions",
// "channels": [
// {
// "name": "level2",
// "product_ids": [ "ETH-BTC" ]
// }
// ]
// }
//
//
// {
// channel: 'subscriptions',
// client_id: '',
// timestamp: '2025-09-15T17:02:49.90120868Z',
// sequence_num: 3,
// events: [ { subscriptions: {} } ]
// }
//
let mut events: Value = (match __pro_message.get("events").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
let mut firstEvent: Value = self.safe_dict(events, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut isUnsub: bool = matches!(&firstEvent, Value::Dict(__d) if __d.contains_key("subscriptions"));
let mut subKeys: Value = object_keys(&firstEvent.as_map().and_then(|__m| __m.get("subscriptions")).cloned().unwrap_or(Value::Null));
let mut subKeysLength: f64 = ((subKeys.len() as i64) as f64);
if isUnsub && (subKeysLength == 0.0) {
let mut unSubObject: Value = self.safe_dict_k(self.options.clone(), "unSubscription", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut messageHashes: Value = self.safe_list_k(unSubObject.clone(), "messageHashes", &[Value::from(vec![])]);
let mut subMessageHashes: Value = self.safe_list_k(unSubObject.clone(), "subMessageHashes", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_265: bool = true;
while { if !__for_first_265 { 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_265 = false; i.as_f64().unwrap_or(f64::NAN) < ((messageHashes.len() as i64) as f64) } {
let mut messageHash: Value = messageHashes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut subHash: Value = subMessageHashes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
self.clean_unsubscription(client.clone(), subHash, messageHash, &[]);
}
}
self.clean_cache(unSubObject);
}
return message;
Value::Null
}
pub fn handle_heartbeats(&self, mut client: Value, mut message: Value) -> Value {
return message;
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 channel: Value = (match __pro_message.get("channel").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut methods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("subscriptions".to_string(), Value::Str("handle_subscription_status".into()).clone());
m.insert("ticker".to_string(), Value::Str("handle_tickers".into()).clone());
m.insert("ticker_batch".to_string(), Value::Str("handle_tickers".into()).clone());
m.insert("market_trades".to_string(), Value::Str("handle_trade".into()).clone());
m.insert("user".to_string(), Value::Str("handle_order".into()).clone());
m.insert("l2_data".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("heartbeats".to_string(), Value::Str("handle_heartbeats".into()).clone());
m
});
let mut type_var: Option<String> = (match __pro_message.get("type").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (type_var.as_deref() == Some("error")) {
let mut errorMessage: Value = (match __pro_message.get("message").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 });
// ternary (not ||) so the ast-transpiler emits a value-typed conditional, not a boolean
let mut errorMessageValue: Value = (if (errorMessage != Value::Null) { errorMessage } else { Value::Str("unknown error".into()) });
panic!("{}", crate::exchange_errors::exchange_error(errorMessageValue));
}
let mut method: Value = self.safe_value(methods, channel, &[]);
if (method != Value::Null) {
self.dispatch_ws_handler(&method, &[client, message]);
}
}
}