// 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 BitfinexCore {
pub parent: crate::exchanges::bitfinex::BitfinexCore,
}
impl BitfinexCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::bitfinex::BitfinexCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = BitfinexCore::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 BitfinexCore {
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 BitfinexCore {
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,
"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)),
"handle_system_status" => self.handle_system_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_unsubscription_status" => self.handle_unsubscription_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_ws_balance" => self.parse_ws_balance(args.get(0).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())..]),
"parse_ws_trade" => self.parse_ws_trade(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_private" => self.subscribe_private(args.get(0).cloned().unwrap_or(crate::Value::Null)).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_watch_ohlcv" => self.un_watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_ticker" => self.un_watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_trades" => self.un_watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"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_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 BitfinexCore {
/// 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 },
"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), args.get(2).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_checksum" => { self.handle_checksum(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_my_trade" => { self.handle_my_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]); 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), args.get(2).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), args.get(2).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_orders" => { self.handle_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_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_system_status" => self.handle_system_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_ticker" => { self.handle_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_trades" => { self.handle_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_unsubscription_status" => self.handle_unsubscription_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_ws_balance" => self.parse_ws_balance(args.get(0).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())..]),
"parse_ws_trade" => self.parse_ws_trade(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_private" => { crate::exchange_stubs::enqueue_spawn("subscribe_private", args.to_vec()); crate::Value::Null },
"un_subscribe" => { crate::exchange_stubs::enqueue_spawn("un_subscribe", args.to_vec()); crate::Value::Null },
"un_watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("un_watch_ohlcv", args.to_vec()); crate::Value::Null },
"un_watch_ticker" => { crate::exchange_stubs::enqueue_spawn("un_watch_ticker", args.to_vec()); crate::Value::Null },
"un_watch_trades" => { crate::exchange_stubs::enqueue_spawn("un_watch_trades", args.to_vec()); crate::Value::Null },
"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_trades" => { crate::exchange_stubs::enqueue_spawn("watch_trades", args.to_vec()); crate::Value::Null },
_ => crate::Value::Null,
}
}
}
impl std::ops::Deref for BitfinexCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for BitfinexCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl BitfinexCore {
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("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(false));
m.insert("watchOrderBook".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("watchBalance".to_string(), Value::Bool(true));
m.insert("watchOHLCV".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("unWatchTicker".to_string(), Value::Bool(true));
m.insert("unWatchTrades".to_string(), Value::Bool(true));
m.insert("unWatchOHLCV".to_string(), Value::Bool(true));
m.insert("unWatchOrderBook".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("wss://api-pub.bitfinex.com/ws/2".into()));
m.insert("private".to_string(), Value::Str("wss://api.bitfinex.com/ws/2".into()));
m
}));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("watchOrderBook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("prec".to_string(), Value::Str("P0".into()));
m.insert("freq".to_string(), Value::Str("F0".into()));
m.insert("checksum".to_string(), Value::Bool(true));
m
}));
m.insert("ordersLimit".to_string(), Value::Int(1000));
m
}));
m
})]);
Value::Null
}
pub async fn subscribe(&mut self, mut channel: Value, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut marketId: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut url: Value = crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "public");
let mut client: Value = self.client(&[url.clone()]);
let mut messageHash: Value = Value::Str(format!("{}{}", add(&channel, &Value::Str(":".into())), marketId).into());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("event".to_string(), Value::Str("subscribe".into()));
m.insert("channel".to_string(), channel.clone());
m.insert("symbol".to_string(), marketId);
m
});
let __ws_arg_0 = self.deep_extend(request, &[params]);
let mut result: Value = self.watch(url, messageHash.clone(), &[__ws_arg_0, messageHash.clone(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("checksum".to_string(), Value::Bool(false));
m
})]).await;
let mut checksum: Value = self.safe_bool_k(self.options.clone(), "checksum", &[Value::Bool(true)]);
if (checksum.as_bool() == Some(true)) && (channel.as_str() == Some("book")) {
let mut sub: Value = get_value(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
if (sub != Value::Null) && (!is_equal(&crate::value::get_value_k(&sub, "checksum"), &Value::Bool(true))) {
add_element_to_object(get_value_mut(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash), &Value::Str("checksum".into()), Value::Bool(true));
client.send(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("event".to_string(), Value::Str("conf".into()));
m.insert("flags".to_string(), Value::Int(131072));
m
})]);
}
}
return result;
Value::Null
}
pub async fn un_subscribe(&mut self, mut channel: Value, mut topic: Value, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut marketId: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut url: Value = crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "public");
let mut client: Value = self.client(&[url.clone()]);
let mut subMessageHash: Value = Value::Str(format!("{}{}", add(&channel, &Value::Str(":".into())), marketId).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", add(&Value::Str("unsubscribe:".into()), &channel), Value::Str(":".into())).into()), marketId).into());
let mut unSubTopic: Value = add(&Value::Str(format!("{}{}", add(&Value::Str(format!("{}{}", Value::Str("unsubscribe".into()), Value::Str(":".into())).into()), &topic), Value::Str(":".into())).into()), &symbol);
let mut channelId: Value = self.safe_string(get_value(&client, &Value::Str("subscriptions".into())), unSubTopic, &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("event".to_string(), Value::Str("unsubscribe".into()));
m.insert("chanId".to_string(), channelId.clone());
m
});
let mut unSubChanMsg: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), channelId).into());
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &unSubChanMsg, subMessageHash.clone());
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("messageHashes".to_string(), Value::from(vec![messageHash.clone()]));
m.insert("subMessageHashes".to_string(), Value::from(vec![subMessageHash]));
m.insert("topic".to_string(), topic);
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("symbols".to_string(), Value::from(vec![symbol]));
m
});
let __ws_arg_1 = self.deep_extend(request, &[params]);
return self.watch(url, messageHash.clone(), &[__ws_arg_1, messageHash.clone(), subscription]).await;
Value::Null
}
pub async fn subscribe_private(&mut self, mut messageHash: Value) -> Value {
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.authenticate(&[]).await;
let mut url: Value = crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "private");
return self.watch(url, messageHash, &[Value::Null, Value::Int(1)]).await;
Value::Null
}
/*
* @method
* @name bitfinex#watchOHLCV
* @description watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn watch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
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 interval: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
let mut channel: Value = Value::Str("candles".into());
let mut key: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("trade:".into()), interval).into()), Value::Str(":".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", channel, Value::Str(":".into())).into()), interval).into()), Value::Str(":".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("event".to_string(), Value::Str("subscribe".into()));
m.insert("channel".to_string(), channel);
m.insert("key".to_string(), key);
m
});
let mut url: Value = crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "public");
// not using subscribe here because this message has a different format
let __ws_arg_2 = self.deep_extend(request, &[params]);
let mut ohlcv: Value = self.watch(url, messageHash.clone(), &[__ws_arg_2, 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
}
/*
* @method
* @name bitfinex#unWatchOHLCV
* @description unWatches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {bool} true if successfully unsubscribed, false otherwise
*/
pub async fn un_watch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut interval: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
let mut channel: Value = Value::Str("candles".into());
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", channel, Value::Str(":".into())).into()), interval).into()), Value::Str(":".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let mut url: Value = crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "public");
let mut client: Value = self.client(&[url.clone()]);
let mut subId: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("unsubscribe:trade:".into()), interval).into()), Value::Str(":".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()); // trade here because we use the key
let mut channelId: Value = self.safe_string(get_value(&client, &Value::Str("subscriptions".into())), subId, &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("event".to_string(), Value::Str("unsubscribe".into()));
m.insert("chanId".to_string(), channelId.clone());
m
});
let mut unSubChanMsg: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), channelId).into());
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &unSubChanMsg, subMessageHash.clone());
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("messageHashes".to_string(), Value::from(vec![messageHash.clone()]));
m.insert("subMessageHashes".to_string(), Value::from(vec![subMessageHash]));
m.insert("topic".to_string(), Value::Str("ohlcv".into()));
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("symbols".to_string(), Value::from(vec![symbol]));
m
});
let __ws_arg_3 = self.deep_extend(request, &[params]);
return self.watch(url, messageHash.clone(), &[__ws_arg_3, messageHash.clone(), subscription]).await;
Value::Null
}
pub fn handle_ohlcv(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
let __subscription_empty = indexmap::IndexMap::new();
let subscription = subscription.as_map().unwrap_or(&__subscription_empty);
//
// initial snapshot
// [
// 341527, // channel id
// [
// [
// 1654705860000, // timestamp
// 1802.6, // open
// 1800.3, // close
// 1802.8, // high
// 1800.3, // low
// 86.49588236 // volume
// ],
// [
// 1654705800000,
// 1803.6,
// 1802.6,
// 1804.9,
// 1802.3,
// 74.6348086
// ],
// [
// 1654705740000,
// 1802.5,
// 1803.2,
// 1804.4,
// 1802.4,
// 23.61801085
// ]
// ]
// ]
//
// update
// [
// 211171,
// [
// 1654705680000,
// 1801,
// 1802.4,
// 1802.9,
// 1800.4,
// 23.91911091
// ]
// ]
//
let mut data: Value = self.safe_list(message, Value::Int(1), &[Value::from(vec![])]);
let mut ohlcvs: Value = Value::from(vec![]);
let mut first: Value = self.safe_list(data.clone(), Value::Int(0), &[]);
if (matches!(&first, Value::Arr(_))) {
// snapshot
ohlcvs = data.clone();
} else {
// update
ohlcvs = Value::from(vec![data]);
}
let mut channel: Value = (match subscription.get("channel") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut key: Value = (match subscription.get("key") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
let mut keyParts: Value = split(&key, &Value::Str(":".into()));
let mut interval: Value = self.safe_string(keyParts, Value::Int(1), &[]);
let mut marketId: Value = key;
marketId = replace_str(&marketId, &Value::Str("trade:".into()), &Value::Str("".into()));
marketId = replace_str(&marketId, &Value::Str(format!("{}{}", interval, Value::Str(":".into())).into()), &Value::Str("".into()));
let mut market: Value = self.safe_market(&[marketId.clone()]);
let mut timeframe: Value = self.find_timeframe(interval.clone(), &[]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", channel, Value::Str(":".into())).into()), interval).into()), Value::Str(":".into())).into()), marketId).into());
{ let __be_tmp = self.safe_dict(self.ohlcvs.clone(), symbol.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); if let Value::Dict(__d) = &mut self.ohlcvs { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
let mut stored: Value = self.safe_value(get_value(&self.ohlcvs, &symbol), timeframe.clone(), &[]);
if (stored == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "OHLCVLimit", &[Value::Int(1000)]);
stored = ArrayCacheByTimestamp::new(limit);
add_element_to_object(get_value_mut(&mut self.ohlcvs, &symbol), &timeframe, stored.clone());
}
let mut ohlcvsLength: Value = Value::Int(ohlcvs.len() as i64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_101: bool = true;
while { if !__for_first_101 { 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_101 = false; i.as_f64().unwrap_or(f64::NAN) < ohlcvsLength.as_f64().unwrap_or(f64::NAN) } {
let mut ohlcv: Value = get_value(&ohlcvs, &(match (&((match (&(ohlcvsLength), &(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 })), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }));
let mut parsed: Value = self.parse_ohlcv(ohlcv, &[market.clone()]);
stored.append(parsed);
}
}
client.resolve(&[stored, messageHash]);
}
/*
* @method
* @name bitfinex#watchTrades
* @description get the list of most recent trades for a particular symbol
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut trades: Value = self.subscribe(Value::Str("trades".into()), 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 bitfinex#unWatchTrades
* @description unWatches the list of most recent trades for a particular symbol
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn un_watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.un_subscribe(Value::Str("trades".into()), Value::Str("trades".into()), symbol, &[params]).await;
Value::Null
}
/*
* @method
* @name bitfinex#watchMyTrades
* @description watches information on multiple trades made by the user
* @param {string} symbol unified market symbol of the market trades were made in
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trade structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut messageHash: Value = Value::Str("myTrade".into());
if (symbol != Value::Null) {
let mut market: Value = self.market(symbol.clone());
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(format!("{}{}", Value::Str(":".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into())).into());
}
let mut trades: Value = self.subscribe_private(messageHash).await;
if is_true(&self.newUpdates) {
limit = trades.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_symbol_since_limit(trades, &[symbol, since, limit, Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name bitfinex#watchTicker
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.subscribe(Value::Str("ticker".into()), symbol, &[params]).await;
Value::Null
}
/*
* @method
* @name bitfinex#unWatchTicker
* @description unWatches 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 un_watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.un_subscribe(Value::Str("ticker".into()), Value::Str("ticker".into()), symbol, &[params]).await;
Value::Null
}
pub fn handle_my_trade(&mut self, mut client: Value, mut message: Value, optional_args: &[Value]) {
let mut subscription = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
//
// trade execution
// [
// 0,
// "te", // or tu
// [
// 1133411090,
// "tLTCUST",
// 1655110144598,
// 97084883506,
// 0.1,
// 42.821,
// "EXCHANGE MARKET",
// 42.799,
// -1,
// null,
// null,
// 1655110144596
// ]
// ]
//
let mut name: Value = Value::Str("myTrade".into());
let mut data: Value = self.safe_value(message, Value::Int(2), &[]);
let mut trade: Value = self.parse_ws_trade(data, &[]);
let mut symbol: Value = trade.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", name, Value::Str(":".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
if (self.myTrades.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCacheBySymbolById::new(limit);
}
let mut tradesArray: Value = self.myTrades.clone();
tradesArray.append(trade);
self.myTrades = tradesArray.clone();
// generic subscription
client.resolve(&[tradesArray.clone(), name]);
// specific subscription
client.resolve(&[tradesArray, messageHash]);
}
pub fn handle_trades(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
//
// initial snapshot
//
// [
// 188687, // channel id
// [
// [ 1128060675, 1654701572690, 0.00217533, 1815.3 ], // id, mts, amount, price
// [ 1128060665, 1654701551231, -0.00280472, 1814.1 ],
// [ 1128060664, 1654701550996, -0.00364444, 1814.1 ],
// [ 1128060656, 1654701527730, -0.00265203, 1814.2 ],
// [ 1128060647, 1654701505193, 0.00262395, 1815.2 ],
// [ 1128060642, 1654701484656, -0.13411443, 1816 ],
// [ 1128060641, 1654701484656, -0.00088557, 1816 ],
// [ 1128060639, 1654701478326, -0.002, 1816 ],
// ]
// ]
// update
//
// [
// 360141,
// "te",
// [
// 1128060969, // id
// 1654702500098, // mts
// 0.00325131, // amount positive buy, negative sell
// 1818.5, // price
// ],
// ]
//
//
let mut channel: Value = self.safe_string_k(subscription.clone(), "channel", &[]);
let mut marketId: Value = self.safe_string_k(subscription, "symbol", &[]);
let mut market: Value = self.safe_market(&[marketId.clone()]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", channel, Value::Str(":".into())).into()), marketId).into());
let mut tradesLimit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut stored: Value = self.safe_value(self.trades.clone(), symbol.clone(), &[]);
if (stored == Value::Null) {
stored = ArrayCache::new(tradesLimit);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), stored.clone()); }
}
let mut messageLength: f64 = ((message.len() as i64) as f64);
if (messageLength == 2.0) {
// initial snapshot
let mut trades: Value = self.safe_list(message.clone(), Value::Int(1), &[Value::from(vec![])]);
// needs to be reversed to make chronological order
let mut length: Value = Value::Int(trades.len() as i64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_102: bool = true;
while { if !__for_first_102 { 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_102 = false; i.as_f64().unwrap_or(f64::NAN) < length.as_f64().unwrap_or(f64::NAN) } {
let mut index: Value = (match (&((match (&(length), &(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 })), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
let mut parsed: Value = self.parse_ws_trade(get_value(&trades, &index), &[market.clone()]);
stored.append(parsed.clone());
}
}
} else {
// update
let mut type_var: Option<String> = self.safe_string(message.clone(), Value::Int(1), &[]).as_str().map(str::to_owned);
if (type_var.as_deref() == Some("tu")) {
return;
}
let mut trade: Value = self.safe_list(message, Value::Int(2), &[Value::from(vec![])]);
let mut parsed: Value = self.parse_ws_trade(trade, &[market]);
stored.append(parsed);
}
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);
//
// [
// 1128060969, // id
// 1654702500098, // mts
// 0.00325131, // amount positive buy, negative sell
// 1818.5, // price
// ]
//
// trade execution
//
// [
// 1133411090, // id
// "tLTCUST", // symbol
// 1655110144598, // create ms
// 97084883506, // order id
// 0.1, // amount
// 42.821, // price
// "EXCHANGE MARKET", // order type
// 42.799, // order price
// -1, // maker
// null, // fee
// null, // fee currency
// 1655110144596 // cid
// ]
//
// trade update
//
// [
// 1133411090,
// "tLTCUST",
// 1655110144598,
// 97084883506,
// 0.1,
// 42.821,
// "EXCHANGE MARKET",
// 42.799,
// -1,
// -0.0002,
// "LTC",
// 1655110144596
// ]
//
let mut numFields: Value = get_array_length(&trade);
let mut isPublic: bool = numFields.as_f64().unwrap_or(f64::NAN) <= ((8i64) as f64);
let mut marketId: Value = (if (!isPublic) { self.safe_string(trade.clone(), Value::Int(1), &[]) } else { Value::Null });
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut createdKey: Value = (if isPublic { Value::Int(1) } else { Value::Int(2) });
let mut priceKey: Value = (if isPublic { Value::Int(3) } else { Value::Int(5) });
let mut amountKey: Value = (if isPublic { Value::Int(2) } else { Value::Int(4) });
marketId = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut type_var: Value = self.safe_string(trade.clone(), Value::Int(6), &[]);
if (type_var != Value::Null) {
if Value::Int(type_var.as_str().and_then(|__s| __s.find("LIMIT")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64) {
type_var = Value::Str("limit".into());
} else if Value::Int(type_var.as_str().and_then(|__s| __s.find("MARKET")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64) {
type_var = Value::Str("market".into());
}
}
let mut orderId: Value = (if (!isPublic) { self.safe_string(trade.clone(), Value::Int(3), &[]) } else { Value::Null });
let mut id: Value = self.safe_string(trade.clone(), Value::Int(0), &[]);
let mut timestamp: Value = self.safe_integer(trade.clone(), createdKey, &[]);
let mut price: Value = self.safe_string(trade.clone(), priceKey, &[]);
let mut amountString: Value = self.safe_string(trade.clone(), amountKey, &[]);
let mut amount: Value = self.parse_number(crate::precise::Precise::stringAbs(&amountString), &[]);
let mut side: Value = Value::Null;
if (amount != Value::Null) {
side = (if is_true(&crate::precise::Precise::stringGt(&amountString, &Value::Str("0".into()))) { Value::Str("buy".into()) } else { Value::Str("sell".into()) });
}
let mut symbol: Value = self.safe_symbol(marketId, &[market.clone()]);
let mut feeValue: Value = self.safe_string(trade.clone(), Value::Int(9), &[]);
let mut fee: Value = Value::Null;
if (feeValue != Value::Null) {
let mut currencyId: Value = self.safe_string(trade.clone(), Value::Int(10), &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeValue);
m.insert("currency".to_string(), code);
m
});
}
let mut maker: Value = self.safe_integer(trade.clone(), Value::Int(8), &[]);
let mut takerOrMaker: Value = Value::Null;
if (maker != Value::Null) {
takerOrMaker = (if (maker.as_f64() == Value::Int(-1).as_f64()) { Value::Str("taker".into()) } else { Value::Str("maker".into()) });
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), symbol);
m.insert("id".to_string(), id);
m.insert("order".to_string(), orderId);
m.insert("type".to_string(), type_var);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
}), &[market]);
Value::Null
}
pub fn handle_ticker(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
//
// [
// 340432, // channel ID
// [
// 236.62, // 1 BID float Price of last highest bid
// 9.0029, // 2 BID_SIZE float Size of the last highest bid
// 236.88, // 3 ASK float Price of last lowest ask
// 7.1138, // 4 ASK_SIZE float Size of the last lowest ask
// -1.02, // 5 DAILY_CHANGE float Amount that the last price has changed since yesterday
// 0, // 6 DAILY_CHANGE_RELATIVE float Relative change (array index 5); parseWsTicker multiplies by 100.
// 236.52, // 7 LAST_PRICE float Price of the last trade.
// 5191.36754297, // 8 VOLUME float Daily volume
// 250.01, // 9 HIGH float Daily high
// 220.05, // 10 LOW float Daily low
// ]
// ]
//
let mut ticker: Value = self.safe_value(message, Value::Int(1), &[]);
let mut marketId: Value = self.safe_string_k(subscription, "symbol", &[]);
let mut market: Value = self.safe_market(&[marketId.clone()]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[]);
let mut parsed: Value = self.parse_ws_ticker(ticker, &[market]);
let mut channel: Value = Value::Str("ticker".into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", channel, Value::Str(":".into())).into()), marketId).into());
if let Value::Dict(__d) = &mut self.tickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), parsed.clone()); }
client.resolve(&[parsed, messageHash]);
}
pub fn parse_ws_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// [
// 236.62, // 1 BID float Price of last highest bid
// 9.0029, // 2 BID_SIZE float Size of the last highest bid
// 236.88, // 3 ASK float Price of last lowest ask
// 7.1138, // 4 ASK_SIZE float Size of the last lowest ask
// -1.02, // 5 DAILY_CHANGE float Amount that the last price has changed since yesterday
// 0, // 6 DAILY_CHANGE_RELATIVE float Relative change (array index 5); parseWsTicker multiplies by 100.
// 236.52, // 7 LAST_PRICE float Price of the last trade.
// 5191.36754297, // 8 VOLUME float Daily volume
// 250.01, // 9 HIGH float Daily high
// 220.05, // 10 LOW float Daily low
// ]
//
market = self.safe_market(&[Value::Null, market.clone()]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut last: Value = self.safe_string(ticker.clone(), Value::Int(6), &[]);
let mut change: Value = self.safe_string(ticker.clone(), Value::Int(4), &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("high".to_string(), self.safe_string(ticker.clone(), Value::Int(8), &[]));
m.insert("low".to_string(), self.safe_string(ticker.clone(), Value::Int(9), &[]));
m.insert("bid".to_string(), self.safe_string(ticker.clone(), Value::Int(0), &[]));
m.insert("bidVolume".to_string(), self.safe_string(ticker.clone(), Value::Int(1), &[]));
m.insert("ask".to_string(), self.safe_string(ticker.clone(), Value::Int(2), &[]));
m.insert("askVolume".to_string(), self.safe_string(ticker.clone(), Value::Int(3), &[]));
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(), change);
m.insert("percentage".to_string(), crate::precise::Precise::stringMul(&self.safe_string(ticker.clone(), Value::Int(5), &[]), &Value::Str("100".into())));
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), self.safe_string(ticker.clone(), Value::Int(7), &[]));
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("info".to_string(), ticker);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name bitfinex#watchOrderBook
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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 (limit != Value::Null) {
if (limit.as_f64() != Some(25.0)) && (limit.as_f64() != Some(100.0)) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" watchOrderBook limit argument must be undefined, 25 or 100".into()))));
}
}
let mut options: Value = self.safe_dict_k(self.options.clone(), "watchOrderBook", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut prec: Value = self.safe_string_k(options.clone(), "prec", &[Value::Str("P0".into())]);
let mut freq: Value = self.safe_string_k(options, "freq", &[Value::Str("F0".into())]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("prec".to_string(), prec);
m.insert("freq".to_string(), freq);
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("len".into(), limit.clone()); }; // string, number of price points, '25', '100', default = '25'
}
let mut orderbook: Value = self.subscribe(Value::Str("book".into()), symbol, &[self.deep_extend(request, &[params])]).await;
return orderbook.limit();
Value::Null
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
let __message_empty = Vec::new();
let message = message.as_array().unwrap_or(&__message_empty);
//
// first message (snapshot)
//
// [
// 18691, // channel id
// [
// [ 7364.8, 10, 4.354802 ], // price, count, size > 0 = bid
// [ 7364.7, 1, 0.00288831 ],
// [ 7364.3, 12, 0.048 ],
// [ 7364.9, 3, -0.42028976 ], // price, count, size < 0 = ask
// [ 7365, 1, -0.25 ],
// [ 7365.5, 1, -0.00371937 ],
// ]
// ]
//
// subsequent updates
//
// [
// 358169, // channel id
// [
// 1807.1, // price
// 0, // count
// 1 // size
// ]
// ]
//
let mut marketId: Value = self.safe_string_k(subscription.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[]);
let mut channel: Value = Value::Str("book".into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", channel, Value::Str(":".into())).into()), marketId).into());
let mut prec: Option<String> = self.safe_string_k(subscription.clone(), "prec", &[Value::Str("P0".into())]).as_str().map(str::to_owned);
let mut isRaw: bool = prec.as_deref() == Some("R0");
// if it is an initial snapshot
if !(in_op(&self.orderbooks, &symbol)) {
let mut limit: Value = self.safe_integer_k(subscription, "len", &[]);
if isRaw {
// raw order books
{ let __be_tmp = self.indexed_order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), limit.clone()]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
} else {
// P0, P1, P2, P3, P4
{ let __be_tmp = self.counted_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); } }
}
let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
if isRaw {
let mut deltas: Value = message.get(1).cloned().unwrap_or(Value::Null);
{
let mut i: Value = Value::Int(0);
let mut __for_first_103: bool = true;
while { if !__for_first_103 { 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_103 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&deltas).as_f64().unwrap_or(f64::NAN) } {
let mut delta: Value = get_value(&deltas, &i);
let mut delta: Value = get_value(&deltas, &i);
let mut delta2: Value = get_value(&delta, &Value::Int(2));
let mut size: Value = (if (delta2.as_f64().unwrap_or(f64::NAN) < ((0i64) as f64)) { negate(&delta2) } else { delta2.clone() });
let mut side: Value = (if (delta2.as_f64().unwrap_or(f64::NAN) < ((0i64) as f64)) { Value::Str("asks".into()) } else { Value::Str("bids".into()) });
let mut bookside: Value = get_value(&orderbook, &side);
let mut bookside: Value = get_value(&orderbook, &side);
let mut idString: Value = self.safe_string(delta.clone(), Value::Int(0), &[]);
let mut price: Value = self.safe_float(delta.clone(), Value::Int(1), &[]);
bookside.store_array(Value::from(vec![price.clone(), size.clone(), idString.clone()]));
}
}
} else {
let mut deltas: Value = message.get(1).cloned().unwrap_or(Value::Null);
{
let mut i: Value = Value::Int(0);
let mut __for_first_104: bool = true;
while { if !__for_first_104 { 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_104 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&deltas).as_f64().unwrap_or(f64::NAN) } {
let mut delta: Value = get_value(&deltas, &i);
let mut delta: Value = get_value(&deltas, &i);
let mut amount: Value = self.safe_number(delta.clone(), Value::Int(2), &[]);
if (amount == Value::Null) {
continue;
}
let mut counter: Value = self.safe_number(delta.clone(), Value::Int(1), &[]);
let mut price: Value = self.safe_number(delta, Value::Int(0), &[]);
let mut size: Value = (if (amount.as_f64().unwrap_or(f64::NAN) < ((0i64) as f64)) { negate(&amount) } else { amount.clone() });
let mut side: Value = (if (amount.as_f64().unwrap_or(f64::NAN) < ((0i64) as f64)) { Value::Str("asks".into()) } else { Value::Str("bids".into()) });
let mut bookside: Value = get_value(&orderbook, &side);
let mut bookside: Value = get_value(&orderbook, &side);
bookside.store_array(Value::from(vec![price.clone(), size.clone(), counter.clone()]));
}
}
}
add_element_to_object(&mut orderbook, &Value::Str("symbol".into()), symbol.clone());
client.resolve(&[orderbook.clone(), messageHash.clone()]);
} else {
let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
let mut deltas: Value = message.get(1).cloned().unwrap_or(Value::Null);
let mut orderbookItem: Value = get_value(&self.orderbooks, &symbol);
if isRaw {
let mut price: Value = self.safe_string(deltas.clone(), Value::Int(1), &[]);
let mut deltas2: Value = get_value(&deltas, &Value::Int(2));
let mut size: Value = (if (deltas2.as_f64().unwrap_or(f64::NAN) < ((0i64) as f64)) { negate(&deltas2) } else { deltas2.clone() });
let mut side: Value = (if (deltas2.as_f64().unwrap_or(f64::NAN) < ((0i64) as f64)) { Value::Str("asks".into()) } else { Value::Str("bids".into()) });
let mut bookside: Value = get_value(&orderbookItem, &side);
let mut bookside: Value = get_value(&orderbookItem, &side);
// price = 0 means that you have to remove the order from your book
let mut amount: Value = (if is_true(&crate::precise::Precise::stringGt(&price, &Value::Str("0".into()))) { size.clone() } else { Value::Str("0".into()) });
let mut idString: Value = self.safe_string(deltas.clone(), Value::Int(0), &[]);
bookside.store_array(Value::from(vec![self.parse_number(price.clone(), &[]), self.parse_number(amount.clone(), &[]), idString]));
} else {
let mut amount: Value = self.safe_string(deltas.clone(), Value::Int(2), &[]);
let mut counter: Value = self.safe_string(deltas.clone(), Value::Int(1), &[]);
let mut price: Value = self.safe_string(deltas, Value::Int(0), &[]);
let mut size: Value = (if is_true(&crate::precise::Precise::stringLt(&amount, &Value::Str("0".into()))) { crate::precise::Precise::stringNeg(&amount) } else { amount.clone() });
let mut side: Value = (if is_true(&crate::precise::Precise::stringLt(&amount, &Value::Str("0".into()))) { Value::Str("asks".into()) } else { Value::Str("bids".into()) });
let mut bookside: Value = get_value(&orderbookItem, &side);
let mut bookside: Value = get_value(&orderbookItem, &side);
bookside.store_array(Value::from(vec![self.parse_number(price, &[]), self.parse_number(size, &[]), self.parse_number(counter, &[])]));
}
client.resolve(&[orderbook, messageHash]);
}
}
pub fn handle_checksum(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
//
// [ 173904, "cs", -890884919 ]
//
let mut marketId: Value = self.safe_string_k(subscription.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[]);
let mut channel: Value = Value::Str("book".into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", channel, Value::Str(":".into())).into()), marketId).into());
let mut book: Value = self.safe_dict(self.orderbooks.clone(), symbol.clone(), &[]);
if (book == Value::Null) {
return;
}
let mut depth: f64 = ((25i64) as f64); // covers the first 25 bids and asks
let mut stringArray: Value = Value::from(vec![]);
let mut bids: Value = book.as_map().and_then(|__m| __m.get("bids")).cloned().unwrap_or(Value::Null);
let mut asks: Value = book.as_map().and_then(|__m| __m.get("asks")).cloned().unwrap_or(Value::Null);
let mut prec: Option<String> = self.safe_string_k(subscription, "prec", &[Value::Str("P0".into())]).as_str().map(str::to_owned);
let mut isRaw: bool = prec.as_deref() == Some("R0");
let mut idToCheck: Value = (if isRaw { Value::Int(2) } else { Value::Int(0) });
{
let mut i: Value = Value::Int(0);
let mut __for_first_105: bool = true;
while { if !__for_first_105 { 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_105 = false; i.as_f64().unwrap_or(f64::NAN) < depth } {
let mut bid: Value = self.safe_list(bids.clone(), i.clone(), &[]);
let mut ask: Value = self.safe_list(asks.clone(), i.clone(), &[]);
if (bid != Value::Null) {
append_to_array(&mut stringArray, self.number_to_string(get_value(&get_value(&bids, &i), &idToCheck)));
append_to_array(&mut stringArray, self.number_to_string(get_value(&get_value(&bids, &i), &Value::Int(1))));
}
if (ask != Value::Null) {
append_to_array(&mut stringArray, self.number_to_string(get_value(&get_value(&asks, &i), &idToCheck)));
let mut aski1: Value = get_value(&get_value(&asks, &i), &Value::Int(1));
append_to_array(&mut stringArray, self.number_to_string(negate(&aski1)));
}
}
}
let mut payload: Value = join(&stringArray, &Value::Str(":".into()));
let mut localChecksum: Value = self.crc32(&[payload, Value::Bool(true)]);
let mut responseChecksum: Value = self.safe_integer(message, Value::Int(2), &[]);
if (responseChecksum.as_f64() != localChecksum.as_f64()) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
remove(&mut self.orderbooks, &symbol);
let mut checksum: Value = self.handle_option(Value::Str("watchOrderBook".into()), Value::Str("checksum".into()), &[Value::Bool(true)]);
if is_equal(&checksum, &Value::Bool(true)) {
let mut error = Value::from(crate::exchange_errors::checksum_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), self.orderbook_checksum_message(symbol))));
client.reject(&[Value::from(error), messageHash]);
}
}
}
/*
* @method
* @name bitfinex#watchBalance
* @description watch 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
* @param {str} [params.type] spot or contract if not provided this.options['defaultType'] is used
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn watch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut balanceType: Value = self.safe_string_k(params.clone(), "wallet", &[Value::Str("exchange".into())]); // exchange, margin
params = self.omit(params, Value::Str("wallet".into()), &[]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("balance:".into()), balanceType).into());
return self.subscribe_private(messageHash).await;
Value::Null
}
pub fn handle_balance(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
//
// snapshot (exchange + margin together)
// [
// 0,
// "ws",
// [
// [
// "exchange",
// "LTC",
// 0.05479727,
// 0,
// null,
// "Trading fees for 0.05 LTC (LTCUST) @ 51.872 on BFX (0.2%)",
// null,
// ]
// [
// "margin",
// "USTF0",
// 11.960650700086292,
// 0,
// null,
// "Trading fees for 0.1 LTCF0 (LTCF0:USTF0) @ 51.844 on BFX (0.065%)",
// null,
// ],
// ],
// ]
//
// spot
// [
// 0,
// "wu",
// [
// "exchange",
// "LTC", // currency
// 0.06729727, // wallet balance
// 0, // unsettled balance
// 0.06729727, // available balance might be null
// "Exchange 0.4 LTC for UST @ 65.075",
// {
// "reason": "TRADE",
// "order_id": 96596397973,
// "order_id_oppo": 96596632735,
// "trade_price": "65.075",
// "trade_amount": "-0.4",
// "order_cid": 1654636218766,
// "order_gid": null
// }
// ]
// ]
//
// margin
//
// [
// "margin",
// "USTF0",
// 11.960650700086292, // total
// 0,
// 6.776250700086292, // available
// "Trading fees for 0.1 LTCF0 (LTCF0:USTF0) @ 51.844 on BFX (0.065%)",
// null
// ]
//
let mut updateType: Value = self.safe_value(message.clone(), Value::Int(1), &[]);
let mut data: Value = Value::from(vec![]);
if (updateType.as_str() == Some("ws")) {
data = self.safe_value(message.clone(), Value::Int(2), &[]);
} else {
data = Value::from(vec![self.safe_value(message.clone(), Value::Int(2), &[])]);
}
let mut updatedTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_106: bool = true;
while { if !__for_first_106 { 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_106 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut rawBalance: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut currencyId: Value = self.safe_string(rawBalance.clone(), Value::Int(1), &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut balance: Value = self.parse_ws_balance(rawBalance.clone());
let mut balanceType: Value = self.safe_string(rawBalance, Value::Int(0), &[]);
let mut oldBalance: Value = self.safe_dict(self.balance.clone(), balanceType.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (code != Value::Null) {
if let Value::Dict(__d) = &mut oldBalance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), balance.clone()); }
}
if let Value::Dict(__d) = &mut oldBalance { std::sync::Arc::make_mut(__d).insert("info".into(), message.clone()); }
{ let __be_tmp = self.safe_balance(oldBalance); if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&balanceType), __be_tmp); } }
if let Value::Dict(__d) = &mut updatedTypes { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&balanceType), Value::Bool(true)); }
}
}
let mut updatesKeys: Value = object_keys(&updatedTypes);
{
let mut i: Value = Value::Int(0);
let mut __for_first_107: bool = true;
while { if !__for_first_107 { 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_107 = false; i.as_f64().unwrap_or(f64::NAN) < ((updatesKeys.len() as i64) as f64) } {
let mut type_var: Value = updatesKeys.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 messageHash: Value = Value::Str(format!("{}{}", Value::Str("balance:".into()), type_var).into());
client.resolve(&[get_value(&self.balance, &type_var), messageHash]);
}
}
}
pub fn parse_ws_balance(&self, mut balance: Value) -> Value {
//
// [
// "exchange",
// "LTC",
// 0.05479727, // balance
// 0,
// null, // available null if not calculated yet
// "Trading fees for 0.05 LTC (LTCUST) @ 51.872 on BFX (0.2%)",
// null,
// ]
//
let mut totalBalance: Value = self.safe_string(balance.clone(), Value::Int(2), &[]);
let mut availableBalance: Value = self.safe_string(balance, Value::Int(4), &[]);
let mut account: Value = self.account();
if (availableBalance != Value::Null) {
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), availableBalance); }
}
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), totalBalance); }
return account;
Value::Null
}
pub fn handle_system_status(&self, mut client: Value, mut message: Value) -> Value {
return message;
Value::Null
}
pub fn handle_unsubscription_status(&mut self, mut client: Value, mut message: Value) -> Value {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "event": "unsubscribed",
// "status": "OK",
// "chanId": CHANNEL_ID
// }
//
let mut channelId: Value = (match message.get("chanId") { 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 unSubChannel: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), channelId).into());
let mut subMessageHash: Value = self.safe_string(get_value(&client, &Value::Str("subscriptions".into())), unSubChannel.clone(), &[]);
let mut subscription: Value = self.safe_dict(get_value(&client, &Value::Str("subscriptions".into())), Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into()), &[]);
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &unSubChannel);
let mut messageHashes: Value = self.safe_list_k(subscription.clone(), "messageHashes", &[Value::from(vec![])]);
let mut subMessageHashes: Value = self.safe_list_k(subscription.clone(), "subMessageHashes", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_108: bool = true;
while { if !__for_first_108 { 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_108 = 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(subscription);
return Value::Bool(true);
Value::Null
}
pub fn handle_subscription_status(&self, mut client: Value, mut message: Value) -> Value {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "event": "subscribed",
// "channel": "book",
// "chanId": 67473,
// "symbol": "tBTCUSD",
// "prec": "P0",
// "freq": "F0",
// "len": "25",
// "pair": "BTCUSD"
// }
//
// {
// event: 'subscribed',
// channel: 'candles',
// chanId: 128306,
// key: 'trade:1m:tBTCUST'
// }
//
let mut channelId: Value = (match __pro_message.get("chanId").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 });
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &channelId, message.clone());
// store the opposite direction too for unWatch
let mut mappings: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("book".to_string(), Value::Str("orderbook".into()));
m.insert("candles".to_string(), Value::Str("ohlcv".into()));
m.insert("ticker".to_string(), Value::Str("ticker".into()));
m.insert("trades".to_string(), Value::Str("trades".into()));
m
});
let mut unifiedChannel: Value = self.safe_string(mappings, (match __pro_message.get("channel").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }), &[]);
if (matches!(&message, Value::Dict(__d) if __d.contains_key("key"))) {
// handle ohlcv differently because the message is different
let mut key: Value = (match __pro_message.get("key").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 subKeyId: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), key).into());
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &subKeyId, channelId.clone());
} else {
let mut marketId: Value = self.safe_string_k(message.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[]);
if (unifiedChannel != Value::Null) {
let mut subId: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), unifiedChannel).into()), Value::Str(":".into())).into()), symbol).into());
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &subId, channelId);
}
}
return message;
Value::Null
}
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 = crate::value::get_value_k(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null), "private");
let mut client: Value = self.client(&[url.clone()]);
let mut messageHash: Value = Value::Str("authenticated".into());
let mut future: Value = client.reusable_future(messageHash.clone());
let mut authenticated: Value = self.safe_value(get_value(&client, &Value::Str("subscriptions".into())), messageHash.clone(), &[]);
if (authenticated == Value::Null) {
let mut nonce: Value = self.milliseconds();
let mut payload: Value = Value::Str(format!("{}{}", Value::Str("AUTH".into()), to_string_val(&nonce)).into());
let mut signature: Value = self.hmac(self.encode(payload.clone()), self.encode(self.secret.clone()), Value::Str("sha384".into()), &[Value::Str("hex".into())]);
let mut event: Value = Value::Str("auth".into());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), self.apiKey.clone());
m.insert("authSig".to_string(), signature);
m.insert("authNonce".to_string(), nonce);
m.insert("authPayload".to_string(), payload);
m.insert("event".to_string(), event);
m
});
let mut message: Value = self.extend(request, &[params]);
self.watch(url, messageHash.clone(), &[message, messageHash.clone()]).await;
}
return crate::exchange_stubs::ws_await_flight(&future).await;
Value::Null
}
pub fn handle_authentication_message(&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 messageHash: Value = Value::Str("authenticated".into());
let mut status: Option<String> = (match __pro_message.get("status").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 (status.as_deref() == Some("OK")) {
// we resolve the future here permanently so authentication only happens once
let mut future: Value = self.safe_value(get_value(&client, &Value::Str("futures".into())), messageHash.clone(), &[]);
future.resolve(&[Value::Bool(true)]);
} else {
let mut error = Value::from(crate::exchange_errors::authentication_error(json_stringify(&message)));
client.reject(&[Value::from(error), messageHash.clone()]);
// allows further authentication attempts
if (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash)) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
}
}
}
/*
* @method
* @name bitfinex#watchOrders
* @description watches information on multiple orders made by the user
* @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 messageHash: Value = Value::Str("orders".into());
if (symbol != Value::Null) {
let mut market: Value = self.market(symbol.clone());
messageHash = Value::Str(format!("{}{}", messageHash, Value::Str(format!("{}{}", Value::Str(":".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into())).into());
}
let mut orders: Value = self.subscribe_private(messageHash).await;
if is_true(&self.newUpdates) {
limit = orders.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_symbol_since_limit(orders, &[symbol, since, limit, Value::Bool(true)]);
Value::Null
}
pub fn handle_orders(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
//
// limit order
// [
// 0,
// "on", // ou or oc
// [
// 96923856256, // order id
// null, // gid
// 1655029337026, // cid
// "tLTCUST", // symbol
// 1655029337027, // created timestamp
// 1655029337029, // updated timestamp
// 0.1, // amount
// 0.1, // amount_orig
// "EXCHANGE LIMIT", // order type
// null, // type_prev
// null, // mts_tif
// null, // placeholder
// 0, // flags
// "ACTIVE", // status
// null,
// null,
// 30, // price
// 0, // price average
// 0, // price_trailing
// 0, // price_aux_limit
// null,
// null,
// null,
// 0, // notify
// 0,
// null,
// null,
// null,
// "BFX",
// null,
// null,
// ]
// ]
//
let mut data: Value = self.safe_list(message.clone(), Value::Int(2), &[Value::from(vec![])]);
let mut messageType: Option<String> = self.safe_string(message, Value::Int(1), &[]).as_str().map(str::to_owned);
if (self.orders.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCacheBySymbolById::new(limit);
}
let mut orders: Value = self.orders.clone();
let mut symbolIds: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (messageType.as_deref() == Some("os")) {
let mut snapshotLength: f64 = ((data.len() as i64) as f64);
if (snapshotLength == 0.0) {
return;
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_109: bool = true;
while { if !__for_first_109 { 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_109 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut value: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut parsed: Value = self.parse_ws_order(value, &[]);
let mut symbol: Value = parsed.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut symbolIds { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Bool(true)); }
orders.append(parsed.clone());
}
}
} else {
let mut parsed: Value = self.parse_ws_order(data, &[]);
orders.append(parsed.clone());
let mut symbol: Value = parsed.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut symbolIds { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Bool(true)); }
}
let mut name: Value = Value::Str("orders".into());
client.resolve(&[self.orders.clone(), name.clone()]);
let mut keys: Value = object_keys(&symbolIds);
{
let mut i: Value = Value::Int(0);
let mut __for_first_110: bool = true;
while { if !__for_first_110 { 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_110 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut symbol: Value = keys.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", name, Value::Str(":".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
client.resolve(&[self.orders.clone(), messageHash]);
}
}
}
pub fn parse_ws_order_status(&self, mut status: Value) -> Option<String> {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ACTIVE".to_string(), Value::Str("open".into()));
m.insert("CANCELED".to_string(), Value::Str("canceled".into()));
m.insert("EXECUTED".to_string(), Value::Str("closed".into()));
m.insert("PARTIALLY".to_string(), Value::Str("open".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub fn parse_ws_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// [
// 97084883506, // order id
// null,
// 1655110144596, // clientOrderId
// "tLTCUST", // symbol
// 1655110144596, // created timestamp
// 1655110144598, // updated timestamp
// 0, // amount
// 0.1, // amount_orig negative if sell order
// "EXCHANGE MARKET", // type
// null,
// null,
// null,
// 0,
// "EXECUTED @ 42.821(0.1)", // status
// null,
// null,
// 42.799, // price
// 42.821, // price average
// 0, // price trailing
// 0, // price_aux_limit
// null,
// null,
// null,
// 0,
// 0,
// null,
// null,
// null,
// "BFX",
// null,
// null,
// {}
// ]
//
let mut id: Value = self.safe_string(order.clone(), Value::Int(0), &[]);
let mut clientOrderId: Value = self.safe_string(order.clone(), Value::Int(1), &[]);
let mut marketId: Value = self.safe_string(order.clone(), Value::Int(3), &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[]);
market = self.safe_market(&[symbol.clone()]);
let mut amount: Value = self.safe_string(order.clone(), Value::Int(7), &[]);
let mut side: Value = Value::Str("buy".into());
if is_true(&crate::precise::Precise::stringLt(&amount, &Value::Str("0".into()))) {
amount = crate::precise::Precise::stringAbs(&amount);
side = Value::Str("sell".into());
}
let mut remaining: Value = crate::precise::Precise::stringAbs(&self.safe_string(order.clone(), Value::Int(6), &[]));
let mut type_var: Value = self.safe_string(order.clone(), Value::Int(8), &[Value::Str("".into())]);
if Value::Int(type_var.as_str().and_then(|__s| __s.find("LIMIT")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64) {
type_var = Value::Str("limit".into());
} else if Value::Int(type_var.as_str().and_then(|__s| __s.find("MARKET")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64) {
type_var = Value::Str("market".into());
}
let mut rawState: Value = self.safe_string(order.clone(), Value::Int(13), &[Value::Str("".into())]);
let mut stateParts: Value = split(&rawState, &Value::Str(" ".into()));
let mut trimmedStatus: Value = self.safe_string(stateParts, Value::Int(0), &[]);
let mut status: Value = self.parse_ws_order_status(trimmedStatus).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut price: Value = self.safe_string(order.clone(), Value::Int(16), &[]);
let mut timestamp: Value = self.safe_integer2(order.clone(), Value::Int(5), Value::Int(4), &[]);
let mut average: Value = self.safe_string(order.clone(), Value::Int(17), &[]);
let mut stopPrice: Value = self.omit_zero(self.safe_string(order.clone(), Value::Int(18), &[]));
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order);
m.insert("id".to_string(), id);
m.insert("clientOrderId".to_string(), clientOrderId);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), type_var);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("stopPrice".to_string(), stopPrice.clone());
m.insert("triggerPrice".to_string(), stopPrice);
m.insert("average".to_string(), average);
m.insert("amount".to_string(), amount);
m.insert("remaining".to_string(), remaining);
m.insert("filled".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("fee".to_string(), Value::Null);
m.insert("cost".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[market]);
Value::Null
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
let mut channelId: Value = self.safe_string(message.clone(), Value::Int(0), &[]);
//
// [
// 1231,
// "hb",
// ]
//
// auth message
// {
// "event": "auth",
// "status": "OK",
// "chanId": 0,
// "userId": 3159883,
// "auth_id": "ac7108e7-2f26-424d-9982-c24700dc02ca",
// "caps": {
// "orders": { read: 1, write: 1 },
// "account": { read: 1, write: 1 },
// "funding": { read: 1, write: 1 },
// "history": { read: 1, write: 0 },
// "wallets": { read: 1, write: 1 },
// "withdraw": { read: 0, write: 1 },
// "positions": { read: 1, write: 1 },
// "ui_withdraw": { read: 0, write: 0 }
// }
// }
//
if (matches!(&message, Value::Arr(_))) {
if (message.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null).as_str() == Some("hb")) {
return;
}
let mut subscription: Value = self.safe_dict(get_value(&client, &Value::Str("subscriptions".into())), channelId.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut channel: Value = self.safe_string_k(subscription.clone(), "channel", &[]);
let mut name: Value = self.safe_string(message.clone(), Value::Int(1), &[]);
let mut publicMethods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("book".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("cs".to_string(), Value::Str("handle_checksum".into()).clone());
m.insert("candles".to_string(), Value::Str("handle_ohlcv".into()).clone());
m.insert("ticker".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("trades".to_string(), Value::Str("handle_trades".into()).clone());
m
});
let mut privateMethods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("os".to_string(), Value::Str("handle_orders".into()).clone());
m.insert("ou".to_string(), Value::Str("handle_orders".into()).clone());
m.insert("on".to_string(), Value::Str("handle_orders".into()).clone());
m.insert("oc".to_string(), Value::Str("handle_orders".into()).clone());
m.insert("wu".to_string(), Value::Str("handle_balance".into()).clone());
m.insert("ws".to_string(), Value::Str("handle_balance".into()).clone());
m.insert("tu".to_string(), Value::Str("handle_my_trade".into()).clone());
m
});
let mut method: Value = Value::Null;
if (channelId.as_str() == Some("0")) {
method = self.safe_value(privateMethods, name.clone(), &[]);
} else {
method = self.safe_value2(publicMethods, name, channel, &[]);
}
if (method != Value::Null) {
self.dispatch_ws_handler(&method, &[client.clone(), message.clone(), subscription]);
}
} else {
let mut event: Value = self.safe_string_k(message.clone(), "event", &[]);
if (event != Value::Null) {
let mut methods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), Value::Str("handle_system_status".into()).clone());
m.insert("subscribed".to_string(), Value::Str("handle_subscription_status".into()).clone());
m.insert("unsubscribed".to_string(), Value::Str("handle_unsubscription_status".into()).clone());
m.insert("auth".to_string(), Value::Str("handle_authentication_message".into()).clone());
m
});
let mut method: Value = self.safe_value(methods, event, &[]);
if (method != Value::Null) {
self.dispatch_ws_handler(&method, &[client, message]);
}
}
}
}
}