// 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 LunoCore {
pub parent: crate::exchanges::luno::LunoCore,
}
impl LunoCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::luno::LunoCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = LunoCore::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 LunoCore {
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 {
// Forward to the inherent method on LunoCore.
LunoCore::parse_trade(self, 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 LunoCore {
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 {
"custom_parse_bid_ask" => self.custom_parse_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"custom_parse_order_book" => self.custom_parse_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]),
"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 },
"is_order_book_delta_in_sequence" => self.is_order_book_delta_in_sequence(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)),
"parse_order_book_bids_asks" => self.parse_order_book_bids_asks(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"reduce_order_volume" => self.reduce_order_volume(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)),
"watch_order_book" => self.watch_order_book(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 LunoCore {
/// 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 {
"custom_parse_bid_ask" => self.custom_parse_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"custom_parse_order_book" => self.custom_parse_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]),
"handle_book_delta" => { self.handle_book_delta(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_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_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 },
"is_order_book_delta_in_sequence" => self.is_order_book_delta_in_sequence(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)),
"parse_order_book_bids_asks" => self.parse_order_book_bids_asks(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"reduce_order_volume" => self.reduce_order_volume(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)),
"watch_order_book" => { crate::exchange_stubs::enqueue_spawn("watch_order_book", 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 LunoCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for LunoCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl LunoCore {
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(false));
m.insert("watchTickers".to_string(), Value::Bool(false));
m.insert("watchTrades".to_string(), Value::Bool(true));
m.insert("watchTradesForSymbols".to_string(), Value::Bool(false));
m.insert("watchMyTrades".to_string(), Value::Bool(false));
m.insert("watchOrders".to_string(), Value::Null);
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOHLCV".to_string(), Value::Bool(false));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Str("wss://ws.luno.com/api/1".into()));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sequenceNumbers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
m.insert("streaming".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name luno#watchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://www.luno.com/en/developers/api#tag/Streaming-API
* @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
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut symbolValue: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut subscriptionHash: Value = Value::Str(format!("{}{}", Value::Str("/stream/".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbolValue.clone());
m
});
let mut wsUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), Value::Str("ws".into()), &[]);
if (wsUrl == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" watchTrades() has no websocket url".into()))));
}
let mut url: Value = Value::Str(format!("{}{}", wsUrl, subscriptionHash).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("trades:".into()), symbolValue).into());
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api_key_id".to_string(), self.apiKey.clone());
m.insert("api_key_secret".to_string(), self.secret.clone());
m
});
let mut request: Value = self.deep_extend(subscribe, &[params]);
let mut trades: Value = self.watch(url, messageHash, &[request, subscriptionHash, subscription]).await;
let mut limitResolved: Value = limit.clone();
if is_true(&self.newUpdates) {
limitResolved = trades.get_limit(symbolValue, limit);
}
return self.filter_by_since_limit(trades, &[since, limitResolved, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
pub fn handle_trades(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "sequence": "110980825",
// "trade_updates": [],
// "create_update": {
// "order_id": "BXHSYXAUMH8C2RW",
// "type": "ASK",
// "price": "24081.09000000",
// "volume": "0.07780000"
// },
// "delete_update": null,
// "status_update": null,
// "timestamp": 1660598775360
// }
//
let mut rawTrades: Value = (match message.get("trade_updates") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut length: f64 = ((rawTrades.len() as i64) as f64);
if (length == 0.0) {
return;
}
let mut symbol: Value = subscription.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol.clone());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("trades:".into()), symbol).into());
let mut stored: Value = self.safe_value(self.trades.clone(), symbol.clone(), &[]);
if (stored == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
stored = ArrayCache::new(limit);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), stored.clone()); }
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_465: bool = true;
while { if !__for_first_465 { 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_465 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawTrades.len() as i64) as f64) } {
let mut rawTrade: Value = rawTrades.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 trade: Value = self.parse_trade(rawTrade, &[market.clone()]);
stored.append(trade);
}
}
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), stored); }
client.resolve(&[get_value(&self.trades, &symbol), messageHash]);
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// watchTrades (public)
//
// {
// "base": "69.00000000",
// "counter": "113.6499000000000000",
// "maker_order_id": "BXEEU4S2BWF5WRB",
// "taker_order_id": "BXKNCSF7JDHXY3H",
// "order_id": "BXEEU4S2BWF5WRB"
// }
//
let mut symbol: Value = Value::Null;
if (market == Value::Null) {
symbol = Value::Null;
} else {
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("id".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol);
m.insert("order".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), Value::Null);
m.insert("takerOrMaker".to_string(), Value::Null);
m.insert("price".to_string(), Value::Null);
m.insert("amount".to_string(), self.safe_string_k(trade.clone(), "base", &[]));
m.insert("cost".to_string(), self.safe_string_k(trade, "counter", &[]));
m.insert("fee".to_string(), Value::Null);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name luno#watchOrderBook
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://www.luno.com/en/developers/api#tag/Streaming-API
* @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 {objectConstructor} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] accepts l2 or l3 for level 2 or level 3 order book
* @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
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut symbolValue: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut subscriptionHash: Value = Value::Str(format!("{}{}", Value::Str("/stream/".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbolValue.clone());
m
});
let mut wsUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), Value::Str("ws".into()), &[]);
if (wsUrl == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" watchOrderBook() has no websocket url".into()))));
}
let mut url: Value = Value::Str(format!("{}{}", wsUrl, subscriptionHash).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbolValue).into());
let mut subscribe: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api_key_id".to_string(), self.apiKey.clone());
m.insert("api_key_secret".to_string(), self.secret.clone());
m
});
let mut request: Value = self.deep_extend(subscribe, &[params]);
let mut orderbook: Value = self.watch(url, messageHash, &[request, subscriptionHash, subscription]).await;
return orderbook.limit();
Value::Null
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value, mut subscription: 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;
//
// {
// "sequence": "24352",
// "asks": [{
// "id": "BXMC2CJ7HNB88U4",
// "price": "1234.00",
// "volume": "0.93"
// }],
// "bids": [{
// "id": "BXMC2CJ7HNB88U5",
// "price": "1201.00",
// "volume": "1.22"
// }],
// "status": "ACTIVE",
// "timestamp": 1528884331021
// }
//
// update
// {
// "sequence": "110980825",
// "trade_updates": [],
// "create_update": {
// "order_id": "BXHSYXAUMH8C2RW",
// "type": "ASK",
// "price": "24081.09000000",
// "volume": "0.07780000"
// },
// "delete_update": null,
// "status_update": null,
// "timestamp": 1660598775360
// }
//
let mut symbol: Value = subscription.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbol).into());
let mut timestamp: Value = self.safe_integer_k(message.clone(), "timestamp", &[]);
if !(in_op(&self.orderbooks, &symbol)) {
{ let __be_tmp = self.indexed_order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); 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);
let mut asks: Value = (match __pro_message.get("asks").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::Null });
if (asks == Value::Null) {
let mut inSequence: Value = self.is_order_book_delta_in_sequence(client.clone(), message.clone(), symbol.clone());
if !is_true(&inSequence) {
return;
}
}
if (asks != Value::Null) {
let mut snapshot: Value = self.custom_parse_order_book(message.clone(), symbol, &[timestamp.clone(), Value::Str("bids".into()), Value::Str("asks".into()), Value::Str("price".into()), Value::Str("volume".into()), Value::Str("id".into())]);
orderbook.reset(snapshot);
} else {
self.handle_book_delta(orderbook.clone(), message);
add_element_to_object(&mut orderbook, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut orderbook, &Value::Str("datetime".into()), self.iso8601(timestamp));
}
let mut nonce: Value = (match __pro_message.get("sequence").cloned() { Some(Value::Int(__n)) => Value::Int(__n), Some(Value::Float(__f)) => Value::Int(__f as i64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
add_element_to_object(&mut orderbook, &Value::Str("nonce".into()), nonce);
client.resolve(&[orderbook, messageHash]);
}
pub fn custom_parse_order_book(&self, mut orderbook: Value, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timestamp = get_arg(optional_args, 0, Value::Null);
let mut bidsKey = get_arg(optional_args, 1, Value::Str("bids".into()));
let mut asksKey = get_arg(optional_args, 2, Value::Str("asks".into()));
let mut priceKey = get_arg(optional_args, 3, Value::Str("price".into()));
let mut amountKey = get_arg(optional_args, 4, Value::Str("volume".into()));
let mut countOrIdKey = get_arg(optional_args, 5, Value::Int(2));
let mut bids: Value = self.parse_order_book_bids_asks(self.safe_list(orderbook.clone(), bidsKey, &[Value::from(vec![])]), &[priceKey.clone(), amountKey.clone(), countOrIdKey.clone()]);
let mut asks: Value = self.parse_order_book_bids_asks(self.safe_list(orderbook, asksKey, &[Value::from(vec![])]), &[priceKey, amountKey, countOrIdKey]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("bids".to_string(), self.sort_by(bids, Value::Int(0), &[Value::Bool(true)]));
m.insert("asks".to_string(), self.sort_by(asks, Value::Int(0), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("nonce".to_string(), Value::Null);
m
});
Value::Null
}
pub fn parse_order_book_bids_asks(&self, mut bidasks: Value, optional_args: &[Value]) -> Value {
let mut priceKey = get_arg(optional_args, 0, Value::Str("price".into()));
let mut amountKey = get_arg(optional_args, 1, Value::Str("volume".into()));
let mut thirdKey = get_arg(optional_args, 2, Value::Int(2));
let mut bidasksValue: Value = self.to_array(bidasks);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_466: bool = true;
while { if !__for_first_466 { 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_466 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&bidasksValue).as_f64().unwrap_or(f64::NAN) } {
append_to_array(&mut result, self.custom_parse_bid_ask(get_value(&bidasksValue, &i), &[priceKey.clone(), amountKey.clone(), thirdKey.clone()]));
}
}
return result;
Value::Null
}
pub fn custom_parse_bid_ask(&self, mut bidask: Value, optional_args: &[Value]) -> Value {
let mut priceKey = get_arg(optional_args, 0, Value::Str("price".into()));
let mut amountKey = get_arg(optional_args, 1, Value::Str("volume".into()));
let mut thirdKey = get_arg(optional_args, 2, Value::Int(2));
let mut price: Value = self.safe_number(bidask.clone(), priceKey, &[]);
let mut amount: Value = self.safe_number(bidask.clone(), amountKey, &[]);
let mut result: Value = Value::from(vec![price, amount]);
if (thirdKey != Value::Null) {
let mut thirdValue: Value = self.safe_string(bidask, thirdKey, &[]);
append_to_array(&mut result, thirdValue);
}
return result;
Value::Null
}
pub fn handle_book_delta(&self, mut orderbook: Value, mut message: Value) {
//
// create
// {
// "sequence": "110980825",
// "trade_updates": [],
// "create_update": {
// "order_id": "BXHSYXAUMH8C2RW",
// "type": "ASK",
// "price": "24081.09000000",
// "volume": "0.07780000"
// },
// "delete_update": null,
// "status_update": null,
// "timestamp": 1660598775360
// }
// delete
// {
// "sequence": "110980825",
// "trade_updates": [],
// "create_update": null,
// "delete_update": {
// "order_id": "BXMC2CJ7HNB88U4"
// },
// "status_update": null,
// "timestamp": 1660598775360
// }
// trade
// {
// "sequence": "110980825",
// "trade_updates": [
// {
// "base": "0.1",
// "counter": "5232.00",
// "maker_order_id": "BXMC2CJ7HNB88U4",
// "taker_order_id": "BXMC2CJ7HNB88U5"
// }
// ],
// "create_update": null,
// "delete_update": null,
// "status_update": null,
// "timestamp": 1660598775360
// }
//
let mut asksOrderSide: Value = get_value(&orderbook, &Value::Str("asks".into()));
let mut bidsOrderSide: Value = get_value(&orderbook, &Value::Str("bids".into()));
// trade updates are applied first, matching the ordering of the
// reference luno streaming client
let mut tradeUpdates: Value = self.safe_list_k(message.clone(), "trade_updates", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_467: bool = true;
while { if !__for_first_467 { 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_467 = false; i.as_f64().unwrap_or(f64::NAN) < ((tradeUpdates.len() as i64) as f64) } {
let mut tradeUpdate: Value = tradeUpdates.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 makerOrderId: Value = self.safe_string_k(tradeUpdate.clone(), "maker_order_id", &[]);
let mut tradedAmount: Value = self.safe_string_k(tradeUpdate, "base", &[]);
if (makerOrderId != Value::Null) && (tradedAmount != Value::Null) {
// the message does not carry the side of the maker order and
// order ids are unique across the book, so try the bids first
// and fall back to the asks only on a miss
let mut reduced: Value = self.reduce_order_volume(bidsOrderSide.clone(), makerOrderId.clone(), tradedAmount.clone());
if !is_true(&reduced) {
self.reduce_order_volume(asksOrderSide.clone(), makerOrderId, tradedAmount);
}
}
}
}
let mut createUpdate: Value = self.safe_dict_k(message.clone(), "create_update", &[]);
if (createUpdate != Value::Null) {
let mut bidAskArray: Value = self.custom_parse_bid_ask(createUpdate.clone(), &[Value::Str("price".into()), Value::Str("volume".into()), Value::Str("order_id".into())]);
let mut type_var: Option<String> = self.safe_string_k(createUpdate, "type", &[]).as_str().map(str::to_owned);
if (type_var.as_deref() == Some("ASK")) {
asksOrderSide.store_array(bidAskArray.clone());
} else if (type_var.as_deref() == Some("BID")) {
bidsOrderSide.store_array(bidAskArray);
}
}
let mut deleteUpdate: Value = self.safe_dict_k(message, "delete_update", &[]);
if (deleteUpdate != Value::Null) {
let mut orderId: Value = self.safe_string_k(deleteUpdate, "order_id", &[]);
asksOrderSide.store_array(Value::from(vec![Value::Int(0), Value::Int(0), orderId.clone()]));
bidsOrderSide.store_array(Value::from(vec![Value::Int(0), Value::Int(0), orderId]));
}
}
/*
* @ignore
* @method
* @name luno#reduceOrderVolume
* @description reduces the outstanding volume of the order with the given id inside one side of a level-3 orderbook after a trade, deleting the order when it is fully filled
* @param {object} orderSide the bids or asks side of an indexed orderbook
* @param {string} orderId the exchange-specific id of the maker order that traded
* @param {string} tradedAmount the traded amount in base currency, as a string
* @returns {boolean} true if the order was found in this side, false otherwise
*/
pub fn reduce_order_volume(&self, mut orderSide: Value, mut orderId: Value, mut tradedAmount: Value) -> Value {
let mut sideLength: Value = get_array_length(&orderSide);
{
let mut i: Value = Value::Int(0);
let mut __for_first_468: bool = true;
while { if !__for_first_468 { 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_468 = false; i.as_f64().unwrap_or(f64::NAN) < sideLength.as_f64().unwrap_or(f64::NAN) } {
let mut order: Value = get_value(&orderSide, &i);
let mut order: Value = get_value(&orderSide, &i);
let mut entryId: Value = self.safe_string(order.clone(), Value::Int(2), &[]);
if (entryId.as_str() == orderId.as_str()) {
let mut price: Value = self.safe_number(order.clone(), Value::Int(0), &[]);
let mut currentAmount: Value = self.safe_string(order, Value::Int(1), &[]);
let mut remainingAmount: Value = crate::precise::Precise::stringSub(¤tAmount, &tradedAmount);
if is_true(&crate::precise::Precise::stringLe(&remainingAmount, &Value::Str("0".into()))) {
// fully filled, storing a zero amount deletes the order
orderSide.store_array(Value::from(vec![price.clone(), Value::Int(0), orderId.clone()]));
} else {
orderSide.store_array(Value::from(vec![price, self.parse_number(remainingAmount, &[]), orderId.clone()]));
}
return Value::Bool(true);
}
}
}
return Value::Bool(false);
Value::Null
}
/*
* @ignore
* @method
* @name luno#isOrderBookDeltaInSequence
* @description checks the sequence number of an orderbook delta frame against the stored book, and on a gap tears the connection down so that the next watch call resubscribes and receives a fresh snapshot
* @param {object} client the websocket client the frame arrived on
* @param {object} message the delta frame
* @param {string} symbol unified market symbol of the book
* @returns {boolean} true if the delta can be applied to the stored book, false if it must be discarded
*/
pub fn is_order_book_delta_in_sequence(&mut self, mut client: Value, mut message: Value, mut symbol: Value) -> Value {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
let mut storedNonce: Value = self.safe_integer_k(orderbook.clone(), "nonce", &[]);
if (storedNonce == Value::Null) {
return Value::Bool(false);
}
let mut messageSequence: Value = (match message.get("sequence") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
if (messageSequence == Value::Null) {
return Value::Bool(true);
}
if messageSequence.as_f64().unwrap_or(f64::NAN) <= storedNonce.as_f64().unwrap_or(f64::NAN) {
return Value::Bool(false);
}
let mut expectedSequence: Value = (match (&(storedNonce), &(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 });
if (messageSequence.as_f64() != expectedSequence.as_f64()) {
// a gap in the sequence means a lost message and the book is
// unrecoverable on a live connection, because luno only sends
// a snapshot as the first frame after a fresh handshake:
// reset the client, which stops its keepalive and rejects
// every pending future on the connection, clear the
// subscription so that frames still arriving on the orphaned
// connection are ignored by handleMessage, and drop the
// client, so that the next watch call dials a new connection;
// the cached book is kept so references returned by earlier
// watchOrderBook calls stay live: clearing its nonce discards
// deltas until the fresh snapshot resets the book in place
let mut error = Value::from(crate::exchange_errors::invalid_nonce(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" watchOrderBook() received an out-of-sequence update for ".into())).into()), symbol).into()), Value::Str(", expected ".into())).into()), to_string_val(&expectedSequence)).into()), Value::Str(" but got ".into())).into()), to_string_val(&messageSequence))));
add_element_to_object(&mut orderbook, &Value::Str("nonce".into()), Value::Null);
let mut market: Value = self.market(symbol);
let mut subscriptionHash: Value = Value::Str(format!("{}{}", Value::Str("/stream/".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
if (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &subscriptionHash)) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &subscriptionHash);
}
client.reset(error);
remove(&mut self.clients, &client.as_map().and_then(|__m| __m.get("url")).cloned().unwrap_or(Value::Null));
return Value::Bool(false);
}
return Value::Bool(true);
Value::Null
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
if (message.as_str() == Some("")) {
return;
}
let mut subscriptions: Value = object_values(&get_value(&client, &Value::Str("subscriptions".into())));
let mut subscriptionsLength: f64 = ((subscriptions.len() as i64) as f64);
if (subscriptionsLength == 0.0) {
return;
}
let mut handlers: Value = Value::from(vec![Value::Str("handle_order_book".into()).clone(), Value::Str("handle_trades".into()).clone()]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_469: bool = true;
while { if !__for_first_469 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_469 = false; j.as_f64().unwrap_or(f64::NAN) < ((handlers.len() as i64) as f64) } {
let mut handler: Value = handlers.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
self.dispatch_ws_handler(&handler, &[client.clone(), message.clone(), subscriptions.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null)]);
}
}
}
}