// 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 DeribitCore {
pub parent: crate::exchanges::deribit::DeribitCore,
}
impl DeribitCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::deribit::DeribitCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = DeribitCore::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 DeribitCore {
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 DeribitCore {
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,
"clean_order_book" => self.clean_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"handle_authentication_message" => self.handle_authentication_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"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 },
"parse_ws_bid_ask" => self.parse_ws_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_ohlcv" => self.parse_ws_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"request_id" => self.request_id(),
"watch_balance" => self.watch_balance(&args[..]).await,
"watch_bids_asks" => self.watch_bids_asks(&args[..]).await,
"watch_multiple_wrapper" => self.watch_multiple_wrapper(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"watch_my_trades" => self.watch_my_trades(&args[..]).await,
"watch_ohlcv" => self.watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_ohlcv_for_symbols" => self.watch_ohlcv_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book_for_symbols" => self.watch_order_book_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_tickers" => self.watch_tickers(&args[..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_trades_for_symbols" => self.watch_trades_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
// Go-style inheritance: an un-overridden method dispatches to the parent core.
_ => crate::exchange_generated::ExchangeBase::call_dynamic(&mut self.parent, method, args).await,
}
})
}
}
impl DeribitCore {
/// 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 },
"clean_order_book" => self.clean_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"handle_authentication_message" => self.handle_authentication_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_balance" => { self.handle_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_bid_ask" => { self.handle_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_delta" => { self.handle_delta(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_deltas" => { self.handle_deltas(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_my_trades" => { self.handle_my_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_ohlcv" => { self.handle_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book" => { self.handle_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_orders" => { self.handle_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_ticker" => { self.handle_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_trades" => { self.handle_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"parse_ws_bid_ask" => self.parse_ws_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_ohlcv" => self.parse_ws_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"request_id" => self.request_id(),
"watch_balance" => { crate::exchange_stubs::enqueue_spawn("watch_balance", args.to_vec()); crate::Value::Null },
"watch_bids_asks" => { crate::exchange_stubs::enqueue_spawn("watch_bids_asks", args.to_vec()); crate::Value::Null },
"watch_multiple_wrapper" => { crate::exchange_stubs::enqueue_spawn("watch_multiple_wrapper", args.to_vec()); crate::Value::Null },
"watch_my_trades" => { crate::exchange_stubs::enqueue_spawn("watch_my_trades", args.to_vec()); crate::Value::Null },
"watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("watch_ohlcv", args.to_vec()); crate::Value::Null },
"watch_ohlcv_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_ohlcv_for_symbols", args.to_vec()); crate::Value::Null },
"watch_order_book" => { crate::exchange_stubs::enqueue_spawn("watch_order_book", args.to_vec()); crate::Value::Null },
"watch_order_book_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_order_book_for_symbols", args.to_vec()); crate::Value::Null },
"watch_orders" => { crate::exchange_stubs::enqueue_spawn("watch_orders", args.to_vec()); crate::Value::Null },
"watch_ticker" => { crate::exchange_stubs::enqueue_spawn("watch_ticker", args.to_vec()); crate::Value::Null },
"watch_tickers" => { crate::exchange_stubs::enqueue_spawn("watch_tickers", args.to_vec()); crate::Value::Null },
"watch_trades" => { crate::exchange_stubs::enqueue_spawn("watch_trades", args.to_vec()); crate::Value::Null },
"watch_trades_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_trades_for_symbols", args.to_vec()); crate::Value::Null },
_ => crate::Value::Null,
}
}
}
impl std::ops::Deref for DeribitCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for DeribitCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl DeribitCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.parent.describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Bool(true));
m.insert("watchBalance".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(true));
m.insert("watchBidsAsks".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m.insert("watchTradesForSymbols".to_string(), Value::Bool(true));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOrderBookForSymbols".to_string(), Value::Bool(true));
m.insert("watchOHLCV".to_string(), Value::Bool(true));
m.insert("watchOHLCVForSymbols".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Str("wss://test.deribit.com/ws/api/v2".into()));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Str("wss://www.deribit.com/ws/api/v2".into()));
m
}));
m
}));
m.insert("options".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("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1".into()));
m.insert("3m".to_string(), Value::Str("3".into()));
m.insert("5m".to_string(), Value::Str("5".into()));
m.insert("15m".to_string(), Value::Str("15".into()));
m.insert("30m".to_string(), Value::Str("30".into()));
m.insert("1h".to_string(), Value::Str("60".into()));
m.insert("2h".to_string(), Value::Str("120".into()));
m.insert("4h".to_string(), Value::Str("180".into()));
m.insert("6h".to_string(), Value::Str("360".into()));
m.insert("12h".to_string(), Value::Str("720".into()));
m.insert("1d".to_string(), Value::Str("1D".into()));
m
}));
m.insert("watchTradesForSymbols".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("interval".to_string(), Value::Str("100ms".into()));
m
}));
m.insert("watchOrderBookForSymbols".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("interval".to_string(), Value::Str("100ms".into()));
m.insert("useDepthEndpoint".to_string(), Value::Bool(false));
m.insert("depth".to_string(), Value::Str("20".into()));
m.insert("group".to_string(), Value::Str("none".into()));
m
}));
m
}));
m.insert("currencies".to_string(), Value::from(vec![Value::Str("BTC".into()), Value::Str("ETH".into()), Value::Str("SOL".into()), Value::Str("USDC".into())]));
m
}));
m.insert("streaming".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
})]);
Value::Null
}
pub fn request_id(&mut self) -> Value {
let mut requestId: Value = self.sum(&[self.safe_integer_k(self.options.clone(), "requestId", &[Value::Int(0)]), Value::Int(1)]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("requestId".into(), requestId.clone()); }
return requestId;
Value::Null
}
/*
* @method
* @name deribit#watchBalance
* @see https://docs.deribit.com/#user-portfolio-currency
* @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
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn watch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.authenticate(&[params.clone()]).await;
let mut messageHash: Value = Value::Str("balance".into());
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut currencies: Value = self.safe_list_k(self.options.clone(), "currencies", &[Value::from(vec![])]);
let mut channels: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_291: bool = true;
while { if !__for_first_291 { 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_291 = false; i.as_f64().unwrap_or(f64::NAN) < ((currencies.len() as i64) as f64) } {
let mut currencyCode: Value = currencies.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
append_to_array(&mut channels, add(&Value::Str("user.portfolio.".into()), ¤cyCode));
}
}
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("jsonrpc".to_string(), Value::Str("2.0".into()));
m.insert("method".to_string(), Value::Str("private/subscribe".into()));
m.insert("params".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channels".to_string(), channels);
m
}));
m.insert("id".to_string(), self.request_id());
m
});
let mut request: Value = self.deep_extend(subscribe, &[params]);
return self.watch(url, messageHash.clone(), &[request.clone(), messageHash.clone(), request.clone()]).await;
Value::Null
}
pub fn handle_balance(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// subscription
// {
// "jsonrpc": "2.0",
// "method": "subscription",
// "params": {
// "channel": "user.portfolio.btc",
// "data": {
// "total_pl": 0,
// "session_upl": 0,
// "session_rpl": 0,
// "projected_maintenance_margin": 0,
// "projected_initial_margin": 0,
// "projected_delta_total": 0,
// "portfolio_margining_enabled": false,
// "options_vega": 0,
// "options_value": 0,
// "options_theta": 0,
// "options_session_upl": 0,
// "options_session_rpl": 0,
// "options_pl": 0,
// "options_gamma": 0,
// "options_delta": 0,
// "margin_balance": 0.0015,
// "maintenance_margin": 0,
// "initial_margin": 0,
// "futures_session_upl": 0,
// "futures_session_rpl": 0,
// "futures_pl": 0,
// "fee_balance": 0,
// "estimated_liquidation_ratio_map": {},
// "estimated_liquidation_ratio": 0,
// "equity": 0.0015,
// "delta_total_map": {},
// "delta_total": 0,
// "currency": "BTC",
// "balance": 0.0015,
// "available_withdrawal_funds": 0.0015,
// "available_funds": 0.0015
// }
// }
// }
//
let mut params: Value = (match message.get("params") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut data: Value = self.safe_dict_k(params, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert("info".into(), data.clone()); }
let mut currencyId: Value = self.safe_string_k(data.clone(), "currency", &[]);
let mut currencyCode: Value = self.safe_currency_code(currencyId, &[]);
let mut balance: Value = self.parse_balance(data);
if (currencyCode != Value::Null) {
if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(¤cyCode), balance.clone()); }
}
let mut messageHash: Value = Value::Str("balance".into());
client.resolve(&[self.balance.clone(), messageHash]);
}
/*
* @method
* @name deribit#watchTicker
* @see https://docs.deribit.com/#ticker-instrument_name-interval
* @description watches a price ticker, a statistical calculation with the information for a specific market.
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {str} [params.interval] specify aggregation and frequency of notifications. Possible values: 100ms, raw
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut interval: Value = self.safe_string_k(params.clone(), "interval", &[Value::Str("100ms".into())]);
params = self.omit(params.clone(), Value::Str("interval".into()), &[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (interval.as_str() == Some("raw")) {
self.authenticate(&[]).await;
}
let mut channel: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("ticker.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".".into())).into()), interval).into());
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("jsonrpc".to_string(), Value::Str("2.0".into()));
m.insert("method".to_string(), Value::Str("public/subscribe".into()));
m.insert("params".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channels".to_string(), Value::from(vec![Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("ticker.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".".into())).into()), interval).into())]));
m
}));
m.insert("id".to_string(), self.request_id());
m
});
let mut request: Value = self.deep_extend(message, &[params]);
return self.watch(url, channel.clone(), &[request.clone(), channel.clone(), request.clone()]).await;
Value::Null
}
/*
* @method
* @name deribit#watchTickers
* @see https://docs.deribit.com/#ticker-instrument_name-interval
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
* @param {string[]} [symbols] unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {str} [params.interval] specify aggregation and frequency of notifications. Possible values: 100ms, raw
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false)]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut interval: Value = self.safe_string_k(params.clone(), "interval", &[Value::Str("100ms".into())]);
params = self.omit(params.clone(), Value::Str("interval".into()), &[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (interval.as_str() == Some("raw")) {
self.authenticate(&[]).await;
}
let mut channels: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_292: bool = true;
while { if !__for_first_292 { 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_292 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut market: Value = self.market(symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
append_to_array(&mut channels, Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("ticker.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".".into())).into()), interval).into()));
}
}
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("jsonrpc".to_string(), Value::Str("2.0".into()));
m.insert("method".to_string(), Value::Str("public/subscribe".into()));
m.insert("params".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channels".to_string(), channels.clone());
m
}));
m.insert("id".to_string(), self.request_id());
m
});
let mut request: Value = self.deep_extend(message, &[params]);
let mut newTickers: Value = self.watch_multiple(url, channels.clone(), &[request.clone(), channels.clone(), request.clone()]).await;
if is_true(&self.newUpdates) {
let mut tickers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut tickers, &crate::value::get_value_k(&newTickers, "symbol"), newTickers.clone());
return tickers;
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".into()), &[symbols]);
Value::Null
}
pub fn handle_ticker(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "jsonrpc": "2.0",
// "method": "subscription",
// "params": {
// "channel": "ticker.BTC_USDC-PERPETUAL.raw",
// "data": {
// "timestamp": 1655393725040,
// "stats": [Object],
// "state": "open",
// "settlement_price": 21729.5891,
// "open_interest": 164.501,
// "min_price": 20792.9376,
// "max_price": 21426.225,
// "mark_price": 21109.555,
// "last_price": 21132,
// "instrument_name": "BTC_USDC-PERPETUAL",
// "index_price": 21122.3937,
// "funding_8h": -0.00022427,
// "estimated_delivery_price": 21122.3937,
// "current_funding": -0.00010782,
// "best_bid_price": 21106,
// "best_bid_amount": 1.143,
// "best_ask_price": 21113,
// "best_ask_amount": 0.327
// }
// }
// }
//
let mut params: Value = (match message.get("params") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut data: Value = self.safe_dict_k(params.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketId: Value = self.safe_string_k(data.clone(), "instrument_name", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[]);
let mut ticker: Value = self.parse_ticker(data, &[]);
let mut messageHash: Value = self.safe_string_k(params, "channel", &[]);
if let Value::Dict(__d) = &mut self.tickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker.clone()); }
client.resolve(&[ticker, messageHash]);
}
/*
* @method
* @name deribit#watchBidsAsks
* @see https://docs.deribit.com/#quote-instrument_name
* @description watches best bid & ask for symbols
* @param {string[]} [symbols] unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_bids_asks(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false)]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut channels: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_293: bool = true;
while { if !__for_first_293 { 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_293 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut market: Value = self.market(symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
append_to_array(&mut channels, Value::Str(format!("{}{}", Value::Str("quote.".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
}
}
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("jsonrpc".to_string(), Value::Str("2.0".into()));
m.insert("method".to_string(), Value::Str("public/subscribe".into()));
m.insert("params".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channels".to_string(), channels.clone());
m
}));
m.insert("id".to_string(), self.request_id());
m
});
let mut request: Value = self.deep_extend(message, &[params]);
let mut newTickers: Value = self.watch_multiple(url, channels.clone(), &[request.clone(), channels.clone(), request.clone()]).await;
if is_true(&self.newUpdates) {
let mut tickers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut tickers, &crate::value::get_value_k(&newTickers, "symbol"), newTickers.clone());
return tickers;
}
return self.filter_by_array(self.bidsasks.clone(), Value::Str("symbol".into()), &[symbols]);
Value::Null
}
pub fn handle_bid_ask(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "jsonrpc": "2.0",
// "method": "subscription",
// "params": {
// "channel": "quote.BTC_USDT",
// "data": {
// "best_bid_amount": 0.026,
// "best_ask_amount": 0.026,
// "best_bid_price": 63908,
// "best_ask_price": 63940,
// "instrument_name": "BTC_USDT",
// "timestamp": 1727765131750
// }
// }
// }
//
let mut params: Value = (match message.get("params") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut data: Value = self.safe_dict_k(params.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ticker: Value = self.parse_ws_bid_ask(data, &[]);
let mut symbol: Value = ticker.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut self.bidsasks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker.clone()); }
let mut messageHash: Value = self.safe_string_k(params, "channel", &[]);
client.resolve(&[ticker, messageHash]);
}
pub fn parse_ws_bid_ask(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Value = self.safe_string_k(ticker.clone(), "instrument_name", &[]);
market = self.safe_market(&[marketId, market.clone()]);
let mut symbol: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut timestamp: Value = self.safe_integer_k(ticker.clone(), "timestamp", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("ask".to_string(), self.safe_string_k(ticker.clone(), "best_ask_price", &[]));
m.insert("askVolume".to_string(), self.safe_string_k(ticker.clone(), "best_ask_amount", &[]));
m.insert("bid".to_string(), self.safe_string_k(ticker.clone(), "best_bid_price", &[]));
m.insert("bidVolume".to_string(), self.safe_string_k(ticker.clone(), "best_bid_amount", &[]));
m.insert("info".to_string(), ticker);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name deribit#watchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://docs.deribit.com/#trades-instrument_name-interval
* @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
* @param {str} [params.interval] specify aggregation and frequency of notifications. Possible values: 100ms, raw
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("callerMethodName".into(), Value::Str("watchTrades".into())); }
return self.watch_trades_for_symbols(Value::from(vec![symbol]), &[since, limit, params]).await;
Value::Null
}
/*
* @method
* @name deribit#watchTradesForSymbols
* @description get the list of most recent trades for a list of symbols
* @see https://docs.deribit.com/#trades-instrument_name-interval
* @param {string[]} symbols unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_trades_for_symbols(&mut self, mut symbols: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut interval: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchTradesForSymbols".into()), Value::Str("interval".into()), &[Value::Str("100ms".into())]); interval = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (interval.as_str() == Some("raw")) {
self.authenticate(&[]).await;
}
let mut trades: Value = self.watch_multiple_wrapper(Value::Str("trades".into()), interval, &[symbols, params]).await;
if is_true(&self.newUpdates) {
let mut first: Value = self.safe_dict(trades.clone(), Value::Int(0), &[]);
let mut tradeSymbol: Value = self.safe_string_k(first, "symbol", &[]);
limit = trades.get_limit(tradeSymbol, limit.clone());
}
return self.filter_by_since_limit(trades, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
pub fn handle_trades(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "jsonrpc": "2.0",
// "method": "subscription",
// "params": {
// "channel": "trades.BTC_USDC-PERPETUAL.100ms",
// "data": [{
// "trade_seq": 501899,
// "trade_id": "USDC-2436803",
// "timestamp": 1655397355998,
// "tick_direction": 2,
// "price": 21026,
// "mark_price": 21019.9719,
// "instrument_name": "BTC_USDC-PERPETUAL",
// "index_price": 21031.7847,
// "direction": "buy",
// "amount": 0.049
// }]
// }
// }
//
let mut params: Value = (match message.get("params") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut channel: Value = self.safe_string_k(params.clone(), "channel", &[Value::Str("".into())]);
let mut parts: Value = split(&channel, &Value::Str(".".into()));
let mut marketId: Value = self.safe_string(parts.clone(), Value::Int(1), &[]);
let mut interval: Value = self.safe_string(parts, Value::Int(2), &[]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut trades: Value = self.safe_list_k(params, "data", &[Value::from(vec![])]);
if (self.safe_dict(self.trades.clone(), symbol.clone(), &[]) == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ArrayCache::new(limit)); }
}
let mut stored: Value = get_value(&self.trades, &symbol);
{
let mut i: Value = Value::Int(0);
let mut __for_first_294: bool = true;
while { if !__for_first_294 { 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_294 = false; i.as_f64().unwrap_or(f64::NAN) < ((trades.len() as i64) as f64) } {
let mut trade: Value = trades.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_trade(trade, &[market.clone()]);
stored.append(parsed);
}
}
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), stored); }
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("trades|".into()), symbol).into()), Value::Str("|".into())).into()), interval).into());
client.resolve(&[get_value(&self.trades, &symbol), messageHash]);
}
/*
* @method
* @name deribit#watchMyTrades
* @description get the list of trades associated with the user
* @see https://docs.deribit.com/#user-trades-instrument_name-interval
* @param {string} symbol unified symbol of the market to fetch trades for. Use 'any' to watch all trades
* @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
* @param {str} [params.interval] specify aggregation and frequency of notifications. Possible values: 100ms, raw
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.authenticate(&[params.clone()]).await;
if (symbol != Value::Null) {
self.load_markets(&[]).await;
symbol = self.symbol(symbol.clone());
}
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut interval: Value = self.safe_string_k(params.clone(), "interval", &[Value::Str("raw".into())]);
params = self.omit(params.clone(), Value::Str("interval".into()), &[]);
let mut channel: Value = Value::Str(format!("{}{}", Value::Str("user.trades.any.any.".into()), interval).into());
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("jsonrpc".to_string(), Value::Str("2.0".into()));
m.insert("method".to_string(), Value::Str("private/subscribe".into()));
m.insert("params".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channels".to_string(), Value::from(vec![channel.clone()]));
m
}));
m.insert("id".to_string(), self.request_id());
m
});
let mut request: Value = self.deep_extend(message, &[params]);
let mut trades: Value = self.watch(url, channel.clone(), &[request.clone(), channel.clone(), request.clone()]).await;
return self.filter_by_symbol_since_limit(trades, &[symbol, since, limit, Value::Bool(true)]);
Value::Null
}
pub fn handle_my_trades(&self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "jsonrpc": "2.0",
// "method": "subscription",
// "params": {
// "channel": "user.trades.any.any.raw",
// "data": [{
// "trade_seq": 149546319,
// "trade_id": "219381310",
// "timestamp": 1655421193564,
// "tick_direction": 0,
// "state": "filled",
// "self_trade": false,
// "reduce_only": false,
// "profit_loss": 0,
// "price": 20236.5,
// "post_only": false,
// "order_type": "market",
// "order_id": "46108941243",
// "matching_id": null,
// "mark_price": 20233.96,
// "liquidity": "T",
// "instrument_name": "BTC-PERPETUAL",
// "index_price": 20253.31,
// "fee_currency": "BTC",
// "fee": 2.5e-7,
// "direction": "buy",
// "amount": 10
// }]
// }
// }
//
let mut params: Value = (match message.get("params") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut channel: Value = self.safe_string_k(params.clone(), "channel", &[Value::Str("".into())]);
let mut trades: Value = self.safe_list_k(params, "data", &[Value::from(vec![])]);
let mut cachedTrades: Value = self.myTrades.clone();
if (cachedTrades == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
cachedTrades = ArrayCacheBySymbolById::new(limit);
}
let mut parsed: Value = self.parse_trades(trades, &[]);
let mut marketIds: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_295: bool = true;
while { if !__for_first_295 { 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_295 = false; i.as_f64().unwrap_or(f64::NAN) < ((parsed.len() as i64) as f64) } {
let mut trade: Value = parsed.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
cachedTrades.append(trade.clone());
let mut symbol: Value = trade.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut marketIds { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Bool(true)); }
}
}
client.resolve(&[cachedTrades, channel]);
}
/*
* @method
* @name deribit#watchOrderBook
* @see https://docs.deribit.com/#book-instrument_name-group-depth-interval
* @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
* @param {string} [params.interval] Frequency of notifications. Events will be aggregated over this interval. Possible values: 100ms, raw
* @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 let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("callerMethodName".into(), Value::Str("watchOrderBook".into())); }
return self.watch_order_book_for_symbols(Value::from(vec![symbol]), &[limit, params]).await;
Value::Null
}
/*
* @method
* @name deribit#watchOrderBookForSymbols
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.deribit.com/#book-instrument_name-group-depth-interval
* @param {string[]} symbols unified array of symbols
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn watch_order_book_for_symbols(&mut self, mut symbols: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut interval: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrderBookForSymbols".into()), Value::Str("interval".into()), &[Value::Str("100ms".into())]); interval = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (interval.as_str() == Some("raw")) {
self.authenticate(&[]).await;
}
let mut descriptor: Value = Value::Str("".into());
let mut useDepthEndpoint: Value = Value::Null; // for more info, see comment in .options
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrderBookForSymbols".into()), Value::Str("useDepthEndpoint".into()), &[Value::Bool(false)]); useDepthEndpoint = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&useDepthEndpoint) {
let mut depth: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrderBookForSymbols".into()), Value::Str("depth".into()), &[Value::Str("20".into())]); depth = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut group: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrderBookForSymbols".into()), Value::Str("group".into()), &[Value::Str("none".into())]); group = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
descriptor = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", group, Value::Str(".".into())).into()), depth).into()), Value::Str(".".into())).into()), interval).into());
} else {
descriptor = interval;
}
let mut orderbook: Value = self.watch_multiple_wrapper(Value::Str("book".into()), descriptor, &[symbols, params]).await;
return orderbook.limit();
Value::Null
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// snapshot
// {
// "jsonrpc": "2.0",
// "method": "subscription",
// "params": {
// "channel": "book.BTC_USDC-PERPETUAL.raw",
// "data": {
// "type": "snapshot",
// "timestamp": 1655395057025,
// "instrument_name": "BTC_USDC-PERPETUAL",
// "change_id": 1550694837,
// "bids": [
// ["new", 20987, 0.487],
// ["new", 20986, 0.238],
// ],
// "asks": [
// ["new", 20999, 0.092],
// ["new", 21000, 1.238],
// ]
// }
// }
// }
//
// change
// {
// "jsonrpc": "2.0",
// "method": "subscription",
// "params": {
// "channel": "book.BTC_USDC-PERPETUAL.raw",
// "data": {
// "type": "change",
// "timestamp": 1655395168086,
// "prev_change_id": 1550724481,
// "instrument_name": "BTC_USDC-PERPETUAL",
// "change_id": 1550724483,
// "bids": [
// ["new", 20977, 0.109],
// ["delete", 20975, 0]
// ],
// "asks": []
// }
// }
// }
//
let mut params: Value = (match message.get("params") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut data: Value = self.safe_dict_k(params.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut channel: Value = self.safe_string_k(params, "channel", &[]);
let mut parts: Value = split(&channel, &Value::Str(".".into()));
let mut descriptor: Value = Value::Str("".into());
let mut partsLength: f64 = ((parts.len() as i64) as f64);
let mut isDetailed: bool = partsLength == 5.0;
if isDetailed {
let mut group: Value = self.safe_string(parts.clone(), Value::Int(2), &[]);
let mut depth: Value = self.safe_string(parts.clone(), Value::Int(3), &[]);
let mut interval: Value = self.safe_string(parts.clone(), Value::Int(4), &[]);
descriptor = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", group, Value::Str(".".into())).into()), depth).into()), Value::Str(".".into())).into()), interval).into());
} else {
let mut interval: Value = self.safe_string(parts, Value::Int(2), &[]);
descriptor = interval;
}
let mut marketId: Value = self.safe_string_k(data.clone(), "instrument_name", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[]);
let mut timestamp: Value = self.safe_integer_k(data.clone(), "timestamp", &[]);
if !(in_op(&self.orderbooks, &symbol)) {
{ let __be_tmp = self.counted_order_book(&[]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
}
let mut storedOrderBook: Value = get_value(&self.orderbooks, &symbol);
let mut asks: Value = self.safe_list_k(data.clone(), "asks", &[Value::from(vec![])]);
let mut bids: Value = self.safe_list_k(data, "bids", &[Value::from(vec![])]);
self.handle_deltas(get_value(&storedOrderBook, &Value::Str("asks".into())), asks);
self.handle_deltas(get_value(&storedOrderBook, &Value::Str("bids".into())), bids);
add_element_to_object(&mut storedOrderBook, &Value::Str("nonce".into()), timestamp.clone());
add_element_to_object(&mut storedOrderBook, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut storedOrderBook, &Value::Str("datetime".into()), self.iso8601(timestamp));
add_element_to_object(&mut storedOrderBook, &Value::Str("symbol".into()), symbol.clone());
if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), storedOrderBook.clone()); }
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("book|".into()), symbol).into()), Value::Str("|".into())).into()), descriptor).into());
client.resolve(&[storedOrderBook, messageHash]);
}
pub fn clean_order_book(&self, mut data: Value) -> Value {
let mut bids: Value = self.safe_list_k(data.clone(), "bids", &[Value::from(vec![])]);
let mut asks: Value = self.safe_list_k(data.clone(), "asks", &[Value::from(vec![])]);
let mut cleanedBids: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_296: bool = true;
while { if !__for_first_296 { 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_296 = false; i.as_f64().unwrap_or(f64::NAN) < ((bids.len() as i64) as f64) } {
append_to_array(&mut cleanedBids, Value::from(vec![get_value(&bids.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &Value::Int(1)), get_value(&bids.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &Value::Int(2))]));
}
}
let mut cleanedAsks: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_297: bool = true;
while { if !__for_first_297 { 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_297 = false; i.as_f64().unwrap_or(f64::NAN) < ((asks.len() as i64) as f64) } {
append_to_array(&mut cleanedAsks, Value::from(vec![get_value(&asks.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &Value::Int(1)), get_value(&asks.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &Value::Int(2))]));
}
}
if let Value::Dict(__d) = &mut data { std::sync::Arc::make_mut(__d).insert("bids".into(), cleanedBids); }
if let Value::Dict(__d) = &mut data { std::sync::Arc::make_mut(__d).insert("asks".into(), cleanedAsks); }
return data;
Value::Null
}
pub fn handle_delta(&self, mut bookside: Value, mut delta: Value) {
let mut price: Value = get_value(&delta, &Value::Int(1));
let mut amount: Value = get_value(&delta, &Value::Int(2));
if (get_value(&delta, &Value::Int(0)).as_str() == Some("new")) || (get_value(&delta, &Value::Int(0)).as_str() == Some("change")) {
bookside.store_array(Value::from(vec![price.clone(), amount.clone(), Value::Int(1)]));
} else if (get_value(&delta, &Value::Int(0)).as_str() == Some("delete")) {
bookside.store_array(Value::from(vec![price, amount, Value::Int(0)]));
}
}
pub fn handle_deltas(&self, mut bookside: Value, mut deltas: Value) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_298: bool = true;
while { if !__for_first_298 { 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_298 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&deltas).as_f64().unwrap_or(f64::NAN) } {
self.handle_delta(bookside.clone(), get_value(&deltas, &i));
}
}
}
/*
* @method
* @name deribit#watchOrders
* @see https://docs.deribit.com/#user-orders-instrument_name-raw
* @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;
}
self.authenticate(&[params.clone()]).await;
if (symbol != Value::Null) {
symbol = self.symbol(symbol.clone());
}
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut currency: Value = self.safe_string_k(params.clone(), "currency", &[Value::Str("any".into())]);
let mut interval: Value = self.safe_string_k(params.clone(), "interval", &[Value::Str("raw".into())]);
let mut kind: Value = self.safe_string_k(params.clone(), "kind", &[Value::Str("any".into())]);
params = self.omit(params.clone(), Value::Str("interval".into()), &[Value::Str("currency".into()), Value::Str("kind".into())]);
let mut channel: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("user.orders.".into()), kind).into()), Value::Str(".".into())).into()), currency).into()), Value::Str(".".into())).into()), interval).into());
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("jsonrpc".to_string(), Value::Str("2.0".into()));
m.insert("method".to_string(), Value::Str("private/subscribe".into()));
m.insert("params".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channels".to_string(), Value::from(vec![channel.clone()]));
m
}));
m.insert("id".to_string(), self.request_id());
m
});
let mut request: Value = self.deep_extend(message, &[params]);
let mut orders: Value = self.watch(url, channel.clone(), &[request.clone(), channel.clone(), request.clone()]).await;
if is_true(&self.newUpdates) {
limit = orders.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_symbol_since_limit(orders, &[symbol, since, limit, Value::Bool(true)]);
Value::Null
}
pub fn handle_orders(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
// Does not return a snapshot of current orders
//
// {
// "jsonrpc": "2.0",
// "method": "subscription",
// "params": {
// "channel": "user.orders.any.any.raw",
// "data": {
// "web": true,
// "time_in_force": "good_til_cancelled",
// "replaced": false,
// "reduce_only": false,
// "profit_loss": 0,
// "price": 50000,
// "post_only": false,
// "order_type": "limit",
// "order_state": "open",
// "order_id": "46094375191",
// "max_show": 10,
// "last_update_timestamp": 1655401625037,
// "label": '',
// "is_liquidation": false,
// "instrument_name": "BTC-PERPETUAL",
// "filled_amount": 0,
// "direction": "sell",
// "creation_timestamp": 1655401625037,
// "commission": 0,
// "average_price": 0,
// "api": false,
// "amount": 10
// }
// }
// }
//
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 params: Value = (match message.get("params") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut channel: Value = self.safe_string_k(params.clone(), "channel", &[Value::Str("".into())]);
let mut data: Value = self.safe_value_k(params, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orders: Value = Value::from(vec![]);
if (matches!(&data, Value::Arr(_))) {
orders = self.parse_orders(data.clone(), &[]);
} else {
let mut order: Value = self.parse_order(data, &[]);
orders = Value::from(vec![order]);
}
let mut cachedOrders: Value = self.orders.clone();
{
let mut i: Value = Value::Int(0);
let mut __for_first_299: bool = true;
while { if !__for_first_299 { 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_299 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
cachedOrders.append(orders.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));
}
}
client.resolve(&[self.orders.clone(), channel]);
}
/*
* @method
* @name deribit#watchOHLCV
* @see https://docs.deribit.com/#chart-trades-instrument_name-resolution
* @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;
}
symbol = self.symbol(symbol.clone());
let mut ohlcvs: Value = self.watch_ohlcv_for_symbols(Value::from(vec![Value::from(vec![symbol.clone(), timeframe.clone()])]), &[since, limit, params]).await;
return get_value(&get_value(&ohlcvs, &symbol), &timeframe);
Value::Null
}
/*
* @method
* @name deribit#watchOHLCVForSymbols
* @description watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://docs.deribit.com/#chart-trades-instrument_name-resolution
* @param {string[][]} symbolsAndTimeframes array of arrays containing unified symbols and timeframes to fetch OHLCV data for, example [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn watch_ohlcv_for_symbols(&mut self, mut symbolsAndTimeframes: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut symbolsLength: f64 = ((symbolsAndTimeframes.len() as i64) as f64);
if (symbolsLength == 0.0) || !(matches!(&symbolsAndTimeframes.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), Value::Arr(_))) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchOHLCVForSymbols() requires a an array of symbols and timeframes, like [['BTC/USDT', '1m'], ['LTC/USDT', '5m']]".into()))));
}
let mut symboltimeframecandlesVariable = self.watch_multiple_wrapper(Value::Str("chart.trades".into()), Value::Null, &[symbolsAndTimeframes, params]).await;
let mut symbol: Value = get_value(&symboltimeframecandlesVariable, &Value::Int(0));
let mut timeframe: Value = get_value(&symboltimeframecandlesVariable, &Value::Int(1));
let mut candles: Value = get_value(&symboltimeframecandlesVariable, &Value::Int(2));
if is_true(&self.newUpdates) {
limit = candles.get_limit(symbol.clone(), limit.clone());
}
let mut filtered: Value = self.filter_by_since_limit(candles, &[since, limit, Value::Int(0), Value::Bool(true)]);
return self.create_ohlcv_object(symbol, timeframe, filtered);
Value::Null
}
pub fn handle_ohlcv(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "jsonrpc": "2.0",
// "method": "subscription",
// "params": {
// "channel": "chart.trades.BTC_USDC-PERPETUAL.1",
// "data": {
// "volume": 0,
// "tick": 1655403420000,
// "open": 20951,
// "low": 20951,
// "high": 20951,
// "cost": 0,
// "close": 20951
// }
// }
// }
//
let mut params: Value = (match message.get("params") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut channel: Value = self.safe_string_k(params.clone(), "channel", &[Value::Str("".into())]);
let mut parts: Value = split(&channel, &Value::Str(".".into()));
let mut marketId: Value = self.safe_string(parts.clone(), Value::Int(2), &[]);
let mut rawTimeframe: Value = self.safe_string(parts, Value::Int(3), &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut wsOptions: Value = self.safe_dict_k(self.options.clone(), "ws", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timeframes: Value = self.safe_dict_k(wsOptions, "timeframes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut unifiedTimeframe: Value = self.find_timeframe(rawTimeframe.clone(), &[timeframes]);
{ 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); } }
if (self.safe_dict(get_value(&self.ohlcvs, &symbol), unifiedTimeframe.clone(), &[]) == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "OHLCVLimit", &[Value::Int(1000)]);
add_element_to_object(get_value_mut(&mut self.ohlcvs, &symbol), &unifiedTimeframe, ArrayCacheByTimestamp::new(limit));
}
let mut stored: Value = get_value(&get_value(&self.ohlcvs, &symbol), &unifiedTimeframe);
let mut ohlcv: Value = self.safe_dict_k(params, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
// data contains a single OHLCV candle
let mut parsed: Value = self.parse_ws_ohlcv(ohlcv, &[market]);
stored.append(parsed);
add_element_to_object(get_value_mut(&mut self.ohlcvs, &symbol), &unifiedTimeframe, stored.clone());
let mut resolveData: Value = Value::from(vec![symbol.clone(), unifiedTimeframe, stored]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("chart.trades|".into()), symbol).into()), Value::Str("|".into())).into()), rawTimeframe).into());
client.resolve(&[resolveData, messageHash]);
}
pub fn parse_ws_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::from(vec![self.safe_integer_k(ohlcv.clone(), "tick", &[]), self.safe_number_k(ohlcv.clone(), "open", &[]), self.safe_number_k(ohlcv.clone(), "high", &[]), self.safe_number_k(ohlcv.clone(), "low", &[]), self.safe_number_k(ohlcv.clone(), "close", &[]), self.safe_number_k(ohlcv, "volume", &[])]);
Value::Null
}
pub async fn watch_multiple_wrapper(&mut self, mut channelName: Value, mut channelDescriptor: Value, optional_args: &[Value]) -> Value {
let mut symbolsArray = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut rawSubscriptions: Value = Value::from(vec![]);
let mut messageHashes: Value = Value::from(vec![]);
let mut isOHLCV: bool = channelName.as_str() == Some("chart.trades");
let mut symbols: Value = (if isOHLCV { self.get_list_from_object_values(symbolsArray.clone(), Value::Int(0)) } else { symbolsArray.clone() });
self.market_symbols(&[symbols, Value::Null, Value::Bool(false)]);
if (symbolsArray == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchMultipleWrapper() symbolsArray is required".into()))));
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_300: bool = true;
while { if !__for_first_300 { 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_300 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&symbolsArray).as_f64().unwrap_or(f64::NAN) } {
if (symbolsArray == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchMultipleWrapper() symbolsArray is required".into()))));
}
let mut current: Value = get_value(&symbolsArray, &i);
let mut current: Value = get_value(&symbolsArray, &i);
let mut market: Value = Value::Null;
if isOHLCV {
market = self.market(get_value(¤t, &Value::Int(0)));
let mut unifiedTf: Value = get_value(¤t, &Value::Int(1));
let mut rawTf: Value = self.safe_string(self.timeframes.clone(), unifiedTf.clone(), &[unifiedTf.clone()]);
channelDescriptor = rawTf;
} else {
market = self.market(current);
}
let mut message: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", channelName, Value::Str(".".into())).into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str(".".into())).into()), channelDescriptor).into());
append_to_array(&mut rawSubscriptions, message);
append_to_array(&mut messageHashes, Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", channelName, Value::Str("|".into())).into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into()), Value::Str("|".into())).into()), channelDescriptor).into()));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("jsonrpc".to_string(), Value::Str("2.0".into()));
m.insert("method".to_string(), Value::Str("public/subscribe".into()));
m.insert("params".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channels".to_string(), rawSubscriptions.clone());
m
}));
m.insert("id".to_string(), self.request_id());
m
});
let mut extendedRequest: Value = self.deep_extend(request, &[params]);
let mut maxMessageByteLimit: Value = (match (&(Value::Int(32768)), &(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 }); // 'Message Too Big: limit 32768B'
let mut jsonedText: Value = json_stringify(&extendedRequest);
if ((jsonedText.len() as i64) as f64) >= maxMessageByteLimit.as_f64().unwrap_or(f64::NAN) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" requested subscription length over limit, try to reduce symbols amount".into()))));
}
return self.watch_multiple(url, messageHashes, &[extendedRequest, rawSubscriptions]).await;
Value::Null
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// error
// {
// "jsonrpc": "2.0",
// "id": 1,
// "error": {
// "message": "Invalid params",
// "data": {
// "reason": "invalid format",
// "param": "nonce"
// },
// "code": -32602
// },
// "usIn": "1655391709417993",
// "usOut": "1655391709418049",
// "usDiff": 56,
// "testnet": false
// }
//
// subscribe
// {
// "jsonrpc": "2.0",
// "id": 2,
// "result": ["ticker.BTC_USDC-PERPETUAL.raw"],
// "usIn": "1655393625889396",
// "usOut": "1655393625889518",
// "usDiff": 122,
// "testnet": false
// }
//
// notification
// {
// "jsonrpc": "2.0",
// "method": "subscription",
// "params": {
// "channel": "ticker.BTC_USDC-PERPETUAL.raw",
// "data": {
// "timestamp": 1655393724752,
// "stats": [Object],
// "state": "open",
// "settlement_price": 21729.5891,
// "open_interest": 164.501,
// "min_price": 20792.9001,
// "max_price": 21426.1864,
// "mark_price": 21109.4757,
// "last_price": 21132,
// "instrument_name": "BTC_USDC-PERPETUAL",
// "index_price": 21122.3937,
// "funding_8h": -0.00022427,
// "estimated_delivery_price": 21122.3937,
// "current_funding": -0.00011158,
// "best_bid_price": 21106,
// "best_bid_amount": 1.143,
// "best_ask_price": 21113,
// "best_ask_amount": 0.402
// }
// }
// }
//
let mut error: Value = (match __pro_message.get("error").cloned() { Some(Value::Str(__s)) if __s.is_empty() => Value::Null, Some(__v) => __v, None => Value::Null });
if (error != Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), json_stringify(&error))));
}
let mut params: Value = (match __pro_message.get("params").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
let mut channel: Value = self.safe_string_k(params, "channel", &[]);
if (channel != Value::Null) {
let mut parts: Value = split(&channel, &Value::Str(".".into()));
let mut channelId: Value = self.safe_string(parts.clone(), Value::Int(0), &[]);
let mut userHandlers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trades".to_string(), Value::Str("handle_my_trades".into()).clone());
m.insert("portfolio".to_string(), Value::Str("handle_balance".into()).clone());
m.insert("orders".to_string(), Value::Str("handle_orders".into()).clone());
m
});
let mut handlers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("quote".to_string(), Value::Str("handle_bid_ask".into()).clone());
m.insert("book".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("trades".to_string(), Value::Str("handle_trades".into()).clone());
m.insert("chart".to_string(), Value::Str("handle_ohlcv".into()).clone());
m.insert("user".to_string(), self.safe_value(userHandlers, self.safe_string(parts, Value::Int(1), &[]), &[]));
m
});
let mut handler: Value = self.safe_value(handlers, channelId, &[]);
if (handler != Value::Null) {
self.dispatch_ws_handler(&handler, &[client.clone(), message.clone()]);
return;
}
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" no handler found for this message ".into())).into()), json_stringify(&message))));
}
let mut result: Value = (match __pro_message.get("result").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut accessToken: Option<String> = self.safe_string_k(result, "access_token", &[]).as_str().map(str::to_owned);
if (accessToken.is_some()) {
self.handle_authentication_message(client, message);
}
}
pub fn handle_authentication_message(&self, mut client: Value, mut message: Value) -> Value {
//
// {
// "jsonrpc": "2.0",
// "id": 1,
// "result": {
// "token_type": "bearer",
// "scope": "account:read_write block_trade:read_write connection custody:read_write mainaccount name:ccxt trade:read_write wallet:read_write",
// "refresh_token": "1686927372328.1EzFBRmt.logRQWXkPA1oE_Tk0gRsls9Hau7YN6a321XUBnxvR4x6cryhbkKcniUJU-czA8_zKXrqQGpQmfoDwhLIjIsWCvRuu6otbg-LKWlrtTX1GQqLcPaTTHAdZGTMV-HM8HiS03QBd9MIXWRfF53sKj2hdR9nZPZ6MH1XrkpAZPB_peuEEB9wlcc3elzWEZFtCmiy1fnQ8TPHwAJMt3nuUmEcMLt_-F554qrsg_-I66D9xMiifJj4dBemdPfV_PkGPRIwIoKlxDjyv2-xfCw-4eKyo6Hu1m2h6gT1DPOTxSXcBgfBQjpi-_uY3iAIj7U6xjC46PHthEdquhEuCTZl7UfCRZSAWwZA",
// "expires_in": 31536000,
// "access_token": "1686923272328.1CkwEx-u.qHradpIulmuoeboKMEi8PkQ1_4DF8yFE2zywBTtkD32sruVC53b1HwL5OWRuh2nYAndXff4xuXIMRkkEfMAFCeq24prihxxinoS8DDVkKBxedGx4CUPJFeXjmh7wuRGqQOLg1plXOpbF3fwF2KPEkAuETwcpcVY6K9HUVjutNRfxFe2TR7CvuS9x8TATvoPeu7H1ezYl-LkKSaRifdTXuwituXgp4oDbPRyQLniEBWuYF9rY7qbABxuOJlXI1VZ63u7Bh0mGWei-KeVeqHGNpy6OgrFRPXPxa9_U7vaxCyHW3zZ9959TQ1QUMLWtUX-NLBEv3BT5eCieW9HORYIOKfsgkpd3"
// },
// "usIn": "1655391872327712",
// "usOut": "1655391872328515",
// "usDiff": 803,
// "testnet": false
// }
//
let mut messageHash: Value = Value::Str("authenticated".into());
client.resolve(&[message.clone(), messageHash]);
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 = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut client: Value = self.client(&[url.clone()]);
let mut time: Value = self.milliseconds();
let mut timeString: Value = self.number_to_string(time.clone());
let mut nonce: Value = timeString.clone();
let mut messageHash: Value = Value::Str("authenticated".into());
let mut future: Value = self.safe_value(get_value(&client, &Value::Str("subscriptions".into())), messageHash.clone(), &[]);
if (future == Value::Null) {
self.check_required_credentials(&[]);
let mut requestId: Value = self.request_id();
let mut lineBreak: Value = Value::Str("\n".into()); // eslint-disable-line quotes
let mut signature: Value = self.hmac(self.encode(Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", timeString, lineBreak).into()), nonce).into()), lineBreak).into())), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("jsonrpc".to_string(), Value::Str("2.0".into()));
m.insert("id".to_string(), requestId);
m.insert("method".to_string(), Value::Str("public/auth".into()));
m.insert("params".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("grant_type".to_string(), Value::Str("client_signature".into()));
m.insert("client_id".to_string(), self.apiKey.clone());
m.insert("timestamp".to_string(), time);
m.insert("signature".to_string(), signature);
m.insert("nonce".to_string(), nonce);
m.insert("data".to_string(), Value::Str("".into()));
m
}));
m
});
let __ws_arg_0 = self.extend(request, &[params]);
future = self.watch(url, messageHash.clone(), &[__ws_arg_0, messageHash.clone()]).await;
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash, future.clone());
}
return future;
Value::Null
}
}