// 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;
pub struct NadoCore {
pub exchange: crate::exchange::Exchange,
}
impl NadoCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { exchange: crate::exchange::Exchange::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = NadoCore::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 NadoCore {
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on NadoCore.
NadoCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on NadoCore.
NadoCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on NadoCore.
NadoCore::parse_order(self, order, &[market])
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on NadoCore.
NadoCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on NadoCore.
NadoCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on NadoCore.
NadoCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on NadoCore.
NadoCore::parse_funding_rate(self, rate, &[market])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on NadoCore.
NadoCore::parse_currency(self, currency)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on NadoCore.
NadoCore::parse_open_interest(self, interest, &[market])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on NadoCore.
NadoCore::parse_transaction(self, transaction, &[currency])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on NadoCore.
NadoCore::sign(self, 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 {
// Forward to the inherent method on NadoCore.
NadoCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for NadoCore {
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 {
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"cancel_all_orders_request" => self.cancel_all_orders_request(&args[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders_request" => self.cancel_orders_request(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"convert_to_x18" => self.convert_to_x18(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_order_request" => self.create_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_subaccount" => self.create_subaccount(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"edit_order_request" => self.edit_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_canceled_and_closed_orders" => self.fetch_canceled_and_closed_orders(&args[..]).await,
"fetch_canceled_orders" => self.fetch_canceled_orders(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_currencies" => self.fetch_currencies(&args[..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_funding_history" => self.fetch_funding_history(&args[..]).await,
"fetch_funding_rate" => self.fetch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_funding_rates" => self.fetch_funding_rates(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interests" => self.fetch_open_interests(&args[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders" => self.fetch_orders(&args[..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_status" => self.fetch_status(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_time" => self.fetch_time(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"is_archive_order_closed" => self.is_archive_order_closed(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"order_verifying_contract" => self.order_verifying_contract(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_currency" => self.parse_currency(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_funding_history" => self.parse_funding_history(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_funding_rate" => self.parse_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_open_interest" => self.parse_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order_time_in_force" => self.parse_order_time_in_force(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ticker" => self.parse_ticker(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())..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_x18" => self.parse_x18(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"query_contracts" => self.query_contracts(&args[..]).await,
"query_transactions_by_event_type" => self.query_transactions_by_event_type(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"remove_market_suffix" => self.remove_market_suffix(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"sign_hash" => self.sign_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for NadoCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for NadoCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl NadoCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.super_describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("nado".into()));
m.insert("name".to_string(), Value::Str("Nado".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("KY".into())]));
m.insert("rateLimit".to_string(), Value::Int(25));
m.insert("version".to_string(), Value::Str("v1".into()));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("dex".to_string(), Value::Bool(true));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(true));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchCanceledAndClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(true));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchFundingHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(true));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("fetchOpenInterests".to_string(), Value::Bool(true));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchStatus".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTime".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("withdraw".to_string(), Value::Bool(false));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/811f4e1a-a8b5-4b9e-84c2-0f88997bd274".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("gateway".to_string(), Value::Str("https://gateway.prod.nado.xyz/v1".into()));
m.insert("gatewayV2".to_string(), Value::Str("https://gateway.prod.nado.xyz/v2".into()));
m.insert("archive".to_string(), Value::Str("https://archive.prod.nado.xyz/v1".into()));
m.insert("archiveV2".to_string(), Value::Str("https://archive.prod.nado.xyz/v2".into()));
m.insert("trigger".to_string(), Value::Str("https://trigger.prod.nado.xyz/v1".into()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("gateway".to_string(), Value::Str("https://gateway.test.nado.xyz/v1".into()));
m.insert("gatewayV2".to_string(), Value::Str("https://gateway.test.nado.xyz/v2".into()));
m.insert("archive".to_string(), Value::Str("https://archive.test.nado.xyz/v1".into()));
m.insert("archiveV2".to_string(), Value::Str("https://archive.test.nado.xyz/v2".into()));
m.insert("trigger".to_string(), Value::Str("https://trigger.test.nado.xyz/v1".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://nado.xyz".into()));
m.insert("doc".to_string(), Value::Str("https://docs.nado.xyz/".into()));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("gateway".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbols".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("query".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("edge/query".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("query".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("edge/query".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("execute".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("gatewayV2".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("pairs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orderbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("archive".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("archiveV2".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("contracts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("symbols".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("trigger".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("execute".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("query".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(false));
m.insert("secret".to_string(), Value::Bool(false));
m.insert("walletAddress".to_string(), Value::Bool(true));
m.insert("privateKey".to_string(), Value::Bool(true));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tierBased".to_string(), Value::Bool(true));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.0001".into()), &[]));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.00035".into()), &[]));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultType".to_string(), Value::Str("swap".into()));
m.insert("recvWindow".to_string(), Value::Int(5000));
m.insert("expiration".to_string(), Value::Str("4294967295".into()));
m.insert("subaccount".to_string(), Value::Str("default".into()));
m.insert("editOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("placeRequiresUnfilled".to_string(), Value::Bool(true));
m
}));
m.insert("builderFee".to_string(), Value::Bool(true));
m.insert("builder".to_string(), Value::Str("4500".into()));
m.insert("feeRate".to_string(), Value::Str("10".into()));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Int(60));
m.insert("5m".to_string(), Value::Int(300));
m.insert("15m".to_string(), Value::Int(900));
m.insert("1h".to_string(), Value::Int(3600));
m.insert("2h".to_string(), Value::Int(7200));
m.insert("4h".to_string(), Value::Int(14400));
m.insert("1d".to_string(), Value::Int(86400));
m.insert("1w".to_string(), Value::Int(604800));
m.insert("4w".to_string(), Value::Int(2419200));
m
}));
m.insert("features".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.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1000".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("1015".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("1001".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("1002".to_string(), Value::Str("RestrictedLocation".into()).clone());
m.insert("1003".to_string(), Value::Str("RestrictedLocation".into()).clone());
m.insert("1004".to_string(), Value::Str("OnMaintenance".into()).clone());
m.insert("1005".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2000".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2001".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2002".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2003".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2004".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2005".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("2006".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("2007".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2008".to_string(), Value::Str("OrderImmediatelyFillable".into()).clone());
m.insert("2009".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2010".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2011".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert("2012".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert("2013".to_string(), Value::Str("DuplicateOrderId".into()).clone());
m.insert("2014".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("2015".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("2016".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("2017".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("2019".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2020".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("2021".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("2022".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert("2023".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("2024".to_string(), Value::Str("InvalidAddress".into()).clone());
m.insert("2025".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("2026".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2027".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2028".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("2029".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2030".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("2031".to_string(), Value::Str("OrderNotFillable".into()).clone());
m.insert("2033".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert("2034".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("2035".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("2036".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("2037".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("2038".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2039".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2040".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2041".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2042".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("2043".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("2044".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("2045".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2046".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2047".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2048".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2049".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("2050".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("2051".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("2052".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2053".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("2054".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2055".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2056".to_string(), Value::Str("OrderNotFillable".into()).clone());
m.insert("2057".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("2058".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("2059".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2060".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("2061".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2062".to_string(), Value::Str("ArgumentsRequired".into()).clone());
m.insert("2063".to_string(), Value::Str("BadResponse".into()).clone());
m.insert("2064".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2065".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2066".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2067".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2068".to_string(), Value::Str("OnMaintenance".into()).clone());
m.insert("2069".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("2070".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("2071".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("2072".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2073".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2074".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2075".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2076".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2077".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2078".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("2079".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2080".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2081".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2082".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("2083".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2084".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2085".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2086".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2087".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("2088".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2089".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2090".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2091".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2092".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("2093".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("2094".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2095".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2096".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("2097".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2098".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2099".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2100".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2101".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2102".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2103".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2104".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2105".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2106".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2107".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2108".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2109".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2110".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2111".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2112".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2113".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2114".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2115".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("2117".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2118".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2119".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2120".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("2121".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("2122".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2123".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("2124".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("2125".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("2126".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("3000".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("3001".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("3002".to_string(), Value::Str("ArgumentsRequired".into()).clone());
m.insert("3003".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("3004".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("3005".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("4000".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("4001".to_string(), Value::Str("NotSupported".into()).clone());
m.insert("4002".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("4003".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("4004".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("5000".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name nado#createOrder
* @description create a trade order
* @see https://docs.nado.xyz/developer-resources/api/gateway/executes/place-order
* @see https://docs.nado.xyz/developer-resources/api/trigger/executes/place-order
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type must be 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @param {string|int} [params.expiration] order expiration timestamp in seconds, defaults to 4294967295
* @param {string|int} [params.appendix] pre-encoded order appendix
* @param {boolean} [params.reduceOnly] true if the order should only reduce position
* @param {boolean} [params.postOnly] true to create a post-only order
* @param {string} [params.timeInForce] 'GTC', 'IOC', 'FOK', or 'PO'
* @param {boolean} [params.spotLeverage] whether leverage should be used for spot, defaults to true, exchange-specific alias params.spot_leverage
* @param {float} [params.triggerPrice] *swap only* The price at which a trigger order is triggered at
* @param {float} [params.stopLossPrice] *swap only* The price at which a stop loss order is triggered at
* @param {float} [params.takeProfitPrice] *swap only* The price at which a take profit order is triggered at
* @param {string} [params.triggerDirection] the direction of the trigger price, 'ascending' or 'descending', also accepts the 'above'/'up' and 'below'/'down' aliases
* @param {int} [params.id] client-provided request id, returned by the exchange in the response
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
pub async fn create_order(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol.clone());
let mut request: Value = self.create_order_request(symbol, type_var, side, amount, &[price, params]).await;
let mut placeOrder: Value = self.safe_dict_k(request.clone(), "place_order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut isTriggerOrder: bool = matches!(&placeOrder, Value::Dict(__d) if __d.contains_key("trigger"));
let mut response: Value = Value::Null;
if isTriggerOrder {
response = self.trigger_private_post_execute(&[request.clone()]).await;
} else {
response = self.gateway_private_post_execute(&[request]).await;
}
let __ws_arg_0 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("place_order".to_string(), placeOrder);
m
}), &[response]);
return self.parse_order(__ws_arg_0, &[market]);
Value::Null
}
/*
* @method
* @ignore
* @name nado#createOrderRequest
* @description build and sign the place_order execute payload
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type must be 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the request payload for the place_order execute
*/
pub async fn create_order_request(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut market: Value = self.market(symbol.clone());
if (type_var.as_str() != Some("limit")) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() supports limit orders only".into()))));
}
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price argument".into()))));
}
let mut productId: Value = self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
let mut priceString: Value = self.price_to_precision(symbol.clone(), price);
let mut amountString: Value = self.amount_to_precision(symbol, amount);
let mut priceX18: Value = self.convert_to_x18(priceString);
let mut amountX18: Value = self.convert_to_x18(amountString);
if (side.as_str() == Some("sell")) {
amountX18 = crate::precise::Precise::stringMul(&amountX18, &Value::Str("-1".into()));
}
let mut subaccountparamsSubaccountVariable = self.handle_option_string_and_params(params, Value::Str("createOrder".into()), Value::Str("subaccount".into()), &[Value::Str("default".into())]);
let mut subaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut expirationparamsExpirationVariable = self.handle_option_string_and_params(paramsSubaccount, Value::Str("createOrder".into()), Value::Str("expiration".into()), &[Value::Str("4294967295".into())]);
let mut expiration: Value = expirationparamsExpirationVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsExpiration: Value = expirationparamsExpirationVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut recvWindowparamsRecvWindowVariable = self.handle_option_integer_and_params(paramsExpiration, Value::Str("createOrder".into()), Value::Str("recvWindow".into()), &[Value::Int(5000)]);
let mut recvWindow: Value = recvWindowparamsRecvWindowVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsRecvWindow: Value = recvWindowparamsRecvWindowVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut nonce: Value = self.create_order_nonce(recvWindow).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut requestId: Value = self.safe_integer_k(paramsRecvWindow.clone(), "id", &[]);
let mut spotLeverage: Value = self.safe_bool2(paramsRecvWindow.clone(), Value::Str("spotLeverage".into()), Value::Str("spot_leverage".into()), &[]);
let mut sender: Value = self.create_subaccount(self.walletAddress.clone(), &[subaccount]);
let mut order: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sender".to_string(), sender);
m.insert("priceX18".to_string(), priceX18);
m.insert("amount".to_string(), amountX18);
m.insert("expiration".to_string(), expiration);
m.insert("nonce".to_string(), nonce);
m
});
let mut placeOrder: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), productId.clone());
m
});
if (requestId != Value::Null) {
if let Value::Dict(__d) = &mut placeOrder { std::sync::Arc::make_mut(__d).insert("id".into(), requestId); }
}
if (spotLeverage != Value::Null) {
if let Value::Dict(__d) = &mut placeOrder { std::sync::Arc::make_mut(__d).insert("spot_leverage".into(), spotLeverage); }
}
let mut isBuy: bool = side.as_str() == Some("buy");
let mut triggerPrice: Value = self.safe_string2(paramsRecvWindow.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut stopLossTriggerPrice: Value = self.safe_string_k(paramsRecvWindow.clone(), "stopLossPrice", &[]);
let mut takeProfitTriggerPrice: Value = self.safe_string_k(paramsRecvWindow.clone(), "takeProfitPrice", &[]);
let mut isStopLossOrder: bool = stopLossTriggerPrice != Value::Null;
let mut isTakeProfitOrder: bool = takeProfitTriggerPrice != Value::Null;
let mut isStopOrder: bool = triggerPrice != Value::Null;
let mut isTriggerOrder: Value = Value::Bool(isStopOrder || isStopLossOrder || isTakeProfitOrder);
if isStopOrder {
// the final omit drops triggerDirection from the request
let mut triggerDirectionAndParams: Value = self.handle_trigger_direction_and_params(paramsRecvWindow.clone(), &[]);
let mut triggerDirection: Value = triggerDirectionAndParams.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut directionSuffix: Value = Value::Str("below".into());
if (triggerDirection.as_str() == Some("ascending")) {
directionSuffix = Value::Str("above".into());
}
let mut triggerPriceX18: Value = self.convert_to_x18(triggerPrice.clone());
let mut priceRequirement: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut priceRequirement, &Value::Str(format!("{}{}", Value::Str("oracle_price_".into()), directionSuffix).into()), triggerPriceX18.clone());
let mut trigger: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("price_trigger".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("price_requirement".to_string(), priceRequirement.clone());
m
}));
m
});
if let Value::Dict(__d) = &mut placeOrder { std::sync::Arc::make_mut(__d).insert("trigger".into(), trigger.clone()); }
} else if isStopLossOrder || isTakeProfitOrder {
let mut oracleSide: Value = Value::Str("".into());
if isBuy {
oracleSide = (if isStopLossOrder { Value::Str("above".into()) } else { Value::Str("below".into()) });
} else {
oracleSide = (if isStopLossOrder { Value::Str("below".into()) } else { Value::Str("above".into()) });
}
if isStopLossOrder {
triggerPrice = stopLossTriggerPrice;
} else {
triggerPrice = takeProfitTriggerPrice;
}
let mut triggerPriceX18: Value = self.convert_to_x18(triggerPrice);
let mut priceRequirement: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut priceRequirement, &Value::Str(format!("{}{}", Value::Str("oracle_price_".into()), oracleSide).into()), triggerPriceX18);
let mut trigger: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("price_trigger".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("price_requirement".to_string(), priceRequirement);
m
}));
m
});
if let Value::Dict(__d) = &mut placeOrder { std::sync::Arc::make_mut(__d).insert("trigger".into(), trigger); }
}
let mut appendix: Value = self.safe_string_k(paramsRecvWindow.clone(), "appendix", &[]);
if (appendix == Value::Null) {
appendix = self.create_order_appendix(isTriggerOrder, &[paramsRecvWindow.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
}
if let Value::Dict(__d) = &mut order { std::sync::Arc::make_mut(__d).insert("appendix".into(), appendix); }
let mut contracts: Value = self.query_contracts(&[]).await;
let mut chainId: Value = self.safe_string_k(contracts, "chain_id", &[]);
let mut signature: Value = self.sign_order(order.clone(), productId, chainId).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut placeOrder { std::sync::Arc::make_mut(__d).insert("order".into(), order); }
if let Value::Dict(__d) = &mut placeOrder { std::sync::Arc::make_mut(__d).insert("signature".into(), signature); }
let mut paramsOmitted: Value = self.omit(paramsRecvWindow, Value::from(vec![Value::Str("expiration".into()), Value::Str("nonce".into()), Value::Str("appendix".into()), Value::Str("reduceOnly".into()), Value::Str("postOnly".into()), Value::Str("timeInForce".into()), Value::Str("id".into()), Value::Str("spotLeverage".into()), Value::Str("spot_leverage".into()), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), Value::Str("triggerDirection".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into())]), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("place_order".to_string(), placeOrder);
m
});
return self.extend(request, &[paramsOmitted]);
Value::Null
}
/*
* @method
* @name nado#editOrder
* @description edit a trade order
* @see https://docs.nado.xyz/developer-resources/api/gateway/executes/cancel-and-place
* @param {string} id order id
* @param {string} symbol unified symbol of the market to edit an order in
* @param {string} type must be 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @param {string|int} [params.expiration] order expiration timestamp in seconds, defaults to 4294967295
* @param {string|int} [params.appendix] pre-encoded order appendix
* @param {boolean} [params.reduceOnly] true if the order should only reduce position
* @param {boolean} [params.postOnly] true to create a post-only order
* @param {string} [params.timeInForce] 'GTC', 'IOC', 'FOK', or 'PO'
* @param {boolean} [params.spotLeverage] whether leverage should be used for spot, defaults to true, exchange-specific alias params.spot_leverage
* @param {boolean} [params.placeRequiresUnfilled] when true, aborts the new order if the canceled order had partial fills or the cancel failed, exchange-specific alias params.place_requires_unfilled, defaults to true
* @param {int} [params.id] client-provided request id, returned by the exchange in the response
* @param {float} [params.triggerPrice] not supported, editing trigger orders throws NotSupported, the same applies to params.stopPrice, params.stopLossPrice and params.takeProfitPrice
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol.clone());
let mut request: Value = self.edit_order_request(id, symbol, type_var, side, &[amount, price, params]).await;
let mut response: Value = self.gateway_private_post_execute(&[request.clone()]).await;
//
// {
// "status": "success",
// "signature": "0x...",
// "data": {
// "digest": "0x..."
// },
// "request_type": "execute_cancel_and_place"
// }
//
let mut cancelAndPlace: Value = self.safe_dict_k(request, "cancel_and_place", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut placeOrder: Value = self.safe_dict_k(cancelAndPlace, "place_order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let __ws_arg_1 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("place_order".to_string(), placeOrder);
m
}), &[response]);
return self.parse_order(__ws_arg_1, &[market]);
Value::Null
}
/*
* @method
* @ignore
* @name nado#editOrderRequest
* @description build and sign the cancel_and_place execute payload
* @param {string} id order id
* @param {string} symbol unified symbol of the market to edit an order in
* @param {string} type must be 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the request payload for the cancel_and_place execute
*/
pub async fn edit_order_request(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut market: Value = self.market(symbol.clone());
if (type_var.as_str() != Some("limit")) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" editOrder() supports limit orders only".into()))));
}
let mut triggerPrice: Option<String> = self.safe_string_n(params.clone(), Value::from(vec![Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into())]), &[]).as_str().map(str::to_owned);
if (triggerPrice.is_some()) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" editOrder() and editOrderWs() do not support trigger orders, cancel the trigger order and create a new one instead".into()))));
}
if (amount == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires an amount argument".into()))));
}
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires a price argument".into()))));
}
let mut productId: Value = self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
let mut priceString: Value = self.price_to_precision(symbol.clone(), price);
let mut amountString: Value = self.amount_to_precision(symbol, amount);
let mut priceX18: Value = self.convert_to_x18(priceString);
let mut amountX18: Value = self.convert_to_x18(amountString);
if (side.as_str() == Some("sell")) {
amountX18 = crate::precise::Precise::stringMul(&amountX18, &Value::Str("-1".into()));
}
let mut editOrderOptions: Value = self.safe_dict_k(self.options.clone(), "editOrder", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut subaccountparamsSubaccountVariable = self.handle_option_string_and_params(params, Value::Str("editOrder".into()), Value::Str("subaccount".into()), &[Value::Str("default".into())]);
let mut subaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut expirationparamsExpirationVariable = self.handle_option_string_and_params(paramsSubaccount, Value::Str("editOrder".into()), Value::Str("expiration".into()), &[Value::Str("4294967295".into())]);
let mut expiration: Value = expirationparamsExpirationVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsExpiration: Value = expirationparamsExpirationVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut recvWindowparamsRecvWindowVariable = self.handle_option_integer_and_params(paramsExpiration, Value::Str("editOrder".into()), Value::Str("recvWindow".into()), &[Value::Int(5000)]);
let mut recvWindow: Value = recvWindowparamsRecvWindowVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsRecvWindow: Value = recvWindowparamsRecvWindowVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut cancelNonce: Value = self.create_order_nonce(recvWindow).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut orderNonce: Value = crate::precise::Precise::stringAdd(&cancelNonce, &Value::Str("1".into()));
let mut appendix: Value = self.safe_string_k(paramsRecvWindow.clone(), "appendix", &[]);
if (appendix == Value::Null) {
appendix = self.create_order_appendix(Value::Bool(false), &[paramsRecvWindow.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
}
let mut requestId: Value = self.safe_integer_k(paramsRecvWindow.clone(), "id", &[]);
let mut spotLeverage: Value = self.safe_bool2(paramsRecvWindow.clone(), Value::Str("spotLeverage".into()), Value::Str("spot_leverage".into()), &[]);
let mut placeRequiresUnfilled: Value = self.safe_bool2(paramsRecvWindow.clone(), Value::Str("placeRequiresUnfilled".into()), Value::Str("place_requires_unfilled".into()), &[self.safe_bool_k(editOrderOptions, "placeRequiresUnfilled", &[Value::Bool(true)])]);
let mut paramsOmitted: Value = self.omit(paramsRecvWindow, Value::from(vec![Value::Str("expiration".into()), Value::Str("nonce".into()), Value::Str("appendix".into()), Value::Str("reduceOnly".into()), Value::Str("postOnly".into()), Value::Str("timeInForce".into()), Value::Str("id".into()), Value::Str("spotLeverage".into()), Value::Str("spot_leverage".into()), Value::Str("placeRequiresUnfilled".into()), Value::Str("place_requires_unfilled".into())]), &[]);
let mut sender: Value = self.create_subaccount(self.walletAddress.clone(), &[subaccount]);
let mut cancelTx: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sender".to_string(), sender.clone());
m.insert("productIds".to_string(), Value::from(vec![productId.clone()]));
m.insert("digests".to_string(), Value::from(vec![id.clone()]));
m.insert("nonce".to_string(), cancelNonce);
m
});
let mut order: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sender".to_string(), sender);
m.insert("priceX18".to_string(), priceX18);
m.insert("amount".to_string(), amountX18);
m.insert("expiration".to_string(), expiration);
m.insert("nonce".to_string(), orderNonce);
m.insert("appendix".to_string(), appendix);
m
});
let mut contracts: Value = self.query_contracts(&[]).await;
let mut chainId: Value = self.safe_string_k(contracts.clone(), "chain_id", &[]);
let mut endpointAddress: Value = self.safe_string_k(contracts, "endpoint_addr", &[]);
if (endpointAddress == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires endpoint_addr from contracts query".into()))));
}
let mut cancelSignature: Value = self.sign_cancellation(cancelTx.clone(), chainId.clone(), endpointAddress).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut orderSignature: Value = self.sign_order(order.clone(), productId.clone(), chainId).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut placeOrder: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), productId);
m.insert("order".to_string(), order);
m.insert("signature".to_string(), orderSignature);
m
});
if (requestId != Value::Null) {
if let Value::Dict(__d) = &mut placeOrder { std::sync::Arc::make_mut(__d).insert("id".into(), requestId); }
}
if (spotLeverage != Value::Null) {
if let Value::Dict(__d) = &mut placeOrder { std::sync::Arc::make_mut(__d).insert("spot_leverage".into(), spotLeverage); }
}
let mut cancelAndPlace: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cancel_tx".to_string(), cancelTx);
m.insert("cancel_signature".to_string(), cancelSignature);
m.insert("place_order".to_string(), placeOrder);
m.insert("place_requires_unfilled".to_string(), placeRequiresUnfilled);
m
});
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cancel_and_place".to_string(), cancelAndPlace);
m
});
return self.extend(request, &[paramsOmitted]);
Value::Null
}
/*
* @method
* @name nado#cancelOrder
* @description cancels an open order
* @see https://docs.nado.xyz/developer-resources/api/gateway/executes/cancel-orders
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @param {string} [params.requiredUnfilledAmount] cancel only if the order's absolute remaining unfilled amount matches this amount, exchange-specific raw x18 alias params.required_unfilled_amount
* @param {int} [params.id] client-provided request id, returned by the exchange in the response
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut orders: Value = self.cancel_orders(Value::from(vec![id]), &[symbol, params]).await;
let mut canceled: Value = self.safe_dict(orders, Value::Int(0), &[]);
return canceled;
Value::Null
}
/*
* @method
* @name nado#cancelAllOrders
* @description cancel all open orders
* @see https://docs.nado.xyz/developer-resources/api/gateway/executes/cancel-product-orders
* @param {string} [symbol] unified market symbol, when undefined all orders for all products are canceled
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @param {int} [params.id] client-provided request id, returned by the exchange in the response
* @param {boolean} [params.trigger] set to true if you would like to fetch portfolio margin account trigger or conditional orders
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_all_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
self.load_markets(&[]).await;
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut trigger: Value = self.safe_bool2(params.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("stop".into()), Value::Str("trigger".into())]), &[]);
let mut request: Value = self.cancel_all_orders_request(&[symbol, paramsOmitted]).await;
let mut response: Value = Value::Null;
if (trigger.as_bool() == Some(true)) {
response = self.trigger_private_post_execute(&[request.clone()]).await;
} else {
response = self.gateway_private_post_execute(&[request]).await;
}
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut cancelledOrders: Value = self.safe_list_k(data, "cancelled_orders", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_970: bool = true;
while { if !__for_first_970 { 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_970 = false; i.as_f64().unwrap_or(f64::NAN) < ((cancelledOrders.len() as i64) as f64) } {
let __ws_arg_2 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("canceled".into()));
m
}), &[cancelledOrders.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 result, self.parse_order(__ws_arg_2, &[market.clone()]));
}
}
return result;
Value::Null
}
/*
* @method
* @ignore
* @name nado#cancelAllOrdersRequest
* @description build and sign the cancel_product_orders execute payload
* @param {string} [symbol] unified market symbol, when undefined all orders for all products are canceled
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the request payload for the cancel_product_orders execute
*/
pub async fn cancel_all_orders_request(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut productIds: Value = Value::from(vec![]);
if (symbol != Value::Null) {
let mut market: Value = self.market(symbol);
append_to_array(&mut productIds, self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
}
let mut subaccountparamsSubaccountVariable = self.handle_option_string_and_params(params, Value::Str("cancelAllOrders".into()), Value::Str("subaccount".into()), &[Value::Str("default".into())]);
let mut subaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut sender: Value = self.create_subaccount(self.walletAddress.clone(), &[subaccount]);
let mut recvWindowparamsRecvWindowVariable = self.handle_option_integer_and_params(paramsSubaccount, Value::Str("cancelAllOrders".into()), Value::Str("recvWindow".into()), &[Value::Int(5000)]);
let mut recvWindow: Value = recvWindowparamsRecvWindowVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsRecvWindow: Value = recvWindowparamsRecvWindowVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut nonce: Value = self.create_order_nonce(recvWindow).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut tx: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sender".to_string(), sender);
m.insert("productIds".to_string(), productIds);
m.insert("nonce".to_string(), nonce);
m
});
let mut contracts: Value = self.query_contracts(&[]).await;
let mut chainId: Value = self.safe_string_k(contracts.clone(), "chain_id", &[]);
let mut endpointAddress: Value = self.safe_string_k(contracts, "endpoint_addr", &[]);
if (endpointAddress == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" cancelAllOrders() requires endpoint_addr from contracts query".into()))));
}
let mut signature: Value = self.sign_cancellation_products(tx.clone(), chainId, endpointAddress).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut requestId: Value = self.safe_integer_k(paramsRecvWindow.clone(), "id", &[]);
let mut paramsOmitted: Value = self.omit(paramsRecvWindow, Value::from(vec![Value::Str("id".into())]), &[]);
let mut cancelProductOrders: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx".to_string(), tx);
m.insert("signature".to_string(), signature);
m
});
if (requestId != Value::Null) {
if let Value::Dict(__d) = &mut cancelProductOrders { std::sync::Arc::make_mut(__d).insert("id".into(), requestId); }
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cancel_product_orders".to_string(), cancelProductOrders);
m
});
return self.extend(request, &[paramsOmitted]);
Value::Null
}
/*
* @method
* @name nado#cancelOrders
* @description cancel multiple orders
* @see https://docs.nado.xyz/developer-resources/api/gateway/executes/cancel-orders
* @param {string[]} ids order ids
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @param {string} [params.requiredUnfilledAmount] cancel only if the order's absolute remaining unfilled amount matches this amount, exchange-specific raw x18 alias params.required_unfilled_amount
* @param {int} [params.id] client-provided request id, returned by the exchange in the response
* @param {boolean} [params.trigger] set to true if you would like to fetch portfolio margin account trigger or conditional orders
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() requires a symbol argument".into()))));
}
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol.clone());
let mut trigger: Value = self.safe_bool2(params.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("stop".into()), Value::Str("trigger".into())]), &[]);
let mut request: Value = self.cancel_orders_request(ids, &[symbol, paramsOmitted]).await;
let mut response: Value = Value::Null;
if (trigger.as_bool() == Some(true)) {
response = self.trigger_private_post_execute(&[request.clone()]).await;
} else {
response = self.gateway_private_post_execute(&[request]).await;
}
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut cancelledOrders: Value = self.safe_list_k(data, "cancelled_orders", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_971: bool = true;
while { if !__for_first_971 { 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_971 = false; i.as_f64().unwrap_or(f64::NAN) < ((cancelledOrders.len() as i64) as f64) } {
let __ws_arg_3 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("canceled".into()));
m
}), &[cancelledOrders.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 result, self.parse_order(__ws_arg_3, &[market.clone()]));
}
}
return result;
Value::Null
}
/*
* @method
* @ignore
* @name nado#cancelOrdersRequest
* @description build and sign the cancel_orders execute payload
* @param {string[]} ids order ids
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the request payload for the cancel_orders execute
*/
pub async fn cancel_orders_request(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut market: Value = self.market(symbol);
let mut productId: Value = self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
let mut subaccountparamsSubaccountVariable = self.handle_option_string_and_params(params, Value::Str("cancelOrders".into()), Value::Str("subaccount".into()), &[Value::Str("default".into())]);
let mut subaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut sender: Value = self.create_subaccount(self.walletAddress.clone(), &[subaccount]);
let mut productIds: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_972: bool = true;
while { if !__for_first_972 { 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_972 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
append_to_array(&mut productIds, productId.clone());
}
}
let mut recvWindowparamsRecvWindowVariable = self.handle_option_integer_and_params(paramsSubaccount, Value::Str("cancelOrders".into()), Value::Str("recvWindow".into()), &[Value::Int(5000)]);
let mut recvWindow: Value = recvWindowparamsRecvWindowVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsRecvWindow: Value = recvWindowparamsRecvWindowVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut nonce: Value = self.create_order_nonce(recvWindow).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut tx: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sender".to_string(), sender);
m.insert("productIds".to_string(), productIds);
m.insert("digests".to_string(), ids);
m.insert("nonce".to_string(), nonce);
m
});
let mut contracts: Value = self.query_contracts(&[]).await;
let mut chainId: Value = self.safe_string_k(contracts.clone(), "chain_id", &[]);
let mut endpointAddress: Value = self.safe_string_k(contracts, "endpoint_addr", &[]);
if (endpointAddress == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() requires endpoint_addr from contracts query".into()))));
}
let mut signature: Value = self.sign_cancellation(tx.clone(), chainId, endpointAddress).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut requestId: Value = self.safe_integer_k(paramsRecvWindow.clone(), "id", &[]);
let mut requiredUnfilledAmountRaw: Value = self.safe_string_k(paramsRecvWindow.clone(), "required_unfilled_amount", &[]);
let mut requiredUnfilledAmount: Value = self.safe_string_k(paramsRecvWindow.clone(), "requiredUnfilledAmount", &[]);
let mut paramsOmitted: Value = self.omit(paramsRecvWindow, Value::from(vec![Value::Str("id".into()), Value::Str("requiredUnfilledAmount".into()), Value::Str("required_unfilled_amount".into())]), &[]);
let mut cancelOrders: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx".to_string(), tx);
m.insert("signature".to_string(), signature);
m
});
if (requiredUnfilledAmountRaw != Value::Null) {
if let Value::Dict(__d) = &mut cancelOrders { std::sync::Arc::make_mut(__d).insert("required_unfilled_amount".into(), requiredUnfilledAmountRaw); }
} else if (requiredUnfilledAmount != Value::Null) {
if let Value::Dict(__d) = &mut cancelOrders { std::sync::Arc::make_mut(__d).insert("required_unfilled_amount".into(), self.convert_to_x18(requiredUnfilledAmount)); }
}
if (requestId != Value::Null) {
if let Value::Dict(__d) = &mut cancelOrders { std::sync::Arc::make_mut(__d).insert("id".into(), requestId); }
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cancel_orders".to_string(), cancelOrders);
m
});
return self.extend(request, &[paramsOmitted]);
Value::Null
}
/*
* @method
* @name nado#fetchOrder
* @description fetches information on an order made by the user
* @see https://docs.nado.xyz/developer-resources/api/gateway/queries/order
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOrder() requires a symbol argument".into()))));
}
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("order".into()));
m.insert("product_id".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m.insert("digest".to_string(), id);
m
});
let __ws_arg_4 = self.extend(request, &[params]);
let mut response: Value = self.gateway_public_get_query(&[__ws_arg_4]).await;
//
// {
// "status": "success",
// "data": {
// "product_id": 1,
// "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43000000000000000000000000",
// "price_x18": "1000000000000000000",
// "amount": "1000000000000000000",
// "expiration": "2000000000",
// "nonce": "1",
// "unfilled_amount": "1000000000000000000",
// "digest": "0x0000000000000000000000000000000000000000000000000000000000000000",
// "placed_at": 1681951347,
// "appendix": "1537",
// "order_type": "ioc"
// },
// "request_type": "query_order"
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(data, &[market]);
Value::Null
}
/*
* @method
* @name nado#fetchOrders
* @description fetches information on multiple orders made by the user
* @see https://docs.nado.xyz/developer-resources/api/archive-indexer/orders
* @see https://docs.nado.xyz/developer-resources/api/trigger/queries/list-trigger-orders
* @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, max 500
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.trigger] set to true if you would like to fetch portfolio margin account trigger or conditional orders
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_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
}));
self.load_markets(&[]).await;
let mut productIds: Value = Value::from(vec![]);
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
append_to_array(&mut productIds, self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
}
let mut subaccountparamsSubaccountVariable = self.handle_option_string_and_params(params, Value::Str("fetchOrders".into()), Value::Str("subaccount".into()), &[Value::Str("default".into())]);
let mut subaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut sender: Value = self.create_subaccount(self.walletAddress.clone(), &[subaccount]);
let mut trigger: Value = self.safe_bool2(paramsSubaccount.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
let mut paramsOmitted: Value = self.omit(paramsSubaccount, Value::from(vec![Value::Str("stop".into()), Value::Str("trigger".into())]), &[]);
if (trigger.as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOrders only support trigger".into()))));
}
let mut recvWindowparamsRecvWindowVariable = self.handle_option_integer_and_params(paramsOmitted, Value::Str("fetchOrders".into()), Value::Str("recvWindow".into()), &[Value::Int(5000)]);
let mut recvWindow: Value = recvWindowparamsRecvWindowVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsRecvWindow: Value = recvWindowparamsRecvWindowVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut tx: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sender".to_string(), sender);
m.insert("recvTime".to_string(), self.number_to_string((match (&(self.milliseconds()), &(recvWindow)) { (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 })));
m
});
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx".to_string(), tx.clone());
m.insert("type".to_string(), Value::Str("list_trigger_orders".into()));
m.insert("product_ids".to_string(), productIds);
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(500))); }
}
let mut contracts: Value = self.query_contracts(&[]).await;
let mut chainId: Value = self.safe_string_k(contracts.clone(), "chain_id", &[]);
let mut endpointAddress: Value = self.safe_string_k(contracts, "endpoint_addr", &[]);
let mut signature: Value = self.sign_fetch_trigger_orders(tx, chainId, endpointAddress).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("signature".into(), signature); }
let __ws_arg_5 = self.extend(request, &[paramsRecvWindow]);
let mut response: Value = self.trigger_private_post_query(&[__ws_arg_5]).await;
//
// {
// "status": "success",
// "data": {
// "orders": [{
// "order": {
// "order": {
// "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43000000000000000000000000",
// "priceX18": "1000000000000000000",
// "amount": "1000000000000000000",
// "expiration": "2000000000",
// "nonce": "1",
// },
// "signature": "0x...",
// "product_id": 1,
// "spot_leverage": true,
// "trigger": {
// "price_above": "1000000000000000000"
// },
// "digest": "0x..."
// },
// "status": "pending",
// "placed_at": 1688768157000,
// "updated_at": 1688768157050
// }]
// },
// "request_type": "query_list_trigger_orders"
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orders: Value = self.safe_list_k(data, "orders", &[Value::from(vec![])]);
return self.parse_orders(orders, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name nado#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://docs.nado.xyz/developer-resources/api/gateway/queries/orders
* @see https://docs.nado.xyz/developer-resources/api/trigger/queries/list-trigger-orders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @param {boolean} [params.trigger] whether the order is a trigger order
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_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.walletAddress.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenOrders() requires walletAddress".into()))));
}
self.load_markets(&[]).await;
let mut subaccountparamsSubaccountVariable = self.handle_option_string_and_params(params, Value::Str("fetchOpenOrders".into()), Value::Str("subaccount".into()), &[Value::Str("default".into())]);
let mut subaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut sender: Value = self.create_subaccount(self.walletAddress.clone(), &[subaccount]);
let mut trigger: Value = self.safe_bool2(paramsSubaccount.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
if (trigger.as_bool() == Some(true)) {
let __ws_arg_6 = self.extend(paramsSubaccount.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status_types".to_string(), Value::from(vec![Value::Str("waiting_price".into()), Value::Str("waiting_dependency".into())]));
m
})]);
return self.fetch_orders(&[symbol.clone(), since.clone(), limit.clone(), __ws_arg_6]).await;
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenOrders() requires a symbol argument".into()))));
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sender".to_string(), sender);
m.insert("type".to_string(), Value::Str("subaccount_orders".into()));
m.insert("product_id".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m
});
let __ws_arg_7 = self.extend(request, &[paramsSubaccount]);
let mut response: Value = self.gateway_public_get_query(&[__ws_arg_7]).await;
//
// single product
//
// {
// "status": "success",
// "data": {
// "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43000000000000000000000000",
// "product_id": 1,
// "orders": [
// {
// "product_id": 1,
// "sender": "0x7a5ec2748e9065794491a8d29dcf3f9edb8d7c43000000000000000000000000",
// "price_x18": "1000000000000000000",
// "amount": "1000000000000000000",
// "expiration": "2000000000",
// "nonce": "1",
// "unfilled_amount": "1000000000000000000",
// "digest": "0x0000000000000000000000000000000000000000000000000000000000000000",
// "placed_at": 1682437739,
// "appendix": "1537",
// "order_type": "ioc"
// }
// ]
// },
// "request_type": "query_subaccount_orders"
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orders: Value = self.safe_list_k(data, "orders", &[Value::from(vec![])]);
return self.parse_orders(orders, &[market, since, limit, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("open".into()));
m
})]);
Value::Null
}
/*
* @method
* @name nado#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://docs.nado.xyz/developer-resources/api/archive-indexer/orders
* @see https://docs.nado.xyz/developer-resources/api/trigger/queries/list-trigger-orders
* @param {string} [symbol] unified market symbol of the market orders were made in
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the maximum number of orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @param {int} [params.until] timestamp in ms of the latest order to fetch
* @param {boolean} [params.trigger] whether the order is a trigger order
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
pub async fn fetch_closed_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.walletAddress.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchClosedOrders() requires walletAddress".into()))));
}
self.load_markets(&[]).await;
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut subaccountparamsSubaccountVariable = self.handle_option_string_and_params(params, Value::Str("fetchClosedOrders".into()), Value::Str("subaccount".into()), &[Value::Str("default".into())]);
let mut subaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut sender: Value = self.create_subaccount(self.walletAddress.clone(), &[subaccount]);
let mut trigger: Value = self.safe_bool2(paramsSubaccount.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
if (trigger.as_bool() == Some(true)) {
let __ws_arg_8 = self.extend(paramsSubaccount.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status_types".to_string(), Value::from(vec![Value::Str("triggered".into()), Value::Str("triggering".into()), Value::Str("twap_executing".into()), Value::Str("twap_completed".into())]));
m
})]);
return self.fetch_orders(&[symbol, since.clone(), limit.clone(), __ws_arg_8]).await;
}
let mut ordersRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("subaccounts".to_string(), Value::from(vec![sender]));
m
});
if (market != Value::Null) {
if let Value::Dict(__d) = &mut ordersRequest { std::sync::Arc::make_mut(__d).insert("product_ids".into(), Value::from(vec![self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null))])); }
}
let mut ordersRequestUntilparamsUntilVariable = self.handle_until_option(Value::Str("max_time".into()), ordersRequest, paramsSubaccount, &[Value::Float(0.001)]);
let mut ordersRequestUntil: Value = ordersRequestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = ordersRequestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (limit != Value::Null) {
add_element_to_object(&mut ordersRequestUntil, &Value::Str("limit".into()), crate::runtime::Math::min(&limit, &Value::Int(500)));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orders".to_string(), ordersRequestUntil);
m
});
let mut response: Value = self.archive_post(&[self.deep_extend(request, &[paramsUntil])]).await;
//
// {
// "orders": [
// {
// "digest": "0xf4f7a8767faf0c7f72251a1f9e5da590f708fd9842bf8fcdeacbaa0237958fff",
// "subaccount": "0x12a0b4888021576eb10a67616dd3dd3d9ce206b664656661756c740000000000",
// "product_id": 1,
// "submission_idx": "563024",
// "amount": "20000000000000000000",
// "price_x18": "1751900000000000000000",
// "base_filled": "20000000000000000000",
// "quote_filled": "-35038000000000000000000",
// "fee": "7007600000000000000",
// "first_fill_timestamp": "1679728133",
// "last_fill_timestamp": "1679728133"
// }
// ]
// }
//
let mut closedOrders: Value = Value::from(vec![]);
let mut orders: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_973: bool = true;
while { if !__for_first_973 { 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_973 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut order: Value = 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);
if is_true(&self.is_archive_order_closed(order.clone())) {
append_to_array(&mut closedOrders, self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("closed".into()));
m
}), &[order]));
}
}
}
return self.parse_orders(closedOrders, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name nado#fetchCanceledOrders
* @description fetches information on multiple canceled trigger orders made by the user, the exchange keeps canceled-order history for trigger orders only
* @see https://docs.nado.xyz/developer-resources/api/trigger/queries/list-trigger-orders
* @param {string} symbol unified market symbol of the market the 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, max 500
* @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 fetch_canceled_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
}));
let __ws_arg_9 = self.extend(params, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trigger".to_string(), Value::Bool(true));
m.insert("status_types".to_string(), Value::from(vec![Value::Str("cancelled".into()), Value::Str("internal_error".into())]));
m
})]);
return self.fetch_orders(&[symbol, since, limit, __ws_arg_9]).await;
Value::Null
}
/*
* @method
* @name nado#fetchCanceledAndClosedOrders
* @description fetches information on multiple canceled and closed trigger orders made by the user, the exchange keeps canceled-order history for trigger orders only
* @see https://docs.nado.xyz/developer-resources/api/trigger/queries/list-trigger-orders
* @param {string} symbol unified market symbol of the market the 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, max 500
* @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 fetch_canceled_and_closed_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
}));
let __ws_arg_10 = self.extend(params, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trigger".to_string(), Value::Bool(true));
m.insert("status_types".to_string(), Value::from(vec![Value::Str("cancelled".into()), Value::Str("internal_error".into()), Value::Str("triggered".into()), Value::Str("triggering".into()), Value::Str("twap_executing".into()), Value::Str("twap_completed".into())]));
m
})]);
return self.fetch_orders(&[symbol, since, limit, __ws_arg_10]).await;
Value::Null
}
/*
* @method
* @name nado#fetchMyTrades
* @description fetch all trades made by the user
* @see https://docs.nado.xyz/developer-resources/api/archive-indexer/matches
* @param {string} [symbol] unified market symbol
* @param {int} [since] timestamp in ms of the earliest trade
* @param {int} [limit] the maximum number of trades to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @param {int} [params.until] timestamp in ms of the latest trade to fetch
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure}
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.walletAddress.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchMyTrades() requires walletAddress".into()))));
}
self.load_markets(&[]).await;
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut subaccountparamsSubaccountVariable = self.handle_option_string_and_params(params, Value::Str("fetchMyTrades".into()), Value::Str("subaccount".into()), &[Value::Str("default".into())]);
let mut subaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut matchesRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("subaccounts".to_string(), Value::from(vec![self.create_subaccount(self.walletAddress.clone(), &[subaccount])]));
m
});
if (market != Value::Null) {
if let Value::Dict(__d) = &mut matchesRequest { std::sync::Arc::make_mut(__d).insert("product_ids".into(), Value::from(vec![self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null))])); }
}
let mut matchesRequestUntilparamsUntilVariable = self.handle_until_option(Value::Str("max_time".into()), matchesRequest, paramsSubaccount, &[Value::Float(0.001)]);
let mut matchesRequestUntil: Value = matchesRequestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = matchesRequestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (limit != Value::Null) {
add_element_to_object(&mut matchesRequestUntil, &Value::Str("limit".into()), crate::runtime::Math::min(&limit, &Value::Int(500)));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("matches".to_string(), matchesRequestUntil);
m
});
let mut response: Value = self.archive_post(&[self.deep_extend(request, &[paramsUntil])]).await;
//
// {
// "matches": [
// {
// "digest": "0x80ce789702b670b7d33f2aa67e12c85f124395c3f9acdb422dde3b4973ccd50c",
// "order": {
// "sender": "0x12a0b4888021576eb10a67616dd3dd3d9ce206b664656661756c740000000000",
// "priceX18": "27544000000000000000000",
// "amount": "2000000000000000000",
// "expiration": "4611686020107119633",
// "nonce": "1761322608857448448"
// },
// "base_filled": "736000000000000000",
// "quote_filled": "-20276464287857571514302",
// "fee": "4055287857571514302",
// "submission_idx": "563012",
// "is_taker": true
// }
// ],
// "txs": [
// {
// "submission_idx": "563012",
// "product_id": 2,
// "timestamp": "1679728133"
// }
// ]
// }
//
let mut matches: Value = self.safe_list_k(response.clone(), "matches", &[Value::from(vec![])]);
let mut txs: Value = self.safe_list_k(response, "txs", &[Value::from(vec![])]);
let mut txsBySubmission: Value = self.index_by(txs, Value::Str("submission_idx".into()));
let mut trades: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_974: bool = true;
while { if !__for_first_974 { 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_974 = false; i.as_f64().unwrap_or(f64::NAN) < ((matches.len() as i64) as f64) } {
let mut match_val: Value = matches.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 submissionIdx: Value = self.safe_string_k(match_val.clone(), "submission_idx", &[]);
let mut tx: Value = self.safe_dict(txsBySubmission.clone(), submissionIdx, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
append_to_array(&mut trades, self.extend(tx, &[match_val]));
}
}
return self.parse_trades(trades, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name nado#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://docs.nado.xyz/developer-resources/api/gateway/queries/subaccount-info
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.walletAddress.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchBalance() requires walletAddress".into()))));
}
self.load_markets(&[]).await;
let mut subaccountparamsSubaccountVariable = self.handle_option_string_and_params(params, Value::Str("fetchBalance".into()), Value::Str("subaccount".into()), &[Value::Str("default".into())]);
let mut subaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("subaccount_info".into()));
m.insert("subaccount".to_string(), self.create_subaccount(self.walletAddress.clone(), &[subaccount]));
m
});
let __ws_arg_11 = self.extend(request, &[paramsSubaccount]);
let mut response: Value = self.gateway_public_get_query(&[__ws_arg_11]).await;
//
// {
// "status": "success",
// "data": {
// "subaccount": "0x8d7d64d6cf1d4f018dd101482ac71ad49e30c56064656661756c740000000000",
// "exists": true,
// "spot_balances": [
// {
// "product_id": 0,
// "balance": {
// "amount": "456895621098158389211471"
// }
// }
// ],
// "perp_balances": []
// },
// "request_type": "query_subaccount_info"
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_balance(data);
Value::Null
}
/*
* @method
* @name nado#fetchDeposits
* @description fetch all deposits made to an account
* @see https://docs.nado.xyz/developer-resources/api/archive-indexer/events
* @param {string} [code] unified currency code
* @param {int} [since] the earliest time in ms to fetch deposits for
* @param {int} [limit] the maximum number of deposits structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @param {int} [params.until] timestamp in ms of the latest deposit to fetch
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/#/?id=transaction-structure}
*/
pub async fn fetch_deposits(&mut self, optional_args: &[Value]) -> Value {
let mut code = 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
}));
return self.query_transactions_by_event_type(Value::Str("deposit_collateral".into()), Value::Str("deposit".into()), Value::Str("fetchDeposits".into()), &[code, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name nado#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @see https://docs.nado.xyz/developer-resources/api/archive-indexer/events
* @param {string} [code] unified currency code
* @param {int} [since] the earliest time in ms to fetch withdrawals for
* @param {int} [limit] the maximum number of withdrawals structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @param {int} [params.until] timestamp in ms of the latest withdrawal to fetch
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/#/?id=transaction-structure}
*/
pub async fn fetch_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = 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
}));
return self.query_transactions_by_event_type(Value::Str("withdraw_collateral".into()), Value::Str("withdrawal".into()), Value::Str("fetchWithdrawals".into()), &[code, since, limit, params]).await;
Value::Null
}
pub async fn query_transactions_by_event_type(&mut self, mut eventType: Value, mut transactionType: Value, mut methodName: Value, optional_args: &[Value]) -> Value {
let mut code = 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.walletAddress.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), methodName).into()), Value::Str("() requires walletAddress".into()))));
}
self.load_markets(&[]).await;
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code.clone());
}
let mut subaccountparamsSubaccountVariable = self.handle_option_string_and_params(params, methodName, Value::Str("subaccount".into()), &[Value::Str("default".into())]);
let mut subaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut eventsRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("subaccounts".to_string(), Value::from(vec![self.create_subaccount(self.walletAddress.clone(), &[subaccount])]));
m.insert("event_types".to_string(), Value::from(vec![eventType]));
m.insert("limit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("raw".to_string(), (if (limit == Value::Null) { Value::Int(100) } else { crate::runtime::Math::min(&limit, &Value::Int(500)) }));
m
}));
m
});
if (currency != Value::Null) {
if let Value::Dict(__d) = &mut eventsRequest { std::sync::Arc::make_mut(__d).insert("product_ids".into(), Value::from(vec![self.parse_to_int(currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null))])); }
}
let mut eventsRequestUntilparamsUntilVariable = self.handle_until_option(Value::Str("max_time".into()), eventsRequest, paramsSubaccount, &[Value::Float(0.001)]);
let mut eventsRequestUntil: Value = eventsRequestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = eventsRequestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("events".to_string(), eventsRequestUntil);
m
});
let mut response: Value = self.archive_post(&[self.deep_extend(request, &[paramsUntil])]).await;
//
// {
// "events": [
// {
// "subaccount": "0x...",
// "product_id": 5,
// "submission_idx": "563011",
// "event_type": "deposit_collateral",
// "pre_balance": {
// "spot": {
// "balance": {
// "amount": "1000000000000000000"
// }
// }
// },
// "post_balance": {
// "spot": {
// "balance": {
// "amount": "2000000000000000000"
// }
// }
// }
// }
// ],
// "txs": [
// {
// "submission_idx": "563011",
// "timestamp": "1679728127"
// }
// ]
// }
//
let mut events: Value = self.safe_list_k(response.clone(), "events", &[Value::from(vec![])]);
let mut txs: Value = self.safe_list_k(response, "txs", &[Value::from(vec![])]);
let mut transactions: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_976: bool = true;
while { if !__for_first_976 { 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_976 = false; i.as_f64().unwrap_or(f64::NAN) < ((events.len() as i64) as f64) } {
let mut event: Value = events.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut submissionIdx: Value = self.safe_string_k(event.clone(), "submission_idx", &[]);
let mut tx: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut j: Value = Value::Int(0);
let mut __for_first_975: bool = true;
while { if !__for_first_975 { 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_975 = false; j.as_f64().unwrap_or(f64::NAN) < ((txs.len() as i64) as f64) } {
let mut rawTx: Value = txs.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut txSubmissionIdx: Value = self.safe_string_k(rawTx.clone(), "submission_idx", &[]);
if (txSubmissionIdx.as_str() == submissionIdx.as_str()) {
tx = rawTx;
break;
}
}
}
let mut transaction: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), &[tx]);
transaction = self.extend(transaction.clone(), &[event]);
add_element_to_object(&mut transaction, &Value::Str("transaction_type".into()), transactionType.clone());
append_to_array(&mut transactions, self.parse_transaction(transaction, &[currency.clone()]));
}
}
return self.filter_by_currency_since_limit(transactions, &[code, since, limit]);
Value::Null
}
/*
* @method
* @name nado#fetchPositions
* @description fetch all open positions
* @see https://docs.nado.xyz/developer-resources/api/gateway/queries/subaccount-info
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @returns {Position[]} a list of [position structures]{@link https://docs.ccxt.com/#/?id=position-structure}
*/
pub async fn fetch_positions(&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.walletAddress.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchPositions() requires walletAddress".into()))));
}
self.load_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut subaccountparamsSubaccountVariable = self.handle_option_string_and_params(params, Value::Str("fetchPositions".into()), Value::Str("subaccount".into()), &[Value::Str("default".into())]);
let mut subaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("subaccount_info".into()));
m.insert("subaccount".to_string(), self.create_subaccount(self.walletAddress.clone(), &[subaccount]));
m
});
let __ws_arg_12 = self.extend(request, &[paramsSubaccount]);
let mut response: Value = self.gateway_public_get_query(&[__ws_arg_12]).await;
//
// {
// "status": "success",
// "data": {
// "perp_balances": [
// {
// "product_id": 2,
// "balance": {
// "amount": "100000000000000000",
// "v_quote_balance": "3033500000000000000000",
// "last_cumulative_funding_x18": "-394223711772447555304"
// }
// }
// ],
// "perp_products": [
// {
// "product_id": 2,
// "oracle_price_x18": "115596528090565357611177",
// "risk": {
// "price_x18": "115596528090565357611177"
// }
// }
// ]
// },
// "request_type": "query_subaccount_info"
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut positions: Value = self.safe_list_k(data.clone(), "perp_balances", &[Value::from(vec![])]);
let mut products: Value = self.safe_list_k(data, "perp_products", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_978: bool = true;
while { if !__for_first_978 { 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_978 = false; i.as_f64().unwrap_or(f64::NAN) < ((positions.len() as i64) as f64) } {
let mut position: Value = positions.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 balance: Value = self.safe_dict_k(position.clone(), "balance", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut amount: Value = self.safe_string_k(balance, "amount", &[]);
if (amount == Value::Null) || is_true(&crate::precise::Precise::stringEquals(&amount, &Value::Str("0".into()))) {
continue;
}
let mut productId: Value = self.safe_string_k(position.clone(), "product_id", &[]);
let mut product: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut j: Value = Value::Int(0);
let mut __for_first_977: bool = true;
while { if !__for_first_977 { 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_977 = false; j.as_f64().unwrap_or(f64::NAN) < ((products.len() as i64) as f64) } {
let mut rawProduct: Value = products.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut rawProductId: Value = self.safe_string_k(rawProduct.clone(), "product_id", &[]);
if (rawProductId.as_str() == productId.as_str()) {
product = rawProduct;
break;
}
}
}
let __ws_arg_13 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product".to_string(), product);
m
}), &[position]);
append_to_array(&mut result, self.parse_position(__ws_arg_13, &[]));
}
}
return self.filter_by_array_positions(result, Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name nado#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://docs.nado.xyz/developer-resources/api/gateway/edge#control-messages
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int} the current integer timestamp in milliseconds from the exchange server
*/
pub async fn fetch_time(&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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("time".into()));
m
});
let __ws_arg_14 = self.extend(request, &[params]);
let mut response: Value = self.gateway_public_get_edge_query(&[__ws_arg_14]).await;
return self.safe_integer_k(response, "server_time", &[]);
Value::Null
}
/*
* @method
* @name nado#fetchStatus
* @description the latest known information on the availability of the exchange API
* @see https://docs.nado.xyz/developer-resources/api/gateway/queries/status
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [status structure]{@link https://docs.ccxt.com/?id=exchange-status-structure}
*/
pub async fn fetch_status(&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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("status".into()));
m
});
let __ws_arg_15 = self.extend(request, &[params]);
let mut response: Value = self.gateway_public_get_query(&[__ws_arg_15]).await;
//
// {
// "status": "success",
// "data": "active",
// "request_type": "query_status"
// }
//
let mut status: Option<String> = self.safe_string_k(response.clone(), "data", &[]).as_str().map(str::to_owned);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), (if (status.as_deref() == Some("active")) { Value::Str("ok".into()) } else { Value::Str("error".into()) }));
m.insert("updated".to_string(), Value::Null);
m.insert("eta".to_string(), Value::Null);
m.insert("url".to_string(), Value::Null);
m.insert("info".to_string(), response);
m
});
Value::Null
}
/*
* @method
* @name nado#fetchMarkets
* @description retrieves data on all markets for nado
* @see https://docs.nado.xyz/developer-resources/api/gateway/queries/symbols
* @see https://docs.nado.xyz/developer-resources/api/v2/pairs
* @see https://docs.nado.xyz/developer-resources/api/v2/assets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&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 symbolsRequest: Value = self.gateway_public_get_symbols(&[params.clone()]).await;
let mut pairsRequest: Value = self.gateway_v2_public_get_pairs(&[params.clone()]).await;
let mut assetsRequest: Value = self.gateway_v2_public_get_assets(&[params]).await;
let mut responses: Value = promise_all(&Value::from(vec![symbolsRequest, pairsRequest, assetsRequest])).await;
let mut symbols: Value = self.safe_list(responses.clone(), Value::Int(0), &[Value::from(vec![])]);
let mut pairs: Value = self.safe_list(responses.clone(), Value::Int(1), &[Value::from(vec![])]);
let mut assets: Value = self.safe_list(responses, Value::Int(2), &[Value::from(vec![])]);
// product_id is a JSON number: JS object keys are always strings but a Python
// dict keeps int keys, so indexBy would never match the safeString lookups below
let mut pairsById: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_979: bool = true;
while { if !__for_first_979 { 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_979 = false; i.as_f64().unwrap_or(f64::NAN) < ((pairs.len() as i64) as f64) } {
let mut rawPair: Value = pairs.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 pairProductId: Value = self.safe_string_k(rawPair.clone(), "product_id", &[]);
if (pairProductId != Value::Null) {
if let Value::Dict(__d) = &mut pairsById { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&pairProductId), rawPair); }
}
}
}
let mut assetsById: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_980: bool = true;
while { if !__for_first_980 { 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_980 = false; i.as_f64().unwrap_or(f64::NAN) < ((assets.len() as i64) as f64) } {
let mut rawAsset: Value = assets.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 assetProductId: Value = self.safe_string_k(rawAsset.clone(), "product_id", &[]);
if (assetProductId != Value::Null) {
if let Value::Dict(__d) = &mut assetsById { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&assetProductId), rawAsset.clone()); }
}
}
}
let mut assetsByCode: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_981: bool = true;
while { if !__for_first_981 { 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_981 = false; i.as_f64().unwrap_or(f64::NAN) < ((assets.len() as i64) as f64) } {
let mut rawAsset: Value = assets.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 assetSymbol: Value = self.safe_string_k(rawAsset.clone(), "symbol", &[]);
let mut assetCode: Value = self.safe_currency_code(self.remove_market_suffix(assetSymbol), &[]);
if (assetCode == Value::Null) {
continue;
}
let mut previous: Value = self.safe_dict(assetsByCode.clone(), assetCode.clone(), &[]);
if (previous == Value::Null) {
if let Value::Dict(__d) = &mut assetsByCode { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&assetCode), rawAsset.clone()); }
} else {
let mut previousDeposit: Value = self.safe_bool_k(previous.clone(), "can_deposit", &[Value::Bool(false)]);
let mut previousWithdraw: Value = self.safe_bool_k(previous, "can_withdraw", &[Value::Bool(false)]);
let mut currentDeposit: Value = self.safe_bool_k(rawAsset.clone(), "can_deposit", &[Value::Bool(false)]);
let mut currentWithdraw: Value = self.safe_bool_k(rawAsset.clone(), "can_withdraw", &[Value::Bool(false)]);
if (previousDeposit.as_bool() != Some(true)) && (previousWithdraw.as_bool() != Some(true)) && ((currentDeposit.as_bool() == Some(true)) || (currentWithdraw.as_bool() == Some(true))) {
if let Value::Dict(__d) = &mut assetsByCode { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&assetCode), rawAsset); }
}
}
}
}
let mut markets: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_982: bool = true;
while { if !__for_first_982 { 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_982 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut market: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut id: Value = self.safe_string_k(market.clone(), "product_id", &[]);
let mut pair: Value = self.safe_dict(pairsById.clone(), id.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut asset: Value = self.safe_dict(assetsById.clone(), id.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawType: Value = self.safe_string_k(market.clone(), "type", &[]);
let mut type_var: Value = rawType.clone();
if (rawType.as_str() == Some("perp")) {
type_var = Value::Str("swap".into());
}
let mut contract: Value = (Value::Bool(type_var.as_str() == Some("swap")));
let mut tickerId: Value = self.safe_string2(pair.clone(), Value::Str("ticker_id".into()), Value::Str("tickerId".into()), &[]);
if (tickerId == Value::Null) {
continue;
}
let mut rawBaseId: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut rawQuoteId: Value = self.safe_string_k(pair.clone(), "quote", &[Value::Str("USDT0".into())]);
let mut base: Value = self.safe_currency_code(self.remove_market_suffix(rawBaseId.clone()), &[]);
let mut quote: Value = self.safe_currency_code(rawQuoteId.clone(), &[]);
if (base == Value::Null) || (quote == Value::Null) {
continue;
}
let mut baseAsset: Value = self.safe_dict(assetsByCode.clone(), base.clone(), &[asset.clone()]);
let mut quoteAsset: Value = self.safe_dict(assetsByCode.clone(), quote.clone(), &[]);
let mut baseId: Value = self.safe_string_k(baseAsset, "product_id", &[rawBaseId]);
let mut quoteId: Value = self.safe_string_k(quoteAsset, "product_id", &[rawQuoteId]);
let mut settleId: Value = (if matches!(&contract, Value::Bool(true)) { quoteId.clone() } else { Value::Null });
let mut settle: Value = (if matches!(&contract, Value::Bool(true)) { quote.clone() } else { Value::Null });
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
if matches!(&contract, Value::Bool(true)) {
symbol = Value::Str(format!("{}{}", symbol, Value::Str(format!("{}{}", Value::Str(":".into()), settle).into())).into());
}
let mut tradingStatus: Option<String> = self.safe_string_k(market.clone(), "trading_status", &[]).as_str().map(str::to_owned);
let mut active: Value = (Value::Bool(tradingStatus.as_deref() != Some("not_tradable")));
let mut priceIncrement: Value = self.parse_x18(self.safe_string_k(market.clone(), "price_increment_x18", &[]));
let mut amountIncrement: Value = self.parse_x18(self.safe_string_k(market.clone(), "size_increment", &[]));
let mut minCost: Value = self.parse_x18(self.safe_string_k(market.clone(), "min_size", &[]));
append_to_array(&mut markets, self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("lowercaseId".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), settle);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), settleId);
m.insert("type".to_string(), type_var.clone());
m.insert("spot".to_string(), (Value::Bool(type_var.as_str() == Some("spot"))));
m.insert("margin".to_string(), Value::Null);
m.insert("swap".to_string(), contract.clone());
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), active);
m.insert("contract".to_string(), contract.clone());
m.insert("linear".to_string(), (if matches!(&contract, Value::Bool(true)) { Value::Bool(true) } else { Value::Null }));
m.insert("inverse".to_string(), (if matches!(&contract, Value::Bool(true)) { Value::Bool(false) } else { Value::Null }));
m.insert("taker".to_string(), self.parse_x18(self.safe_string_k(market.clone(), "taker_fee_rate_x18", &[])));
m.insert("maker".to_string(), self.parse_x18(self.safe_string_k(market.clone(), "maker_fee_rate_x18", &[])));
m.insert("contractSize".to_string(), (if matches!(&contract, Value::Bool(true)) { Value::Int(1) } else { Value::Null }));
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), amountIncrement);
m.insert("price".to_string(), priceIncrement);
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), minCost);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
let __ws_arg_16 = self.safe_string_k(asset.clone(), "name", &[]);
m.insert("info".to_string(), self.extend(market, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker_id".to_string(), tickerId);
m.insert("name".to_string(), __ws_arg_16);
m.insert("v2Pair".to_string(), pair);
m.insert("v2Asset".to_string(), asset);
m
})]));
m
})]));
}
}
return markets;
Value::Null
}
/*
* @method
* @name nado#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://docs.nado.xyz/developer-resources/api/v2/assets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
pub async fn fetch_currencies(&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 response: Value = self.gateway_v2_public_get_assets(&[params]).await;
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut assets: Value = self.to_array(response);
{
let mut i: Value = Value::Int(0);
let mut __for_first_983: bool = true;
while { if !__for_first_983 { 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_983 = false; i.as_f64().unwrap_or(f64::NAN) < ((assets.len() as i64) as f64) } {
let mut currency: Value = assets.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_currency(currency.clone());
let mut code: Value = self.safe_string_k(parsed.clone(), "code", &[]);
if (code == Value::Null) {
continue;
}
let mut previous: Value = self.safe_dict(result.clone(), code.clone(), &[]);
let mut canDeposit: Value = self.safe_bool_k(currency.clone(), "can_deposit", &[Value::Bool(false)]);
let mut canWithdraw: Value = self.safe_bool_k(currency, "can_withdraw", &[Value::Bool(false)]);
if (previous == Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), parsed.clone()); }
} else {
let mut previousDeposit: Value = self.safe_bool_k(previous.clone(), "deposit", &[Value::Bool(false)]);
let mut previousWithdraw: Value = self.safe_bool_k(previous, "withdraw", &[Value::Bool(false)]);
if (previousDeposit.as_bool() != Some(true)) && (previousWithdraw.as_bool() != Some(true)) && ((canDeposit.as_bool() == Some(true)) || (canWithdraw.as_bool() == Some(true))) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), parsed); }
}
}
}
}
return result;
Value::Null
}
/*
* @method
* @name nado#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://docs.nado.xyz/developer-resources/api/v2/tickers
* @param {string[]|undefined} symbols unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_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
}));
self.load_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut response: Value = self.archive_v2_public_get_tickers(&[params]).await;
//
// {
// "BTC-PERP_USDT0": {
// "product_id": 2,
// "ticker_id": "BTC-PERP_USDT0",
// "base_currency": "BTC",
// "quote_currency": "USDT0",
// "last_price": 25728.0,
// "base_volume": 552.048,
// "quote_volume": 14238632.207250029,
// "price_change_percent_24h": -0.6348599635253989
// }
// }
//
let mut tickers: Value = self.to_array(response);
return self.parse_tickers(tickers, &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name nado#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://docs.nado.xyz/developer-resources/api/v2/tickers
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_ticker(&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
}));
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 tickers: Value = self.fetch_tickers(&[Value::from(vec![symbolValue.clone()]), params]).await;
let mut ticker: Value = self.safe_dict(tickers, symbolValue.clone(), &[]);
if (ticker == Value::Null) {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchTicker() ticker not found for ".into())).into()), symbolValue)));
}
return ticker;
Value::Null
}
/*
* @method
* @name nado#fetchFundingRate
* @description fetch the current funding rate
* @see https://docs.nado.xyz/developer-resources/api/v2/contracts
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.edge] whether to retrieve volume and open interest metrics for all chains, defaults to true
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn fetch_funding_rate(&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
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRate() supports swap contracts only".into()))));
}
let mut tickerId: Value = self.safe_string(market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker_id".into()), &[]);
let mut response: Value = self.archive_v2_public_get_contracts(&[params]).await;
//
// {
// "BTC-PERP_USDT0": {
// "product_id": 1,
// "ticker_id": "BTC-PERP_USDT0",
// "base_currency": "BTC-PERP",
// "quote_currency": "USDT0",
// "last_price": 25744.0,
// "base_volume": 794.154,
// "quote_volume": 20475749.367766097,
// "product_type": "perpetual",
// "contract_price": 25830.738843799172,
// "contract_price_currency": "USD",
// "open_interest": 3059.325,
// "open_interest_usd": 79024625.11330591,
// "index_price": 25878.913320746455,
// "mark_price": 25783.996946729356,
// "funding_rate": -0.003664562348812546,
// "next_funding_rate_timestamp": 1694379600,
// "price_change_percent_24h": -0.6348599635253989
// }
// }
//
let mut data: Value = self.safe_dict(response, tickerId, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_funding_rate(data, &[market]);
Value::Null
}
/*
* @method
* @name nado#fetchFundingHistory
* @description fetch the history of funding payments paid and received on this account
* @see https://docs.nado.xyz/developer-resources/api/archive-indexer/interest-and-funding-payments
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch funding history for
* @param {int} [limit] the maximum number of funding history structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subaccount] the 12-byte subaccount identifier, defaults to 'default'
* @returns {object[]} a list of [funding history structures]{@link https://docs.ccxt.com/?id=funding-history-structure}
*/
pub async fn fetch_funding_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingHistory() requires a symbol argument".into()))));
}
if (self.walletAddress.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingHistory() requires walletAddress".into()))));
}
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol.clone());
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingHistory() supports swap contracts only".into()))));
}
let mut subaccountparamsSubaccountVariable = self.handle_option_string_and_params(params, Value::Str("fetchFundingHistory".into()), Value::Str("subaccount".into()), &[Value::Str("default".into())]);
let mut subaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubaccount: Value = subaccountparamsSubaccountVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("interest_and_funding".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("subaccount".to_string(), self.create_subaccount(self.walletAddress.clone(), &[subaccount]));
m.insert("product_ids".to_string(), Value::from(vec![self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null))]));
m.insert("limit".to_string(), (if (limit == Value::Null) { Value::Int(100) } else { crate::runtime::Math::min(&limit, &Value::Int(100)) }));
m
}));
m
});
let mut response: Value = self.archive_post(&[self.deep_extend(request, &[paramsSubaccount])]).await;
//
// {
// "interest_payments": [],
// "funding_payments": [
// {
// "product_id": 2,
// "idx": "5968022",
// "timestamp": "1701698400",
// "amount": "-12273223338657163",
// "balance_amount": "1000000000000000000",
// "rate_x18": "47928279191008320",
// "oracle_price_x18": "2243215034242228224820"
// }
// ],
// "next_idx": "1314805"
// }
//
let mut fundingPayments: Value = self.safe_list_k(response, "funding_payments", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_984: bool = true;
while { if !__for_first_984 { 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_984 = false; i.as_f64().unwrap_or(f64::NAN) < ((fundingPayments.len() as i64) as f64) } {
append_to_array(&mut result, self.parse_funding_history(fundingPayments.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[market.clone()]));
}
}
let mut sorted: Value = self.sort_by(result, Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[symbol, since, limit]);
Value::Null
}
/*
* @method
* @name nado#fetchFundingRates
* @description fetch the funding rate for multiple markets
* @see https://docs.nado.xyz/developer-resources/api/v2/contracts
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.edge] whether to retrieve volume and open interest metrics for all chains, defaults to true
* @returns {object} a dictionary of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rates-structure}, indexed by market symbols
*/
pub async fn fetch_funding_rates(&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
}));
self.load_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Str("swap".into()), Value::Bool(true)]);
let mut response: Value = self.archive_v2_public_get_contracts(&[params]).await;
//
// {
// "BTC-PERP_USDT0": {
// "product_id": 1,
// "ticker_id": "BTC-PERP_USDT0",
// "base_currency": "BTC-PERP",
// "quote_currency": "USDT0",
// "last_price": 25744.0,
// "base_volume": 794.154,
// "quote_volume": 20475749.367766097,
// "product_type": "perpetual",
// "contract_price": 25830.738843799172,
// "contract_price_currency": "USD",
// "open_interest": 3059.325,
// "open_interest_usd": 79024625.11330591,
// "index_price": 25878.913320746455,
// "mark_price": 25783.996946729356,
// "funding_rate": -0.003664562348812546,
// "next_funding_rate_timestamp": 1694379600,
// "price_change_percent_24h": -0.6348599635253989
// }
// }
//
let mut tickers: Value = object_keys(&response);
let mut rates: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_985: bool = true;
while { if !__for_first_985 { 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_985 = false; i.as_f64().unwrap_or(f64::NAN) < ((tickers.len() as i64) as f64) } {
let mut ticker: Value = tickers.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 rates, self.safe_dict(response.clone(), ticker, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]));
}
}
return self.parse_funding_rates(rates, &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name nado#fetchOpenInterest
* @description retrieves the open interest of a contract trading pair
* @see https://docs.nado.xyz/developer-resources/api/v2/contracts
* @param {string} symbol unified CCXT market symbol
* @param {object} [params] exchange specific parameters
* @param {boolean} [params.edge] whether to retrieve volume and open interest metrics for all chains, defaults to true
* @returns {object} an [open interest structure]{@link https://docs.ccxt.com/?id=open-interest-structure}
*/
pub async fn fetch_open_interest(&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
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenInterest() supports swap contracts only".into()))));
}
let mut tickerId: Value = self.safe_string(market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker_id".into()), &[]);
let mut response: Value = self.archive_v2_public_get_contracts(&[params]).await;
//
// {
// "BTC-PERP_USDT0": {
// "product_id": 1,
// "ticker_id": "BTC-PERP_USDT0",
// "base_currency": "BTC-PERP",
// "quote_currency": "USDT0",
// "last_price": 25744.0,
// "base_volume": 794.154,
// "quote_volume": 20475749.367766097,
// "product_type": "perpetual",
// "contract_price": 25830.738843799172,
// "contract_price_currency": "USD",
// "open_interest": 3059.325,
// "open_interest_usd": 79024625.11330591,
// "index_price": 25878.913320746455,
// "mark_price": 25783.996946729356,
// "funding_rate": -0.003664562348812546,
// "next_funding_rate_timestamp": 1694379600,
// "price_change_percent_24h": -0.6348599635253989
// }
// }
//
let mut data: Value = self.safe_dict(response, tickerId, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_open_interest(data, &[market]);
Value::Null
}
/*
* @method
* @name nado#fetchOpenInterests
* @description retrieves the open interests of some currencies
* @see https://docs.nado.xyz/developer-resources/api/v2/contracts
* @param {string[]} [symbols] unified CCXT market symbols
* @param {object} [params] exchange specific parameters
* @param {boolean} [params.edge] whether to retrieve volume and open interest metrics for all chains, defaults to true
* @returns {object} a dictionary of [open interest structures]{@link https://docs.ccxt.com/?id=open-interest-structure}
*/
pub async fn fetch_open_interests(&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
}));
self.load_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Str("swap".into()), Value::Bool(true)]);
let mut response: Value = self.archive_v2_public_get_contracts(&[params]).await;
//
// {
// "BTC-PERP_USDT0": {
// "product_id": 1,
// "ticker_id": "BTC-PERP_USDT0",
// "base_currency": "BTC-PERP",
// "quote_currency": "USDT0",
// "last_price": 25744.0,
// "base_volume": 794.154,
// "quote_volume": 20475749.367766097,
// "product_type": "perpetual",
// "contract_price": 25830.738843799172,
// "contract_price_currency": "USD",
// "open_interest": 3059.325,
// "open_interest_usd": 79024625.11330591,
// "index_price": 25878.913320746455,
// "mark_price": 25783.996946729356,
// "funding_rate": -0.003664562348812546,
// "next_funding_rate_timestamp": 1694379600,
// "price_change_percent_24h": -0.6348599635253989
// }
// }
//
let mut tickers: Value = object_keys(&response);
let mut interests: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_986: bool = true;
while { if !__for_first_986 { 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_986 = false; i.as_f64().unwrap_or(f64::NAN) < ((tickers.len() as i64) as f64) } {
let mut ticker: Value = tickers.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 interests, self.safe_dict(response.clone(), ticker, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]));
}
}
return self.parse_open_interests(interests, &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name nado#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.nado.xyz/developer-resources/api/v2/orderbook
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn fetch_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.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut tickerId: Value = self.safe_string(market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker_id".into()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker_id".to_string(), tickerId);
m.insert("depth".to_string(), (if (limit == Value::Null) { Value::Int(100) } else { limit }));
m
});
let __ws_arg_17 = self.extend(request, &[params]);
let mut response: Value = self.gateway_v2_public_get_orderbook(&[__ws_arg_17]).await;
//
// {
// "product_id": 1,
// "ticker_id": "BTC-PERP_USDT0",
// "bids": [
// [ 116215.0, 0.128 ],
// [ 116214.0, 0.172 ]
// ],
// "asks": [
// [ 116225.0, 0.043 ],
// [ 116226.0, 0.172 ]
// ],
// "timestamp": 1757913317944
// }
//
let mut timestamp: Value = self.safe_integer_k(response.clone(), "timestamp", &[]);
return self.parse_order_book(response, market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[timestamp]);
Value::Null
}
/*
* @method
* @name nado#fetchTrades
* @description get the list of the most recent trades for a particular symbol
* @see https://docs.nado.xyz/developer-resources/api/v2/trades
* @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 {int} [params.max_trade_id] max trade id to include in the result for pagination
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn fetch_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.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut tickerId: Value = self.safe_string(market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker_id".into()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker_id".to_string(), tickerId);
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(500))); }
}
let __ws_arg_18 = self.extend(request, &[params]);
let mut response: Value = self.archive_v2_public_get_trades(&[__ws_arg_18]).await;
return self.parse_trades(response, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name nado#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://docs.nado.xyz/developer-resources/api/archive-indexer/candlesticks
* @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, max 500
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest candle to fetch
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_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
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("until".into()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("candlesticks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m.insert("granularity".to_string(), self.safe_integer(self.timeframes.clone(), timeframe.clone(), &[self.parse_timeframe(timeframe.clone())]));
m
}));
m
});
if (limit != Value::Null) {
add_element_to_object(get_value_mut(&mut request, &Value::Str("candlesticks".into())), &Value::Str("limit".into()), crate::runtime::Math::min(&limit, &Value::Int(500)));
}
if (until != Value::Null) {
add_element_to_object(get_value_mut(&mut request, &Value::Str("candlesticks".into())), &Value::Str("max_time".into()), self.parse_to_int((match ((until).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })));
}
let mut response: Value = self.archive_post(&[self.deep_extend(request, &[paramsOmitted])]).await;
//
// {
// "candlesticks": [
// {
// "product_id": 1,
// "granularity": 60,
// "submission_idx": "627709",
// "timestamp": "1680118140",
// "open_x18": "27235000000000000000000",
// "high_x18": "27298000000000000000000",
// "low_x18": "27235000000000000000000",
// "close_x18": "27298000000000000000000",
// "volume": "1999999999999999998"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "candlesticks", &[Value::from(vec![])]);
return self.parse_ohlc_vs(data, &[market, timeframe, since, limit]);
Value::Null
}
pub fn parse_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_timestamp_k(ohlcv.clone(), "timestamp", &[]), self.parse_x18(self.safe_string_k(ohlcv.clone(), "open_x18", &[])), self.parse_x18(self.safe_string_k(ohlcv.clone(), "high_x18", &[])), self.parse_x18(self.safe_string_k(ohlcv.clone(), "low_x18", &[])), self.parse_x18(self.safe_string_k(ohlcv.clone(), "close_x18", &[])), self.parse_x18(self.safe_string_k(ohlcv, "volume", &[]))]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "product_id": 1,
// "ticker_id": "BTC-PERP_USDT0",
// "trade_id": 6351,
// "price": 112029.5896,
// "base_filled": -0.388,
// "quote_filled": 43467.4807648,
// "timestamp": 1757335618,
// "trade_type": "sell"
// }
//
// archive match
//
// {
// "submission_idx": "563012",
// "product_id": 2,
// "timestamp": "1679728133",
// "digest": "0x80ce789702b670b7d33f2aa67e12c85f124395c3f9acdb422dde3b4973ccd50c",
// "order": {
// "priceX18": "27544000000000000000000",
// "amount": "2000000000000000000"
// },
// "base_filled": "736000000000000000",
// "quote_filled": "-20276464287857571514302",
// "fee": "4055287857571514302",
// "is_taker": true
// }
//
let mut marketId: Value = self.safe_string_k(trade.clone(), "product_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut timestamp: Value = self.safe_timestamp_k(trade.clone(), "timestamp", &[]);
let mut rawOrder: Value = self.safe_dict_k(trade.clone(), "order", &[]);
let mut isArchiveMatch: bool = rawOrder != Value::Null;
let mut order: Value = (if (rawOrder == Value::Null) { Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) } else { rawOrder });
let mut amountString: Value = self.safe_string_k(trade.clone(), "base_filled", &[]);
let mut costString: Value = self.safe_string_k(trade.clone(), "quote_filled", &[]);
let mut rawOrderAmount: Value = self.safe_string_k(order.clone(), "amount", &[]);
let mut side: Value = self.safe_string_k(trade.clone(), "trade_type", &[]);
if (side == Value::Null) && (rawOrderAmount != Value::Null) {
if is_true(&crate::precise::Precise::stringLt(&rawOrderAmount, &Value::Str("0".into()))) {
side = Value::Str("sell".into());
} else {
side = Value::Str("buy".into());
}
}
let mut price: Value = self.safe_string_k(trade.clone(), "price", &[]);
if (price == Value::Null) {
let mut parsedPrice: Value = self.parse_x18(self.safe_string_k(order, "priceX18", &[]));
price = (if (parsedPrice == Value::Null) { Value::Null } else { self.number_to_string(parsedPrice) });
}
let mut takerOrMaker: Value = Value::Null;
let mut isTaker: Value = self.safe_bool_k(trade.clone(), "is_taker", &[]);
if (isTaker != Value::Null) {
if isTaker.as_bool() == Some(true) {
takerOrMaker = Value::Str("taker".into());
} else {
takerOrMaker = Value::Str("maker".into());
}
}
let mut feeString: Value = self.safe_string_k(trade.clone(), "fee", &[]);
let mut feeCost: Value = Value::Null;
if isArchiveMatch {
feeCost = self.parse_x18(feeString.clone());
} else {
feeCost = self.parse_number(feeString, &[]);
}
let mut fee: Value = Value::Null;
if (feeCost != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost);
m.insert("currency".to_string(), marketResolved.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null));
m
});
}
let mut parsedAmount: Value = Value::Null;
if (amountString != Value::Null) {
let mut absoluteAmount: Value = crate::precise::Precise::stringAbs(&amountString);
if isArchiveMatch {
parsedAmount = self.parse_x18(absoluteAmount.clone());
} else {
parsedAmount = absoluteAmount;
}
}
let mut parsedCost: Value = Value::Null;
if (costString != Value::Null) {
let mut absoluteCost: Value = crate::precise::Precise::stringAbs(&costString);
if isArchiveMatch {
parsedCost = self.parse_x18(absoluteCost.clone());
} else {
parsedCost = absoluteCost;
}
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("id".to_string(), self.safe_string2(trade.clone(), Value::Str("trade_id".into()), Value::Str("submission_idx".into()), &[]));
m.insert("order".to_string(), self.safe_string_k(trade, "digest", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), parsedAmount);
m.insert("cost".to_string(), parsedCost);
m.insert("fee".to_string(), fee);
m
}), &[marketResolved]);
Value::Null
}
pub fn parse_funding_rate(&self, mut contract: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "product_id": 1,
// "ticker_id": "BTC-PERP_USDT0",
// "base_currency": "BTC-PERP",
// "quote_currency": "USDT0",
// "last_price": 25744.0,
// "base_volume": 794.154,
// "quote_volume": 20475749.367766097,
// "product_type": "perpetual",
// "contract_price": 25830.738843799172,
// "contract_price_currency": "USD",
// "open_interest": 3059.325,
// "open_interest_usd": 79024625.11330591,
// "index_price": 25878.913320746455,
// "mark_price": 25783.996946729356,
// "funding_rate": -0.003664562348812546,
// "next_funding_rate_timestamp": 1694379600,
// "price_change_percent_24h": -0.6348599635253989
// }
//
let mut marketId: Value = self.safe_string_k(contract.clone(), "product_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut fundingTimestamp: Value = self.safe_timestamp_k(contract.clone(), "next_funding_rate_timestamp", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), contract.clone());
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("markPrice".to_string(), self.safe_number_k(contract.clone(), "mark_price", &[]));
m.insert("indexPrice".to_string(), self.safe_number_k(contract.clone(), "index_price", &[]));
m.insert("interestRate".to_string(), Value::Null);
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("fundingRate".to_string(), self.safe_number_k(contract, "funding_rate", &[]));
m.insert("fundingTimestamp".to_string(), fundingTimestamp.clone());
m.insert("fundingDatetime".to_string(), self.iso8601(fundingTimestamp));
m.insert("nextFundingRate".to_string(), Value::Null);
m.insert("nextFundingTimestamp".to_string(), Value::Null);
m.insert("nextFundingDatetime".to_string(), Value::Null);
m.insert("previousFundingRate".to_string(), Value::Null);
m.insert("previousFundingTimestamp".to_string(), Value::Null);
m.insert("previousFundingDatetime".to_string(), Value::Null);
m.insert("interval".to_string(), Value::Str("24h".into()));
m
});
Value::Null
}
pub fn parse_funding_history(&self, mut funding: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "product_id": 2,
// "idx": "5968022",
// "timestamp": "1701698400",
// "amount": "-12273223338657163",
// "balance_amount": "1000000000000000000",
// "rate_x18": "47928279191008320",
// "oracle_price_x18": "2243215034242228224820"
// }
//
let mut marketId: Value = self.safe_string_k(funding.clone(), "product_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut timestamp: Value = self.safe_timestamp_k(funding.clone(), "timestamp", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), funding.clone());
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("code".to_string(), self.safe_string_k(marketResolved, "settle", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("id".to_string(), self.safe_string_k(funding.clone(), "idx", &[]));
m.insert("amount".to_string(), self.parse_x18(self.safe_string_k(funding, "amount", &[])));
m
});
Value::Null
}
pub fn parse_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "product_id": 1,
// "ticker_id": "BTC-PERP_USDT0",
// "base_currency": "BTC-PERP",
// "quote_currency": "USDT0",
// "last_price": 25744.0,
// "base_volume": 794.154,
// "quote_volume": 20475749.367766097,
// "product_type": "perpetual",
// "contract_price": 25830.738843799172,
// "contract_price_currency": "USD",
// "open_interest": 3059.325,
// "open_interest_usd": 79024625.11330591,
// "index_price": 25878.913320746455,
// "mark_price": 25783.996946729356,
// "funding_rate": -0.003664562348812546,
// "next_funding_rate_timestamp": 1694379600,
// "price_change_percent_24h": -0.6348599635253989
// }
//
let mut marketId: Value = self.safe_string_k(interest.clone(), "product_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
return self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("openInterestAmount".to_string(), self.safe_number_k(interest.clone(), "open_interest", &[]));
m.insert("openInterestValue".to_string(), self.safe_number_k(interest.clone(), "open_interest_usd", &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("info".to_string(), interest);
m
}), &[marketResolved]);
Value::Null
}
pub fn parse_ticker(&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(), "product_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut timestamp: Value = Value::Null;
let mut last: Value = self.safe_string_k(ticker.clone(), "last_price", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), Value::Null);
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), Value::Null);
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last);
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), self.safe_string_k(ticker.clone(), "price_change_percent_24h", &[]));
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), self.safe_string_k(ticker.clone(), "base_volume", &[]));
m.insert("quoteVolume".to_string(), self.safe_string_k(ticker.clone(), "quote_volume", &[]));
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
Value::Null
}
pub fn parse_currency(&self, mut rawCurrency: Value) -> Value {
let mut canDeposit: Value = self.safe_bool_k(rawCurrency.clone(), "can_deposit", &[Value::Bool(false)]);
let mut canWithdraw: Value = self.safe_bool_k(rawCurrency.clone(), "can_withdraw", &[Value::Bool(false)]);
let mut id: Value = self.safe_string_k(rawCurrency.clone(), "product_id", &[]);
let mut currencyId: Value = self.safe_string_k(rawCurrency.clone(), "symbol", &[]);
let mut code: Value = self.safe_currency_code(self.remove_market_suffix(currencyId), &[]);
return self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("name".to_string(), self.safe_string_k(rawCurrency.clone(), "name", &[]));
m.insert("code".to_string(), code);
m.insert("precision".to_string(), Value::Null);
m.insert("active".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("deposit".to_string(), canDeposit);
m.insert("withdraw".to_string(), canWithdraw);
m.insert("type".to_string(), Value::Str("crypto".into()));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("info".to_string(), rawCurrency);
m
}));
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
//
// {
// "subaccount": "0x8d7d64d6cf1d4f018dd101482ac71ad49e30c56064656661756c740000000000",
// "exists": true,
// "spot_balances": [
// {
// "product_id": 0,
// "balance": {
// "amount": "456895621098158389211471"
// }
// }
// ],
// "perp_balances": []
// }
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut balances: Value = self.safe_list_k(response, "spot_balances", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_987: bool = true;
while { if !__for_first_987 { 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_987 = false; i.as_f64().unwrap_or(f64::NAN) < ((balances.len() as i64) as f64) } {
let mut rawBalance: Value = self.safe_dict(balances.clone(), i.clone(), &[]);
let mut currencyId: Value = self.safe_string_k(rawBalance.clone(), "product_id", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
if (code.as_str() == Some("0")) {
code = Value::Str("USDT0".into());
} else if (code.as_str() == currencyId.as_str()) {
let mut market: Value = self.safe_market(&[currencyId, Value::Null, Value::Null, Value::Str("spot".into())]);
if matches!(self.safe_bool_k(market.clone(), "spot", &[Value::Bool(false)]), Value::Bool(true)) {
code = self.safe_string_k(market, "base", &[code.clone()]);
}
}
let mut balance: Value = self.safe_dict_k(rawBalance, "balance", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut amount: Value = crate::precise::Precise::stringDiv(&self.safe_string_k(balance, "amount", &[]), &Value::Str("1000000000000000000".into()));
let mut account: Value = self.account();
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), amount.clone()); }
// the subaccount balance carries no locked/reserved breakdown, the whole amount is spendable
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), amount); }
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
}
}
return self.safe_balance(result);
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "submission_idx": "563011",
// "timestamp": "1679728127",
// "subaccount": "0x...",
// "product_id": 5,
// "event_type": "deposit_collateral",
// "transaction_type": "deposit",
// "pre_balance": {
// "spot": {
// "balance": {
// "amount": "1000000000000000000"
// }
// }
// },
// "post_balance": {
// "spot": {
// "balance": {
// "amount": "2000000000000000000"
// }
// }
// }
// }
//
let mut currencyId: Value = self.safe_string_k(transaction.clone(), "product_id", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[currency]);
let mut timestamp: Value = self.safe_timestamp_k(transaction.clone(), "timestamp", &[]);
let mut preBalance: Value = self.safe_dict_k(transaction.clone(), "pre_balance", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut postBalance: Value = self.safe_dict_k(transaction.clone(), "post_balance", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut preSpot: Value = self.safe_dict_k(preBalance, "spot", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut postSpot: Value = self.safe_dict_k(postBalance, "spot", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut preSpotBalance: Value = self.safe_dict_k(preSpot, "balance", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut postSpotBalance: Value = self.safe_dict_k(postSpot, "balance", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut preAmount: Value = self.safe_string_k(preSpotBalance, "amount", &[Value::Str("0".into())]);
let mut postAmount: Value = self.safe_string_k(postSpotBalance, "amount", &[Value::Str("0".into())]);
let mut amount: Value = self.parse_x18(crate::precise::Precise::stringAbs(&crate::precise::Precise::stringSub(&postAmount, &preAmount)));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), self.safe_string_k(transaction.clone(), "submission_idx", &[]));
m.insert("txid".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("address".to_string(), Value::Null);
m.insert("addressFrom".to_string(), Value::Null);
m.insert("addressTo".to_string(), Value::Null);
m.insert("tag".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("type".to_string(), self.safe_string_k(transaction, "transaction_type", &[]));
m.insert("amount".to_string(), amount);
m.insert("currency".to_string(), code);
m.insert("status".to_string(), Value::Str("ok".into()));
m.insert("updated".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("network".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("internal".to_string(), Value::Null);
m
});
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "product_id": 2,
// "balance": {
// "amount": "100000000000000000",
// "v_quote_balance": "3033500000000000000000",
// "last_cumulative_funding_x18": "-394223711772447555304"
// },
// "product": {
// "product_id": 2,
// "oracle_price_x18": "115596528090565357611177",
// "risk": {
// "price_x18": "115596528090565357611177"
// }
// }
// }
//
let mut marketId: Value = self.safe_string_k(position.clone(), "product_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut balance: Value = self.safe_dict_k(position.clone(), "balance", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut amountString: Value = self.safe_string_k(balance.clone(), "amount", &[]);
let mut product: Value = self.safe_dict_k(position.clone(), "product", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut risk: Value = self.safe_dict_k(product, "risk", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut markPriceX18: Value = self.safe_string2(risk, Value::Str("price_x18".into()), Value::Str("oracle_price_x18".into()), &[]);
let mut vQuoteBalance: Value = self.safe_string_k(balance, "v_quote_balance", &[]);
let mut side: Value = Value::Null;
let mut contracts: Value = Value::Null;
let mut entryPrice: Value = Value::Null;
let mut markPrice: Value = Value::Null;
let mut notional: Value = Value::Null;
if (amountString != Value::Null) {
if is_true(&crate::precise::Precise::stringGt(&amountString, &Value::Str("0".into()))) {
side = Value::Str("long".into());
} else if is_true(&crate::precise::Precise::stringLt(&amountString, &Value::Str("0".into()))) {
side = Value::Str("short".into());
}
let mut absoluteAmount: Value = crate::precise::Precise::stringAbs(&amountString);
contracts = self.parse_x18(absoluteAmount.clone());
if (vQuoteBalance != Value::Null) && !is_true(&crate::precise::Precise::stringEquals(&absoluteAmount, &Value::Str("0".into()))) {
entryPrice = self.parse_number(crate::precise::Precise::stringDiv(&crate::precise::Precise::stringAbs(&vQuoteBalance), &absoluteAmount), &[]);
}
if (markPriceX18 != Value::Null) {
markPrice = self.parse_x18(markPriceX18.clone());
let mut notionalX36: Value = crate::precise::Precise::stringMul(&absoluteAmount, &markPriceX18);
notional = self.parse_number(crate::precise::Precise::stringDiv(¬ionalX36, &Value::Str("1000000000000000000000000000000000000".into())), &[]);
}
}
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position);
m.insert("id".to_string(), Value::Null);
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("isolated".to_string(), Value::Null);
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("side".to_string(), side);
m.insert("contracts".to_string(), contracts);
m.insert("contractSize".to_string(), self.safe_number_k(marketResolved, "contractSize", &[]));
m.insert("entryPrice".to_string(), entryPrice);
m.insert("markPrice".to_string(), markPrice);
m.insert("notional".to_string(), notional);
m.insert("leverage".to_string(), Value::Null);
m.insert("collateral".to_string(), Value::Null);
m.insert("initialMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("unrealizedPnl".to_string(), Value::Null);
m.insert("liquidationPrice".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Null);
m.insert("marginRatio".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m
}));
Value::Null
}
pub fn is_archive_order_closed(&self, mut order: Value) -> Value {
let __order_empty = indexmap::IndexMap::new();
let order = order.as_map().unwrap_or(&__order_empty);
let mut amount: Value = (match order.get("amount") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut filled: Value = (match order.get("base_filled") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (amount == Value::Null) || (filled == Value::Null) {
return Value::Bool(false);
}
return crate::precise::Precise::stringGe(&crate::precise::Precise::stringAbs(&filled), &crate::precise::Precise::stringAbs(&amount));
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// create order
//
// {
// "status": "success",
// "signature": "0x...",
// "data": {
// "digest": "0x..."
// },
// "request_type": "execute_place_order",
// "id": 100,
// "place_order": {
// "product_id": 2,
// "order": {
// "sender": "0x...",
// "priceX18": "1000000000000000000",
// "amount": "1000000000000000000",
// "expiration": "4294967295",
// "nonce": "1757062078359666688",
// "appendix": "1"
// },
// "signature": "0x..."
// }
// }
//
// open/cancel order
//
// {
// "product_id": 2,
// "sender": "0x...",
// "price_x18": "20000000000000000000000",
// "amount": "-100000000000000000",
// "expiration": "1686332748",
// "order_type": "post_only",
// "nonce": "1768248100142339392",
// "unfilled_amount": "-100000000000000000",
// "digest": "0x...",
// "appendix": "1537",
// "placed_at": 1686332708
// }
//
// trigger order
//
// {
// order: {
// order: {
// sender: '',
// priceX18: '100000000000000000000',
// amount: '-1000000000000000000',
// expiration: '4294967295',
// nonce: '',
// appendix: '4097'
// },
// signature: '',
// product_id: '8',
// spot_leverage: null,
// borrow_margin: null,
// trigger: { price_trigger: [Object] },
// digest: '',
// id: null
// },
// status: 'waiting_price',
// placed_at: '1783347360',
// updated_at: '1783347360'
// }
//
let mut id: Value = Value::Null;
let mut timestamp: Value = Value::Null;
let mut timeInForce: Value = Value::Null;
let mut postOnly: Value = Value::Null;
let mut side: Value = Value::Null;
let mut price: Value = Value::Null;
let mut amount: Value = Value::Null;
let mut filled: Value = Value::Null;
let mut remaining: Value = Value::Null;
let mut cost: Value = Value::Null;
let mut average: Value = Value::Null;
let mut fee: Value = Value::Null;
let mut lastTradeTimestamp: Value = Value::Null;
let mut lastUpdateTimestamp: Value = Value::Null;
let mut status: Value = Value::Null;
let mut marketResolved: Value = Value::Null;
let mut cancelOrderDigest: Value = self.safe_string_k(order.clone(), "digest", &[]);
let mut archiveFilled: Value = self.safe_string_k(order.clone(), "base_filled", &[]);
if (archiveFilled != Value::Null) {
id = cancelOrderDigest.clone();
let mut marketId: Value = self.safe_string_k(order.clone(), "product_id", &[]);
marketResolved = self.safe_market(&[marketId.clone(), market.clone()]);
let mut amountString: Value = self.safe_string_k(order.clone(), "amount", &[]);
if (amountString != Value::Null) {
side = (if is_true(&crate::precise::Precise::stringLt(&amountString, &Value::Str("0".into()))) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
amount = self.parse_x18(crate::precise::Precise::stringAbs(&amountString));
}
filled = self.parse_x18(crate::precise::Precise::stringAbs(&archiveFilled));
let mut costString: Value = self.safe_string_k(order.clone(), "quote_filled", &[]);
cost = (if (costString == Value::Null) { Value::Null } else { self.parse_x18(crate::precise::Precise::stringAbs(&costString)) });
if (filled != Value::Null) && (cost != Value::Null) {
average = crate::precise::Precise::stringDiv(&self.number_to_string(cost.clone()), &self.number_to_string(filled.clone()));
}
if (amountString != Value::Null) && (archiveFilled != Value::Null) {
remaining = self.parse_x18(crate::precise::Precise::stringMax(&crate::precise::Precise::stringSub(&crate::precise::Precise::stringAbs(&amountString), &crate::precise::Precise::stringAbs(&archiveFilled)), &Value::Str("0".into())));
}
timestamp = self.safe_timestamp_k(order.clone(), "first_fill_timestamp", &[]);
lastTradeTimestamp = self.safe_timestamp_k(order.clone(), "last_fill_timestamp", &[]);
price = self.parse_x18(self.safe_string_k(order.clone(), "price_x18", &[]));
status = self.safe_string_k(order.clone(), "status", &[]);
if (status == Value::Null) {
if is_true(&self.is_archive_order_closed(order.clone())) {
status = Value::Str("closed".into());
}
}
let mut feeCost: Value = self.parse_x18(self.safe_string_k(order.clone(), "fee", &[]));
if (feeCost != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost);
m.insert("currency".to_string(), self.safe_string_k(marketResolved.clone(), "quote", &[]));
m
});
}
} else if (cancelOrderDigest != Value::Null) {
id = cancelOrderDigest;
let mut marketId: Value = self.safe_string_k(order.clone(), "product_id", &[]);
marketResolved = self.safe_market(&[marketId.clone(), market.clone()]);
let mut amountString: Value = self.safe_string_k(order.clone(), "amount", &[]);
if (amountString != Value::Null) {
side = (if is_true(&crate::precise::Precise::stringLt(&amountString, &Value::Str("0".into()))) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
amount = self.parse_x18(crate::precise::Precise::stringAbs(&amountString));
}
let mut unfilledAmount: Value = self.safe_string_k(order.clone(), "unfilled_amount", &[]);
if (unfilledAmount != Value::Null) {
remaining = self.parse_x18(crate::precise::Precise::stringAbs(&unfilledAmount));
}
timestamp = self.safe_timestamp_k(order.clone(), "placed_at", &[]);
let mut orderType: Value = self.safe_string_k(order.clone(), "order_type", &[]);
timeInForce = self.parse_order_time_in_force(orderType.clone());
postOnly = Value::Bool(orderType.as_str() == Some("post_only"));
price = self.parse_x18(self.safe_string_k(order.clone(), "price_x18", &[]));
status = self.safe_string_k(order.clone(), "status", &[Value::Str("open".into())]);
} else {
let mut placeOrder: Value = self.safe_dict2(order.clone(), Value::Str("place_order".into()), Value::Str("order".into()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawOrder: Value = self.safe_dict_k(placeOrder.clone(), "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketId: Value = self.safe_string_k(placeOrder.clone(), "product_id", &[]);
marketResolved = self.safe_market(&[marketId, market]);
let mut data: Value = self.safe_dict_k(order.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
id = self.safe_string_k(data, "digest", &[]);
if (id == Value::Null) {
id = self.safe_string_k(placeOrder, "digest", &[]);
timestamp = self.safe_timestamp_k(order.clone(), "placed_at", &[]);
lastUpdateTimestamp = self.safe_timestamp_k(order.clone(), "updated_at", &[]);
}
let mut amountString: Value = self.safe_string_k(rawOrder.clone(), "amount", &[]);
if (amountString != Value::Null) {
side = (if is_true(&crate::precise::Precise::stringLt(&amountString, &Value::Str("0".into()))) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
amount = self.parse_x18(crate::precise::Precise::stringAbs(&amountString));
}
let mut triggerStatus: Value = self.safe_dict_k(order.clone(), "status", &[]);
if (triggerStatus != Value::Null) {
let mut triggered: Value = self.safe_dict_k(triggerStatus, "triggered", &[]);
if (triggered != Value::Null) {
status = Value::Str("closed".into());
} else {
status = Value::Str("canceled".into());
}
} else {
status = self.safe_string_k(order.clone(), "status", &[Value::Str("rejected".into())]);
if (status.as_str() == Some("success")) || (Value::Int(status.as_str().and_then(|__s| __s.find("waiting")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64)) {
status = Value::Str("open".into());
}
}
price = self.parse_x18(self.safe_string_k(rawOrder, "priceX18", &[]));
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order);
m.insert("id".to_string(), id);
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), lastTradeTimestamp);
m.insert("lastUpdateTimestamp".to_string(), lastUpdateTimestamp);
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), Value::Str("limit".into()));
m.insert("timeInForce".to_string(), timeInForce);
m.insert("postOnly".to_string(), postOnly);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("stopPrice".to_string(), Value::Null);
m.insert("triggerPrice".to_string(), Value::Null);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), cost);
m.insert("average".to_string(), average);
m.insert("filled".to_string(), filled);
m.insert("remaining".to_string(), remaining);
m.insert("status".to_string(), status);
m.insert("fee".to_string(), fee);
m.insert("trades".to_string(), Value::Null);
m
}), &[marketResolved]);
Value::Null
}
pub fn parse_order_time_in_force(&self, mut timeInForce: Value) -> Value {
let mut timeInForces: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("default".to_string(), Value::Str("GTC".into()));
m.insert("ioc".to_string(), Value::Str("IOC".into()));
m.insert("fok".to_string(), Value::Str("FOK".into()));
m.insert("post_only".to_string(), Value::Str("PO".into()));
m
});
return self.safe_string(timeInForces, timeInForce.clone(), &[timeInForce.clone()]);
Value::Null
}
pub fn convert_to_x18(&self, mut value: Value) -> Value {
if (value == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" convertToX18() requires a value".into()))));
}
return crate::precise::Precise::stringDivPrec(&crate::precise::Precise::stringMul(&value, &Value::Str("1000000000000000000".into())), &Value::Str("1".into()), &Value::Int(0));
Value::Null
}
pub fn parse_x18(&self, mut value: Value) -> Value {
if (value == Value::Null) {
return Value::Null;
}
return self.parse_number(crate::precise::Precise::stringDiv(&value, &Value::Str("1000000000000000000".into())), &[]);
Value::Null
}
pub fn create_order_nonce(&self, mut recvWindow: Value) -> Option<String> {
let mut expires: Value = self.sum(&[self.milliseconds(), recvWindow]);
let mut highBits: Value = crate::precise::Precise::stringMul(&self.number_to_string(expires), &Value::Str("1048576".into()));
// the exchange defines the nonce to be the recv time moved left by 20 bits
// plus a random value on the low bits, otherwise two orders created
// during the same millisecond would collide on the same nonce and get rejected
let mut entropy: Value = self.rand_number(Value::Int(6));
return crate::precise::Precise::stringAdd(&highBits, &self.number_to_string(entropy)).as_str().map(str::to_owned);
}
pub fn create_order_appendix(&self, mut isTriggerOrder: Value, optional_args: &[Value]) -> Option<String> {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// | value | builder | builder fee rate | reserved | trigger | reduce only | order type | isolated | version |
// | 64 bits | 16 bits | 10 bits | 24 bits | 2 bits | 1 bit | 2 bits | 1 bit | 8 bits |
// | 127..64 | 63..48 | 47..38 | 37..14 | 13..12 | 11 | 10..9 | 8 | 7..0 |
let mut reduceOnly: Value = self.safe_bool_k(params.clone(), "reduceOnly", &[Value::Bool(false)]);
let mut postOnly: Value = self.is_post_only(Value::Bool(false), Value::Null, &[params.clone()]);
let mut timeInForce: Option<String> = self.safe_string_upper_k(params, "timeInForce", &[]).as_str().map(str::to_owned);
let mut orderType: Value = Value::Int(0);
if (timeInForce.as_deref() == Some("IOC")) {
orderType = Value::Int(1);
} else if (timeInForce.as_deref() == Some("FOK")) {
orderType = Value::Int(2);
} else if is_true(&postOnly) || (timeInForce.as_deref() == Some("PO")) {
orderType = Value::Int(3);
} else if (timeInForce.is_some()) && (timeInForce.as_deref() != Some("GTC")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrder() only supports timeInForce values GTC, IOC, FOK, or PO".into()))));
}
let mut appendix: Value = Value::Str("1".into()); // version
if (orderType.as_f64() != Some(0.0)) {
appendix = crate::precise::Precise::stringAdd(&appendix, &crate::precise::Precise::stringMul(&self.number_to_string(orderType), &Value::Str("512".into())));
}
if (reduceOnly.as_bool() == Some(true)) {
appendix = crate::precise::Precise::stringAdd(&appendix, &Value::Str("2048".into()));
}
let mut buildFee: Value = self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(true)]);
if (buildFee.as_bool() == Some(true)) {
let mut builder: Value = self.safe_string_k(self.options.clone(), "builder", &[Value::Str("4500".into())]);
let mut builderFeeRate: Value = self.safe_string_k(self.options.clone(), "feeRate", &[Value::Str("10".into())]); // 10 units = 0.01%
appendix = crate::precise::Precise::stringAdd(&appendix, &crate::precise::Precise::stringMul(&builder, &Value::Str("281474976710656".into()))); // 1<<48
appendix = crate::precise::Precise::stringAdd(&appendix, &crate::precise::Precise::stringMul(&builderFeeRate, &Value::Str("274877906944".into()))); // 1<<32
}
if (isTriggerOrder.as_bool() == Some(true)) {
appendix = crate::precise::Precise::stringAdd(&appendix, &Value::Str("4096".into()));
}
return appendix.as_str().map(str::to_owned);
}
pub fn create_subaccount(&self, mut walletAddress: Value, optional_args: &[Value]) -> Value {
let mut subaccount = get_arg(optional_args, 0, Value::Str("default".into()));
if (walletAddress == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createSubaccount() requires walletAddress".into()))));
}
let mut subaccountName: Value = (if (subaccount == Value::Null) { Value::Str("default".into()) } else { subaccount });
let mut address: Value = to_lower(&self.remove0x_prefix(walletAddress));
if (Value::Int(address.len() as i64).as_f64() != Some(40.0)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a 20-byte walletAddress".into()))));
}
let mut encoded: Value = self.remove0x_prefix(self.string_to_base16(subaccountName));
if ((encoded.len() as i64) as f64) > ((24i64) as f64) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrder() subaccount must fit in 12 bytes".into()))));
}
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), address).into()), self.pad_hex(encoded, Value::Int(24), &[Value::Bool(false)]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)).into());
Value::Null
}
pub async fn query_contracts(&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 cachedContracts: Value = self.safe_dict_k(self.options.clone(), "gatewayContracts", &[]);
if (cachedContracts != Value::Null) {
return cachedContracts;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("contracts".into()));
m
});
let __ws_arg_19 = self.extend(request, &[params]);
let mut response: Value = self.gateway_public_get_query(&[__ws_arg_19]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("gatewayContracts".into(), data.clone()); }
return data;
Value::Null
}
pub fn order_verifying_contract(&self, mut productId: Value) -> Value {
return Value::Str(format!("{}{}", Value::Str("0x".into()), self.pad_hex(self.int_to_base16(productId, &[]), Value::Int(40), &[]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)).into());
Value::Null
}
pub fn pad_hex(&self, mut value: Value, mut length: Value, optional_args: &[Value]) -> Option<String> {
let mut left = get_arg(optional_args, 0, Value::Bool(true));
if (length == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" padHex() requires length".into()))));
}
let mut zeros: Value = Value::Str("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into());
let mut padded: Value = Value::Null;
if is_true(&left) {
padded = (Value::Str(format!("{}{}", zeros, value).into()));
} else {
padded = (Value::Str(format!("{}{}", value, zeros).into()));
}
if is_true(&left) {
let mut start: Value = (match (&(Value::Int(padded.len() as i64)), &(length)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
return slice(&padded, &start, &Value::Int(padded.len() as i64)).as_str().map(str::to_owned);
}
return slice(&padded, &Value::Int(0), &length).as_str().map(str::to_owned);
}
pub fn sign_order(&self, mut order: Value, mut productId: Value, mut chainId: Value) -> Option<String> {
let mut domain: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("Nado".into()));
m.insert("version".to_string(), Value::Str("0.0.1".into()));
m.insert("chainId".to_string(), chainId);
m.insert("verifyingContract".to_string(), self.order_verifying_contract(productId));
m
});
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Order".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("sender".into()));
m.insert("type".to_string(), Value::Str("bytes32".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("priceX18".into()));
m.insert("type".to_string(), Value::Str("int128".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("amount".into()));
m.insert("type".to_string(), Value::Str("int128".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("expiration".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("appendix".into()));
m.insert("type".to_string(), Value::Str("uint128".into()));
m
})]));
m
});
let mut encoded: Value = self.eth_encode_structured_data(domain, messageTypes, order);
let mut hash: Value = Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(encoded, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into());
return self.sign_hash(hash, self.privateKey.clone()).as_str().map(str::to_owned);
}
pub fn sign_cancellation(&self, mut cancellation: Value, mut chainId: Value, mut endpointAddress: Value) -> Option<String> {
let mut domain: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("Nado".into()));
m.insert("version".to_string(), Value::Str("0.0.1".into()));
m.insert("chainId".to_string(), chainId);
m.insert("verifyingContract".to_string(), endpointAddress);
m
});
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Cancellation".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("sender".into()));
m.insert("type".to_string(), Value::Str("bytes32".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("productIds".into()));
m.insert("type".to_string(), Value::Str("uint32[]".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("digests".into()));
m.insert("type".to_string(), Value::Str("bytes32[]".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
let mut encoded: Value = self.eth_encode_structured_data(domain, messageTypes, cancellation);
let mut hash: Value = Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(encoded, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into());
return self.sign_hash(hash, self.privateKey.clone()).as_str().map(str::to_owned);
}
pub fn sign_cancellation_products(&self, mut cancellation: Value, mut chainId: Value, mut endpointAddress: Value) -> Option<String> {
let mut domain: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("Nado".into()));
m.insert("version".to_string(), Value::Str("0.0.1".into()));
m.insert("chainId".to_string(), chainId);
m.insert("verifyingContract".to_string(), endpointAddress);
m
});
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CancellationProducts".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("sender".into()));
m.insert("type".to_string(), Value::Str("bytes32".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("productIds".into()));
m.insert("type".to_string(), Value::Str("uint32[]".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
let mut encoded: Value = self.eth_encode_structured_data(domain, messageTypes, cancellation);
let mut hash: Value = Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(encoded, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into());
return self.sign_hash(hash, self.privateKey.clone()).as_str().map(str::to_owned);
}
pub fn sign_fetch_trigger_orders(&self, mut tx: Value, mut chainId: Value, mut endpointAddress: Value) -> Option<String> {
let mut domain: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("Nado".into()));
m.insert("version".to_string(), Value::Str("0.0.1".into()));
m.insert("chainId".to_string(), chainId);
m.insert("verifyingContract".to_string(), endpointAddress);
m
});
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ListTriggerOrders".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("sender".into()));
m.insert("type".to_string(), Value::Str("bytes32".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("recvTime".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
let mut encoded: Value = self.eth_encode_structured_data(domain, messageTypes, tx);
let mut hash: Value = Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(encoded, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into());
return self.sign_hash(hash, self.privateKey.clone()).as_str().map(str::to_owned);
}
pub fn sign_hash(&self, mut hash: Value, mut privateKey: Value) -> Value {
if (privateKey == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" signHash() requires privateKey".into()))));
}
let mut signature: Value = ecdsa(hash.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null), privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null), Value::Str("secp256k1".into()), Value::Null);
let mut r: Value = signature.as_map().and_then(|__m| __m.get("r")).cloned().unwrap_or(Value::Null);
let mut s: Value = signature.as_map().and_then(|__m| __m.get("s")).cloned().unwrap_or(Value::Null);
let mut v: Value = to_lower(&self.int_to_base16(self.sum(&[Value::Int(27), signature.as_map().and_then(|__m| __m.get("v")).cloned().unwrap_or(Value::Null)]), &[]));
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), self.pad_hex(r, Value::Int(64), &[]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)).into()), self.pad_hex(s, Value::Int(64), &[]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)).into()), v).into());
Value::Null
}
pub fn remove_market_suffix(&self, mut marketId: Value) -> Value {
if (marketId == Value::Null) {
return Value::Null;
}
if (ends_with(&marketId, &Value::Str("-PERP".into()))) {
return marketId.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(0); let __j = (__l - 5).max(0); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
}
return marketId;
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![]));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut requestBody: Value = Value::Null;
let mut endpoint: Value = get_value(&api, &Value::Int(0));
if matches!(&api, Value::Str(_)) {
endpoint = api.clone();
}
let mut baseApiUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), endpoint.clone(), &[]);
if (baseApiUrl == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
let mut url: Value = baseApiUrl;
if (path.as_str() != Some("")) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("/".into()), self.implode_params(path.clone(), params.clone())).into())).into());
}
let mut query: Value = self.omit(params, self.extract_params(path), &[]);
let mut headersValue: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (endpoint.as_str() == Some("gateway")) || (endpoint.as_str() == Some("archive")) {
if let Value::Dict(__d) = &mut headersValue { std::sync::Arc::make_mut(__d).insert("Accept-Encoding".into(), Value::Str("gzip, br, deflate".into())); }
}
if (method.as_str() == Some("GET")) {
if ((object_keys(&query).len() as i64) as f64) > ((0i64) as f64) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into())).into());
}
} else {
if let Value::Dict(__d) = &mut headersValue { std::sync::Arc::make_mut(__d).insert("Content-Type".into(), Value::Str("application/json".into())); }
requestBody = json_stringify(&query);
}
let mut bodyResult: Value = (if (requestBody != Value::Null) { requestBody } else { body });
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), bodyResult);
m.insert("headers".to_string(), headersValue);
m
});
Value::Null
}
pub fn handle_errors(&self, mut httpCode: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) || (response == Value::Null) {
return Value::Null;
}
//
// {
// "status": "failure",
// "signature": "0x...",
// "error_code": 2007,
// "error": "Order price must be within a range of 80% to 120% of oracle price.",
// "request_type": "execute_place_order"
// }
//
let mut status: Option<String> = self.safe_string_k(response.clone(), "status", &[]).as_str().map(str::to_owned);
let mut errorCode: Value = self.safe_string_k(response.clone(), "error_code", &[]);
let mut error: Value = self.safe_string_k(response, "error", &[]);
if (status.as_deref() == Some("failure")) || (errorCode != Value::Null) || (error != Value::Null) {
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorCode, feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), error, feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
}