// 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 DigifinexCore {
pub exchange: crate::exchange::Exchange,
}
impl DigifinexCore {
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 = DigifinexCore::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 DigifinexCore {
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_order(self, order, &[market])
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_funding_rate(self, rate, &[market])
}
fn parse_deposit_address(&self, depositAddress: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_deposit_address(self, depositAddress, &[currency])
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_ledger_entry(self, entry, &[currency])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_transfer(self, transfer, &[currency])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_currency(self, currency)
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_margin_modification(self, data, &[market])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_transaction(self, transaction, &[currency])
}
fn parse_borrow_interest(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_borrow_interest(self, info, &[market])
}
fn parse_income(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_income(self, info, &[market])
}
fn parse_borrow_rate(&self, info: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_borrow_rate(self, info, &[currency])
}
fn parse_market_leverage_tiers(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DigifinexCore.
DigifinexCore::parse_market_leverage_tiers(self, info, &[market])
}
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 DigifinexCore.
DigifinexCore::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 DigifinexCore.
DigifinexCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for DigifinexCore {
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 {
"add_margin" => self.add_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).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_for_symbols" => self.cancel_orders_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_market_buy_order_with_cost" => self.create_market_buy_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"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())..]),
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_borrow_interest" => self.fetch_borrow_interest(&args[..]).await,
"fetch_cross_borrow_rate" => self.fetch_cross_borrow_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_cross_borrow_rates" => self.fetch_cross_borrow_rates(&args[..]).await,
"fetch_currencies" => self.fetch_currencies(&args[..]).await,
"fetch_deposit_address" => self.fetch_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposit_withdraw_fees" => self.fetch_deposit_withdraw_fees(&args[..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_funding_history" => self.fetch_funding_history(&args[..]).await,
"fetch_funding_interval" => self.fetch_funding_interval(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_rate_history" => self.fetch_funding_rate_history(&args[..]).await,
"fetch_ledger" => self.fetch_ledger(&args[..]).await,
"fetch_leverage_tiers" => self.fetch_leverage_tiers(&args[..]).await,
"fetch_market_leverage_tiers" => self.fetch_market_leverage_tiers(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_markets_v1" => self.fetch_markets_v1(&args[..]).await,
"fetch_markets_v2" => self.fetch_markets_v2(&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_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_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_trading_fee" => self.fetch_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_transactions_by_type" => self.fetch_transactions_by_type(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_transfers" => self.fetch_transfers(&args[..]).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)),
"handle_margin_mode_and_params" => self.handle_margin_mode_and_params(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"modify_margin_helper" => self.modify_margin_helper(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,
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_borrow_interest" => self.parse_borrow_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_borrow_rate" => self.parse_borrow_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_borrow_rates" => self.parse_borrow_rates(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_cancel_orders" => self.parse_cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_currency" => self.parse_currency(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_deposit_address" => self.parse_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_deposit_withdraw_fees" => self.parse_deposit_withdraw_fees(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_income" => self.parse_income(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ledger_entry" => self.parse_ledger_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ledger_entry_type" => self.parse_ledger_entry_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_margin_modification" => self.parse_margin_modification(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_market_leverage_tiers" => self.parse_market_leverage_tiers(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_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order_status" => self.parse_order_status(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_trading_fee" => self.parse_trading_fee(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_transaction_status" => self.parse_transaction_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"reduce_margin" => self.reduce_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_margin_mode" => self.set_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"transfer" => self.transfer(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,
"withdraw" => self.withdraw(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,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for DigifinexCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for DigifinexCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl DigifinexCore {
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("digifinex".into()));
m.insert("name".to_string(), Value::Str("DigiFinex".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("SG".into())]));
m.insert("version".to_string(), Value::Str("v3".into()));
m.insert("rateLimit".to_string(), Value::Int(900));
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("addMargin".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("cancelOrdersForSymbols".to_string(), Value::Bool(true));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(true));
m.insert("createMarketOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketSellOrderWithCost".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(true));
m.insert("createPostOnlyOrder".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("createStopLimitOrder".to_string(), Value::Bool(false));
m.insert("createStopMarketOrder".to_string(), Value::Bool(false));
m.insert("createStopOrder".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBorrowInterest".to_string(), Value::Bool(true));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(true));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(true));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDepositAddress".to_string(), Value::Bool(true));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDepositAddressesByNetwork".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchDepositWithdrawFee".to_string(), Value::Str("emulated".into()));
m.insert("fetchDepositWithdrawFees".to_string(), Value::Bool(true));
m.insert("fetchFundingHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingInterval".to_string(), Value::Bool(true));
m.insert("fetchFundingIntervals".to_string(), Value::Bool(false));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(false));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(true));
m.insert("fetchLeverage".to_string(), Value::Bool(false));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(true));
m.insert("fetchMarginMode".to_string(), Value::Bool(false));
m.insert("fetchMarketLeverageTiers".to_string(), Value::Bool(true));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(false));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".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("fetchPosition".to_string(), Value::Bool(true));
m.insert("fetchPositionMode".to_string(), Value::Bool(false));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsRisk".to_string(), Value::Bool(false));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
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("fetchTradingFee".to_string(), Value::Bool(true));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchTransfers".to_string(), Value::Bool(true));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("reduceMargin".to_string(), Value::Bool(true));
m.insert("setLeverage".to_string(), Value::Bool(true));
m.insert("setMargin".to_string(), Value::Bool(false));
m.insert("setMarginMode".to_string(), Value::Bool(true));
m.insert("setPositionMode".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(true));
m.insert("withdraw".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1".into()));
m.insert("5m".to_string(), Value::Str("5".into()));
m.insert("15m".to_string(), Value::Str("15".into()));
m.insert("30m".to_string(), Value::Str("30".into()));
m.insert("1h".to_string(), Value::Str("60".into()));
m.insert("4h".to_string(), Value::Str("240".into()));
m.insert("12h".to_string(), Value::Str("720".into()));
m.insert("1d".to_string(), Value::Str("1D".into()));
m.insert("1w".to_string(), Value::Str("1W".into()));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://user-images.githubusercontent.com/51840849/87443315-01283a00-c5fe-11ea-8628-c2a0feaf07ac.jpg".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rest".to_string(), Value::Str("https://openapi.digifinex.com".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://www.digifinex.com".into()));
m.insert("doc".to_string(), Value::from(vec![Value::Str("https://docs.digifinex.com".into())]));
m.insert("fees".to_string(), Value::Str("https://digifinex.zendesk.com/hc/en-us/articles/360000328422-Fee-Structure-on-DigiFinex".into()));
m.insert("referral".to_string(), Value::Str("https://www.digifinex.com/en-ww/from/DhOzBg?channelCode=ljaUPp".into()));
m
}));
m.insert("api".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("spot".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("{market}/symbols".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("kline".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("margin/currencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("margin/symbols".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("order_book".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("ping".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/symbols".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("time".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("trades/symbols".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("ticker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("currencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("swap".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("public/api_weight".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/candles_history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/depth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/funding_rate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/funding_rate_history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/instrument".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/instruments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/ticker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/tickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".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("{market}/financelog".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("{market}/mytrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("{market}/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("{market}/order/detail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("{market}/order/current".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("{market}/order/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("margin/assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("margin/financelog".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("margin/mytrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("margin/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("margin/order/current".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("margin/order/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("margin/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("otc/financelog".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/financelog".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/mytrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/order/current".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/order/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("deposit/address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("deposit/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("withdraw/history".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("{market}/order/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("{market}/order/new".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("{market}/order/batch_new".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("margin/order/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("margin/order/new".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("margin/position/close".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/order/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/order/new".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("withdraw/new".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("withdraw/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("swap".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("account/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/finance_record".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/trading_fee_rate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/transfer_record".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/funding_fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/history_orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/history_trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/open_orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/order_info".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("account/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/position_mode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/position_margin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/batch_cancel_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/batch_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/cancel_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/order_place".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("follow/sponsor_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("follow/close_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("follow/cancel_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("follow/user_center_current".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("follow/user_center_history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("follow/expert_current_open_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("follow/add_algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("follow/cancel_algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("follow/account_available".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("follow/plan_task".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("follow/instrument_list".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("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("default".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandbox".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(true));
m.insert("triggerPrice".to_string(), Value::Bool(false));
m.insert("triggerPriceType".to_string(), Value::Null);
m.insert("triggerDirection".to_string(), Value::Bool(false));
m.insert("stopLossPrice".to_string(), Value::Bool(false));
m.insert("takeProfitPrice".to_string(), Value::Bool(false));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Null);
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("IOC".to_string(), Value::Bool(false));
m.insert("FOK".to_string(), Value::Bool(false));
m.insert("PO".to_string(), Value::Bool(true));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("iceberg".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("max".to_string(), Value::Int(10));
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(true));
m.insert("limit".to_string(), Value::Int(500));
m.insert("daysBack".to_string(), Value::Int(100000));
m.insert("untilDays".to_string(), Value::Int(30));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(true));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("marketType".to_string(), Value::Bool(true));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(true));
m.insert("limit".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(true));
m.insert("limit".to_string(), Value::Int(100));
m.insert("daysBack".to_string(), Value::Int(100000));
m.insert("untilDays".to_string(), Value::Int(30));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Null);
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(500));
m
}));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m.insert("forDerivatives".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m.insert("createOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("max".to_string(), Value::Int(20));
m.insert("marginMode".to_string(), Value::Bool(false));
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(100));
m.insert("daysBack".to_string(), Value::Int(100000));
m.insert("untilDays".to_string(), Value::Int(100000));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(100));
m
}));
m.insert("fetchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("daysBack".to_string(), Value::Int(100000));
m
}));
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(100));
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forDerivatives".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forDerivatives".into()));
m
}));
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m
}));
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.002".into()), &[]));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.002".into()), &[]));
m
}));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
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("10001".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("Wrong request method, please check it's a GET ot POST request".into())]));
m.insert("10002".to_string(), Value::from(vec![Value::Str("AuthenticationError".into()), Value::Str("Invalid ApiKey".into())]));
m.insert("10003".to_string(), Value::from(vec![Value::Str("AuthenticationError".into()), Value::Str("Sign doesn't match".into())]));
m.insert("10004".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("Illegal request parameters".into())]));
m.insert("10005".to_string(), Value::from(vec![Value::Str("DDoSProtection".into()), Value::Str("Request frequency exceeds the limit".into())]));
m.insert("10006".to_string(), Value::from(vec![Value::Str("PermissionDenied".into()), Value::Str("Unauthorized to execute this request".into())]));
m.insert("10007".to_string(), Value::from(vec![Value::Str("PermissionDenied".into()), Value::Str("IP address Unauthorized".into())]));
m.insert("10008".to_string(), Value::from(vec![Value::Str("InvalidNonce".into()), Value::Str("Timestamp for this request is invalid, timestamp must within 1 minute".into())]));
m.insert("10009".to_string(), Value::from(vec![Value::Str("NetworkError".into()), Value::Str("Unexist endpoint, please check endpoint URL".into())]));
m.insert("10011".to_string(), Value::from(vec![Value::Str("AccountSuspended".into()), Value::Str("ApiKey expired. Please go to client side to re-create an ApiKey".into())]));
m.insert("20001".to_string(), Value::from(vec![Value::Str("PermissionDenied".into()), Value::Str("Trade is not open for this trading pair".into())]));
m.insert("20002".to_string(), Value::from(vec![Value::Str("PermissionDenied".into()), Value::Str("Trade of this trading pair is suspended".into())]));
m.insert("20003".to_string(), Value::from(vec![Value::Str("InvalidOrder".into()), Value::Str("Invalid price or amount".into())]));
m.insert("20007".to_string(), Value::from(vec![Value::Str("InvalidOrder".into()), Value::Str("Price precision error".into())]));
m.insert("20008".to_string(), Value::from(vec![Value::Str("InvalidOrder".into()), Value::Str("Amount precision error".into())]));
m.insert("20009".to_string(), Value::from(vec![Value::Str("InvalidOrder".into()), Value::Str("Amount is less than the minimum requirement".into())]));
m.insert("20010".to_string(), Value::from(vec![Value::Str("InvalidOrder".into()), Value::Str("Cash Amount is less than the minimum requirement".into())]));
m.insert("20011".to_string(), Value::from(vec![Value::Str("InsufficientFunds".into()), Value::Str("Insufficient balance".into())]));
m.insert("20012".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("Invalid trade type, valid value: buy/sell)".into())]));
m.insert("20013".to_string(), Value::from(vec![Value::Str("InvalidOrder".into()), Value::Str("No order info found".into())]));
m.insert("20014".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("Invalid date, Valid format: 2018-07-25)".into())]));
m.insert("20015".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("Date exceeds the limit".into())]));
m.insert("20018".to_string(), Value::from(vec![Value::Str("PermissionDenied".into()), Value::Str("Your trading rights have been banned by the system".into())]));
m.insert("20019".to_string(), Value::from(vec![Value::Str("BadSymbol".into()), Value::Str("Wrong trading pair symbol. Correct format:\"usdt_btc\". Quote asset is in the front".into())]));
m.insert("20020".to_string(), Value::from(vec![Value::Str("DDoSProtection".into()), Value::Str("You have violated the API operation trading rules and temporarily forbid trading. At present, we have certain restrictions on the user's transaction rate and withdrawal rate.".into())]));
m.insert("50000".to_string(), Value::from(vec![Value::Str("ExchangeError".into()), Value::Str("Exception error".into())]));
m.insert("20021".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("Invalid currency".into())]));
m.insert("20022".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("The ending timestamp must be larger than the starting timestamp".into())]));
m.insert("20023".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("Invalid transfer type".into())]));
m.insert("20024".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("Invalid amount".into())]));
m.insert("20025".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("This currency is not transferable at the moment".into())]));
m.insert("20026".to_string(), Value::from(vec![Value::Str("InsufficientFunds".into()), Value::Str("Transfer amount exceed your balance".into())]));
m.insert("20027".to_string(), Value::from(vec![Value::Str("PermissionDenied".into()), Value::Str("Abnormal account status".into())]));
m.insert("20028".to_string(), Value::from(vec![Value::Str("PermissionDenied".into()), Value::Str("Blacklist for transfer".into())]));
m.insert("20029".to_string(), Value::from(vec![Value::Str("PermissionDenied".into()), Value::Str("Transfer amount exceed your daily limit".into())]));
m.insert("20030".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("You have no position on this trading pair".into())]));
m.insert("20032".to_string(), Value::from(vec![Value::Str("PermissionDenied".into()), Value::Str("Withdrawal limited".into())]));
m.insert("20033".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("Wrong Withdrawal ID".into())]));
m.insert("20034".to_string(), Value::from(vec![Value::Str("PermissionDenied".into()), Value::Str("Withdrawal service of this crypto has been closed".into())]));
m.insert("20035".to_string(), Value::from(vec![Value::Str("PermissionDenied".into()), Value::Str("Withdrawal limit".into())]));
m.insert("20036".to_string(), Value::from(vec![Value::Str("ExchangeError".into()), Value::Str("Withdrawal cancellation failed".into())]));
m.insert("20037".to_string(), Value::from(vec![Value::Str("InvalidAddress".into()), Value::Str("The withdrawal address, Tag or chain type is not included in the withdrawal management list".into())]));
m.insert("20038".to_string(), Value::from(vec![Value::Str("InvalidAddress".into()), Value::Str("The withdrawal address is not on the white list".into())]));
m.insert("20039".to_string(), Value::from(vec![Value::Str("ExchangeError".into()), Value::Str("Can't be canceled in current status".into())]));
m.insert("20040".to_string(), Value::from(vec![Value::Str("RateLimitExceeded".into()), Value::Str("Withdraw too frequently; limitation: 3 times a minute, 100 times a day".into())]));
m.insert("20041".to_string(), Value::from(vec![Value::Str("PermissionDenied".into()), Value::Str("Beyond the daily withdrawal limit".into())]));
m.insert("20042".to_string(), Value::from(vec![Value::Str("BadSymbol".into()), Value::Str("Current trading pair does not support API trading".into())]));
m.insert("400002".to_string(), Value::from(vec![Value::Str("BadRequest".into()), Value::Str("Invalid Parameter".into())]));
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultType".to_string(), Value::Str("spot".into()));
m.insert("types".to_string(), Value::from(vec![Value::Str("spot".into()), Value::Str("margin".into()), Value::Str("otc".into())]));
m.insert("createMarketBuyOrderRequiresPrice".to_string(), Value::Bool(true));
m.insert("accountsByType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("1".into()));
m.insert("margin".to_string(), Value::Str("2".into()));
m.insert("OTC".to_string(), Value::Str("3".into()));
m
}));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ARBITRUM".to_string(), Value::Str("Arbitrum".into()));
m.insert("AVALANCEC".to_string(), Value::Str("AVAX-CCHAIN".into()));
m.insert("AVALANCEX".to_string(), Value::Str("AVAX-XCHAIN".into()));
m.insert("BEP20".to_string(), Value::Str("BEP20".into()));
m.insert("BSC".to_string(), Value::Str("BEP20".into()));
m.insert("CARDANO".to_string(), Value::Str("Cardano".into()));
m.insert("CELO".to_string(), Value::Str("Celo".into()));
m.insert("CHILIZ".to_string(), Value::Str("Chiliz".into()));
m.insert("COSMOS".to_string(), Value::Str("COSMOS".into()));
m.insert("CRC20".to_string(), Value::Str("Crypto.com".into()));
m.insert("CRONOS".to_string(), Value::Str("Crypto.com".into()));
m.insert("DOGECOIN".to_string(), Value::Str("DogeChain".into()));
m.insert("ERC20".to_string(), Value::Str("ERC20".into()));
m.insert("ETH".to_string(), Value::Str("ERC20".into()));
m.insert("ETHW".to_string(), Value::Str("ETHW".into()));
m.insert("IOTA".to_string(), Value::Str("MIOTA".into()));
m.insert("KLAYTN".to_string(), Value::Str("KLAY".into()));
m.insert("METIS".to_string(), Value::Str("MetisDAO".into()));
m.insert("MOONBEAM".to_string(), Value::Str("GLMR".into()));
m.insert("MOONRIVER".to_string(), Value::Str("Moonriver".into()));
m.insert("OPTIMISM".to_string(), Value::Str("OPETH".into()));
m.insert("POLYGON".to_string(), Value::Str("Polygon".into()));
m.insert("MATIC".to_string(), Value::Str("Polygon".into()));
m.insert("RIPPLE".to_string(), Value::Str("XRP".into()));
m.insert("SOL".to_string(), Value::Str("SOL".into()));
m.insert("XLM".to_string(), Value::Str("Stella".into()));
m.insert("TERRACLASSIC".to_string(), Value::Str("TerraClassic".into()));
m.insert("TERRA".to_string(), Value::Str("Terra".into()));
m.insert("TON".to_string(), Value::Str("Ton".into()));
m.insert("TRC20".to_string(), Value::Str("TRC20".into()));
m.insert("TRX".to_string(), Value::Str("TRC20".into()));
m.insert("VECHAIN".to_string(), Value::Str("Vechain".into()));
m
}));
m.insert("networksById".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("TRC20".to_string(), Value::Str("TRC20".into()));
m.insert("TRX".to_string(), Value::Str("TRC20".into()));
m.insert("BEP20".to_string(), Value::Str("BEP20".into()));
m.insert("BSC".to_string(), Value::Str("BEP20".into()));
m.insert("ERC20".to_string(), Value::Str("ERC20".into()));
m.insert("ETH".to_string(), Value::Str("ERC20".into()));
m.insert("Polygon".to_string(), Value::Str("POLYGON".into()));
m.insert("Crypto.com".to_string(), Value::Str("CRONOS".into()));
m
}));
m
}));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("BHT".to_string(), Value::Str("Black House Test".into()));
m.insert("EPS".to_string(), Value::Str("Epanus".into()));
m.insert("FREE".to_string(), Value::Str("FreeRossDAO".into()));
m.insert("MBN".to_string(), Value::Str("Mobilian Coin".into()));
m.insert("TEL".to_string(), Value::Str("TEL666".into()));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name digifinex#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-currency-deposit-and-withdrawal-information
* @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.public_spot_get_currencies(&[params]).await;
//
// {
// "data":[
// {
// "deposit_status":1,
// "min_deposit_amount":10,
// "withdraw_fee_rate":0,
// "min_withdraw_amount":10,
// "min_withdraw_fee":5,
// "currency":"USDT",
// "withdraw_fee_currency":"USDT",
// "withdraw_status":0,
// "chain":"OMNI"
// },
// {
// "deposit_status":1,
// "min_deposit_amount":10,
// "withdraw_fee_rate":0,
// "min_withdraw_amount":10,
// "min_withdraw_fee":3,
// "currency":"USDT",
// "withdraw_fee_currency":"USDT",
// "withdraw_status":1,
// "chain":"ERC20"
// },
// {
// "deposit_status":0,
// "min_deposit_amount":0,
// "withdraw_fee_rate":0,
// "min_withdraw_amount":0,
// "min_withdraw_fee":0,
// "currency":"DGF13",
// "withdraw_fee_currency":"DGF13",
// "withdraw_status":0,
// "chain":""
// },
// ],
// "code":200
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut groupedById: Value = self.group_by(data, Value::Str("currency".into()), &[]);
let mut values: Value = object_values(&groupedById);
return self.parse_currencies(values);
Value::Null
}
pub fn parse_currency(&self, mut rawCurrency: Value) -> Value {
let mut networkEntries: Value = rawCurrency;
let mut firstEntry: Value = self.safe_dict(networkEntries.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); // it must have at least one entry
let mut id: Value = self.safe_string_k(firstEntry, "currency", &[]);
let mut code: Value = self.safe_currency_code(id.clone(), &[]);
let mut networks: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut j: Value = Value::Int(0);
let mut __for_first_636: bool = true;
while { if !__for_first_636 { 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_636 = false; j.as_f64().unwrap_or(f64::NAN) < ((networkEntries.len() as i64) as f64) } {
let mut networkEntry: Value = networkEntries.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 networkId: Value = self.safe_string2(networkEntry.clone(), Value::Str("chain".into()), Value::Str("currency".into()), &[]);
let mut networkCode: Value = self.network_id_to_code(&[networkId.clone(), code.clone()]);
if (networkCode != Value::Null) {
if let Value::Dict(__d) = &mut networks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&networkCode), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), networkId);
m.insert("network".to_string(), networkCode.clone());
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), Value::Bool(self.safe_integer_k(networkEntry.clone(), "deposit_status", &[]).as_f64() == Some(1.0)));
m.insert("withdraw".to_string(), Value::Bool(self.safe_integer_k(networkEntry.clone(), "withdraw_status", &[]).as_f64() == Some(1.0)));
m.insert("fee".to_string(), self.safe_number_k(networkEntry.clone(), "min_withdraw_fee", &[]));
m.insert("precision".to_string(), Value::Null);
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(networkEntry.clone(), "min_withdraw_amount", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(networkEntry.clone(), "min_deposit_amount", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("info".to_string(), networkEntry);
m
})); }
}
}
}
return self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("code".to_string(), code);
m.insert("info".to_string(), networkEntries);
m.insert("networks".to_string(), networks);
m
}));
Value::Null
}
/*
* @method
* @name digifinex#fetchMarkets
* @description retrieves data on all markets for digifinex
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#all-the-market-description
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#spot-trading-pair-symbol
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#margin-trading-pair-symbol
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#instruments
* @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 options: Value = self.safe_dict_k(self.options.clone(), "fetchMarkets", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut method: Option<String> = self.safe_string_k(options, "method", &[Value::Str("fetch_markets_v2".into())]).as_str().map(str::to_owned);
if (method.as_deref() == Some("fetch_markets_v2")) {
return self.fetch_markets_v2(&[params.clone()]).await;
}
return self.fetch_markets_v1(&[params]).await;
Value::Null
}
pub async fn fetch_markets_v2(&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 defaultType: Option<String> = self.safe_string_k(self.options.clone(), "defaultType", &[]).as_str().map(str::to_owned);
let mut marginModequeryVariable = self.handle_margin_mode_and_params(Value::Str("fetchMarketsV2".into()), &[params.clone()]);
let mut marginMode: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut promisesRaw: Value = Value::from(vec![]);
if (marginMode != Value::Null) {
append_to_array(&mut promisesRaw, self.public_spot_get_margin_symbols(&[query.clone()]).await);
} else {
append_to_array(&mut promisesRaw, self.public_spot_get_trades_symbols(&[query]).await);
}
append_to_array(&mut promisesRaw, self.public_swap_get_public_instruments(&[params]).await);
let mut promises: Value = promise_all(&promisesRaw).await;
let mut spotMarkets: Value = self.safe_dict(promises.clone(), Value::Int(0), &[]);
let mut swapMarkets: Value = self.safe_dict(promises, Value::Int(1), &[]);
//
// spot and margin
//
// {
// "symbol_list":[
// {
// "order_types":["LIMIT","MARKET"],
// "quote_asset":"USDT",
// "minimum_value":2,
// "amount_precision":4,
// "status":"TRADING",
// "minimum_amount":0.0001,
// "symbol":"BTC_USDT",
// "is_allow":1,
// "zone":"MAIN",
// "base_asset":"BTC",
// "price_precision":2
// }
// ],
// "code":0
// }
//
// swap
//
// {
// "code": 0,
// "data": [
// {
// "instrument_id": "BTCUSDTPERP",
// "type": "REAL",
// "contract_type": "PERPETUAL",
// "base_currency": "BTC",
// "quote_currency": "USDT",
// "clear_currency": "USDT",
// "contract_value": "0.001",
// "contract_value_currency": "BTC",
// "is_inverse": false,
// "is_trading": true,
// "status": "ONLINE",
// "price_precision": 4,
// "tick_size": "0.0001",
// "min_order_amount": 1,
// "open_max_limits": [
// {
// "leverage": "50",
// "max_limit": "1000000"
// }
// ]
// },
// ]
// }
//
let mut spotData: Value = self.safe_list_k(spotMarkets, "symbol_list", &[Value::from(vec![])]);
let mut swapData: Value = self.safe_list_k(swapMarkets, "data", &[Value::from(vec![])]);
let mut response: Value = self.array_concat(spotData, swapData);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_637: bool = true;
while { if !__for_first_637 { 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_637 = false; i.as_f64().unwrap_or(f64::NAN) < ((response.len() as i64) as f64) } {
let mut market: Value = response.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_string2(market.clone(), Value::Str("symbol".into()), Value::Str("instrument_id".into()), &[]);
let mut baseId: Value = self.safe_string2(market.clone(), Value::Str("base_asset".into()), Value::Str("base_currency".into()), &[]);
let mut quoteId: Value = self.safe_string2(market.clone(), Value::Str("quote_asset".into()), Value::Str("quote_currency".into()), &[]);
let mut settleId: Value = self.safe_string_k(market.clone(), "clear_currency", &[]);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
if (base == Value::Null) || (quote == Value::Null) {
continue;
}
let mut settle: Value = self.safe_currency_code(settleId.clone(), &[]);
//
// The status is documented in the exchange API docs as follows:
// TRADING, HALT (delisted), BREAK (trading paused)
// https://docs.digifinex.vip/en-ww/v3/#/public/spot/symbols
// However, all spot markets actually have status === 'HALT'
// despite that they appear to be active on the exchange website.
// Apparently, we can't trust this status.
// const status = this.safeString (market, 'status');
// const active = (status === 'TRADING');
//
let mut isAllowed: Value = self.safe_integer_k(market.clone(), "is_allow", &[Value::Int(1)]);
let mut type_var: Value = (if (defaultType.as_deref() == Some("margin")) { Value::Str("margin".into()) } else { Value::Str("spot".into()) });
let mut spot: Value = Value::Bool(settle == Value::Null);
let mut swap: Value = Value::Bool(!(matches!(&spot, Value::Bool(true))));
let mut margin: Value = (if (marginMode != Value::Null) { Value::Bool(true) } else { Value::Null });
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
let mut isInverse: Value = Value::Null;
let mut isLinear: Value = Value::Null;
if matches!(&swap, Value::Bool(true)) {
type_var = Value::Str("swap".into());
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into()), Value::Str(":".into())).into()), settle).into());
isInverse = self.safe_bool_k(market.clone(), "is_inverse", &[]);
isLinear = (if (isInverse.as_bool() != Some(true)) { Value::Bool(true) } else { Value::Bool(false) });
let mut isTrading: Value = self.safe_bool_k(market.clone(), "isTrading", &[]);
if (isTrading.as_bool() == Some(true)) {
isAllowed = Value::Int(1);
}
}
let mut isActive: Value = (Value::Bool(isAllowed.as_f64() != Some(0.0)));
append_to_array(&mut result, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
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);
m.insert("spot".to_string(), spot);
m.insert("margin".to_string(), margin);
m.insert("swap".to_string(), swap.clone());
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), isActive);
m.insert("contract".to_string(), swap);
m.insert("linear".to_string(), isLinear);
m.insert("inverse".to_string(), isInverse);
m.insert("contractSize".to_string(), self.safe_number_k(market.clone(), "contract_value", &[]));
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(), self.parse_number(self.parse_precision(&[self.safe_string_k(market.clone(), "amount_precision", &[])]), &[]));
m.insert("price".to_string(), self.parse_number(self.parse_precision(&[self.safe_string_k(market.clone(), "price_precision", &[])]), &[]));
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(), self.safe_number2(market.clone(), Value::Str("minimum_amount".into()), Value::Str("min_order_amount".into()), &[]));
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(), self.safe_number_k(market.clone(), "tick_size", &[]));
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(), self.safe_number_k(market.clone(), "minimum_value", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), market);
m
}));
}
}
return result;
Value::Null
}
pub async fn fetch_markets_v1(&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.public_spot_get_markets(&[params]).await;
//
// {
// "data": [
// {
// "volume_precision":4,
// "price_precision":2,
// "market":"btc_usdt",
// "min_amount":2,
// "min_volume":0.0001
// },
// ],
// "date":1564507456,
// "code":0
// }
//
let mut markets: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_638: bool = true;
while { if !__for_first_638 { 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_638 = false; i.as_f64().unwrap_or(f64::NAN) < ((markets.len() as i64) as f64) } {
let mut market: Value = markets.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(), "market", &[]);
if (id == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchMarketsV1() missing id".into()))));
}
let mut baseIdquoteIdVariable = split(&id, &Value::Str("_".into()));
let mut baseId: Value = baseIdquoteIdVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut quoteId: Value = baseIdquoteIdVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
if (base == Value::Null) || (quote == Value::Null) {
continue;
}
append_to_array(&mut result, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("symbol".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into()));
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("spot".into()));
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Null);
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Null);
m.insert("contract".to_string(), Value::Bool(false));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("contractSize".to_string(), 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("price".to_string(), self.parse_number(self.parse_precision(&[self.safe_string_k(market.clone(), "price_precision", &[])]), &[]));
m.insert("amount".to_string(), self.parse_number(self.parse_precision(&[self.safe_string_k(market.clone(), "volume_precision", &[])]), &[]));
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(), self.safe_number_k(market.clone(), "min_volume", &[]));
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(), self.safe_number_k(market.clone(), "min_amount", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("info".to_string(), market);
m
}));
}
}
return result;
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
//
// spot and margin
//
// {
// "currency": "BTC",
// "free": 4723846.89208129,
// "total": 0
// }
//
// swap
//
// {
// "equity": "0",
// "currency": "BTC",
// "margin": "0",
// "frozen_margin": "0",
// "frozen_money": "0",
// "margin_ratio": "0",
// "realized_pnl": "0",
// "avail_balance": "0",
// "unrealized_pnl": "0",
// "time_stamp": 1661487402396
// }
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_639: bool = true;
while { if !__for_first_639 { 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_639 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&response).as_f64().unwrap_or(f64::NAN) } {
let mut balance: Value = self.safe_dict(response.clone(), i.clone(), &[]);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut account: Value = self.account();
let mut free: Value = self.safe_string2(balance.clone(), Value::Str("free".into()), Value::Str("avail_balance".into()), &[]);
let mut total: Value = self.safe_string2(balance, Value::Str("total".into()), Value::Str("equity".into()), &[]);
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), free.clone()); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), crate::precise::Precise::stringSub(&total, &free)); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), total); }
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
}
/*
* @method
* @name digifinex#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#spot-account-assets
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#margin-assets
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#accountbalance
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn 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.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut marketType: Value = Value::Null;
let mut paramsMarketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchBalance".into()), &[Value::Null, params]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsMarketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut marginModequeryVariable = self.handle_margin_mode_and_params(Value::Str("fetchBalance".into()), &[paramsMarketType]);
let mut marginMode: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut response: Value = Value::Null;
if (marginMode != Value::Null) || (marketType.as_str() == Some("margin")) {
marketType = Value::Str("margin".into());
response = self.private_spot_get_margin_assets(&[query.clone()]).await;
} else if (marketType.as_str() == Some("spot")) {
response = self.private_spot_get_spot_assets(&[query.clone()]).await;
} else if (marketType.as_str() == Some("swap")) {
response = self.private_swap_get_account_balance(&[query]).await;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchBalance() not support this market type".into()))));
}
//
// spot and margin
//
// {
// "code": 0,
// "list": [
// {
// "currency": "BTC",
// "free": 4723846.89208129,
// "total": 0
// },
// ...
// ]
// }
//
// swap
//
// {
// "code": 0,
// "data": [
// {
// "equity": "0",
// "currency": "BTC",
// "margin": "0",
// "frozen_margin": "0",
// "frozen_money": "0",
// "margin_ratio": "0",
// "realized_pnl": "0",
// "avail_balance": "0",
// "unrealized_pnl": "0",
// "time_stamp": 1661487402396
// },
// ...
// ]
// }
//
let mut balanceRequest: Value = Value::Str("list".into());
if (marketType.as_str() == Some("swap")) {
balanceRequest = Value::Str("data".into());
}
let mut balances: Value = self.safe_list(response, balanceRequest, &[Value::from(vec![])]);
return self.parse_balance(balances);
Value::Null
}
/*
* @method
* @name digifinex#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-orderbook
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut marketTypequeryVariable = self.handle_market_type_and_params(Value::Str("fetchOrderBook".into()), &[market.clone(), params]);
let mut marketType: Value = marketTypequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = marketTypequeryVariable.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
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit); }
}
let mut response: Value = Value::Null;
if (marketType.as_str() == Some("swap")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instrument_id".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
let __ws_arg_0 = self.extend(request.clone(), &[query.clone()]);
response = self.public_swap_get_public_depth(&[__ws_arg_0]).await;
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
let __ws_arg_1 = self.extend(request, &[query]);
response = self.public_spot_get_order_book(&[__ws_arg_1]).await;
}
//
// spot
//
// {
// "bids": [
// [9605.77,0.0016],
// [9605.46,0.0003],
// [9602.04,0.0127],
// ],
// "asks": [
// [9627.22,0.025803],
// [9627.12,0.168543],
// [9626.52,0.0011529],
// ],
// "date":1564509499,
// "code":0
// }
//
// swap
//
// {
// "code": 0,
// "data": {
// "instrument_id": "BTCUSDTPERP",
// "timestamp": 1667975290425,
// "asks": [
// ["18384.7",3492],
// ["18402.7",5000],
// ["18406.7",5000],
// ],
// "bids": [
// ["18366.2",4395],
// ["18364.3",3070],
// ["18359.4",5000],
// ]
// }
// }
//
let mut timestamp: Value = Value::Null;
let mut orderBook: Value = Value::Null;
if (marketType.as_str() == Some("swap")) {
orderBook = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
timestamp = self.safe_integer_k(orderBook.clone(), "timestamp", &[]);
} else {
orderBook = response.clone();
timestamp = self.safe_timestamp_k(response, "date", &[]);
}
return self.parse_order_book(orderBook, market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[timestamp]);
Value::Null
}
/*
* @method
* @name digifinex#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#ticker-price
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut first: Value = self.safe_string(symbolsNormalized.clone(), Value::Int(0), &[]);
let mut market: Value = Value::Null;
if (first != Value::Null) {
market = self.market(first);
}
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchTickers".into()), &[market, params]);
let mut type_var: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = type_varparamsMarketTypeVariable.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
});
let mut response: Value = Value::Null;
if (type_var.as_str() == Some("swap")) {
let __ws_arg_2 = self.extend(request.clone(), &[paramsMarketType.clone()]);
response = self.public_swap_get_public_tickers(&[__ws_arg_2]).await;
} else {
let __ws_arg_3 = self.extend(request, &[paramsMarketType]);
response = self.public_spot_get_ticker(&[__ws_arg_3]).await;
}
//
// spot
//
// {
// "ticker": [{
// "vol": 40717.4461,
// "change": -1.91,
// "base_vol": 392447999.65374,
// "sell": 9592.23,
// "last": 9592.22,
// "symbol": "btc_usdt",
// "low": 9476.24,
// "buy": 9592.03,
// "high": 9793.87
// }],
// "date": 1589874294,
// "code": 0
// }
//
// swap
//
// {
// "code": 0,
// "data": [
// {
// "instrument_id": "SUSHIUSDTPERP",
// "index_price": "1.1297",
// "mark_price": "1.1289",
// "max_buy_price": "1.1856",
// "min_sell_price": "1.0726",
// "best_bid": "1.1278",
// "best_bid_size": "500",
// "best_ask": "1.1302",
// "best_ask_size": "471",
// "high_24h": "1.2064",
// "open_24h": "1.1938",
// "low_24h": "1.1239",
// "last": "1.1302",
// "last_qty": "29",
// "volume_24h": "4946163",
// "price_change_percent": "-0.053275255486681085",
// "open_interest": "-",
// "timestamp": 1663222782100
// },
// ...
// ]
// }
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut tickers: Value = self.safe_list2(response.clone(), Value::Str("ticker".into()), Value::Str("data".into()), &[Value::from(vec![])]);
let mut date: Value = self.safe_integer_k(response, "date", &[]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_640: bool = true;
while { if !__for_first_640 { 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_640 = false; i.as_f64().unwrap_or(f64::NAN) < ((tickers.len() as i64) as f64) } {
let mut rawTicker: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("date".to_string(), date.clone());
m
}), &[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)]);
let mut ticker: Value = self.parse_ticker(rawTicker, &[]);
let mut symbol: Value = ticker.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker); }
}
}
}
return self.filter_by_array_tickers(result, Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name digifinex#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.digifinex.com/en-ww/spot/v3/rest.html#ticker-price
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#ticker
* @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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instrument_id".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
let __ws_arg_4 = self.extend(request.clone(), &[params.clone()]);
response = self.public_swap_get_public_ticker(&[__ws_arg_4]).await;
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
let __ws_arg_5 = self.extend(request, &[params]);
response = self.public_spot_get_ticker(&[__ws_arg_5]).await;
}
//
// spot
//
// {
// "ticker": [{
// "vol": 40717.4461,
// "change": -1.91,
// "base_vol": 392447999.65374,
// "sell": 9592.23,
// "last": 9592.22,
// "symbol": "btc_usdt",
// "low": 9476.24,
// "buy": 9592.03,
// "high": 9793.87
// }],
// "date": 1589874294,
// "code": 0
// }
//
// swap
//
// {
// "code": 0,
// "data": {
// "instrument_id": "BTCUSDTPERP",
// "index_price": "20141.9967",
// "mark_price": "20139.3404",
// "max_buy_price": "21146.4838",
// "min_sell_price": "19132.2725",
// "best_bid": "20140.0998",
// "best_bid_size": "3116",
// "best_ask": "20140.0999",
// "best_ask_size": "9004",
// "high_24h": "20410.6496",
// "open_24h": "20308.6998",
// "low_24h": "19600",
// "last": "20140.0999",
// "last_qty": "2",
// "volume_24h": "49382816",
// "price_change_percent": "-0.008301855936636448",
// "open_interest": "-",
// "timestamp": 1663221614998
// }
// }
//
let mut date: Value = self.safe_integer_k(response.clone(), "date", &[]);
let mut tickers: Value = self.safe_list_k(response.clone(), "ticker", &[Value::from(vec![])]);
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut firstTicker: Value = self.safe_dict(tickers, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut result: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
result = data;
} else {
result = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("date".to_string(), date);
m
}), &[firstTicker]);
}
if (result == Value::Null) {
panic!("{}", crate::exchange_errors::null_response(format!("{}{}", self.id.clone(), Value::Str(" fetchTicker() returned empty response".into()))));
}
return self.parse_ticker(result, &[market]);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// spot: fetchTicker, fetchTickers
//
// {
// "last":0.021957,
// "symbol": "btc_usdt",
// "base_vol":2249.3521732227,
// "change":-0.6,
// "vol":102443.5111,
// "sell":0.021978,
// "low":0.021791,
// "buy":0.021946,
// "high":0.022266,
// "date"1564518452, // injected from fetchTicker/fetchTickers
// }
//
// swap: fetchTicker, fetchTickers
//
// {
// "instrument_id": "BTCUSDTPERP",
// "index_price": "20141.9967",
// "mark_price": "20139.3404",
// "max_buy_price": "21146.4838",
// "min_sell_price": "19132.2725",
// "best_bid": "20140.0998",
// "best_bid_size": "3116",
// "best_ask": "20140.0999",
// "best_ask_size": "9004",
// "high_24h": "20410.6496",
// "open_24h": "20308.6998",
// "low_24h": "19600",
// "last": "20140.0999",
// "last_qty": "2",
// "volume_24h": "49382816",
// "price_change_percent": "-0.008301855936636448",
// "open_interest": "-",
// "timestamp": 1663221614998
// }
//
let mut indexPrice: Value = self.safe_number_k(ticker.clone(), "index_price", &[]);
let mut marketType: Value = Value::Str("spot".into());
if (indexPrice != Value::Null) {
marketType = Value::Str("contract".into());
}
let mut marketId: Value = self.safe_string_upper2(ticker.clone(), Value::Str("symbol".into()), Value::Str("instrument_id".into()), &[]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[market.clone(), Value::Null, marketType.clone()]);
let mut marketResolved: Value = self.safe_market(&[marketId, market, Value::Null, marketType]);
let mut timestamp: Value = self.safe_timestamp_k(ticker.clone(), "date", &[]);
if (marketResolved.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
timestamp = self.safe_integer_k(ticker.clone(), "timestamp", &[]);
}
let mut last: Value = self.safe_string_k(ticker.clone(), "last", &[]);
let mut percentage: Value = self.safe_string2(ticker.clone(), Value::Str("change".into()), Value::Str("price_change_percent".into()), &[]);
if (marketResolved.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
// swap endpoints return a raw ratio, spot already returns a percent
percentage = crate::precise::Precise::stringMul(&percentage, &Value::Str("100".into()));
}
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("high".to_string(), self.safe_string2(ticker.clone(), Value::Str("high".into()), Value::Str("high_24h".into()), &[]));
m.insert("low".to_string(), self.safe_string2(ticker.clone(), Value::Str("low".into()), Value::Str("low_24h".into()), &[]));
m.insert("bid".to_string(), self.safe_string2(ticker.clone(), Value::Str("buy".into()), Value::Str("best_bid".into()), &[]));
m.insert("bidVolume".to_string(), self.safe_string_k(ticker.clone(), "best_bid_size", &[]));
m.insert("ask".to_string(), self.safe_string2(ticker.clone(), Value::Str("sell".into()), Value::Str("best_ask".into()), &[]));
m.insert("askVolume".to_string(), self.safe_string_k(ticker.clone(), "best_ask_size", &[]));
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), self.safe_string_k(ticker.clone(), "open_24h", &[]));
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(), percentage);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), self.safe_string2(ticker.clone(), Value::Str("vol".into()), Value::Str("volume_24h".into()), &[]));
m.insert("quoteVolume".to_string(), self.safe_string_k(ticker.clone(), "base_vol", &[]));
m.insert("markPrice".to_string(), self.safe_string_k(ticker.clone(), "mark_price", &[]));
m.insert("indexPrice".to_string(), indexPrice);
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// spot: fetchTrades
//
// {
// "date":1564520003,
// "id":1596149203,
// "amount":0.7073,
// "type":"buy",
// "price":0.02193,
// }
//
// swap: fetchTrades
//
// {
// "instrument_id": "BTCUSDTPERP",
// "trade_id": "1595190773677035521",
// "direction": "4",
// "volume": "4",
// "price": "16188.3",
// "trade_time": 1669158092314
// }
//
// spot: fetchMyTrades
//
// {
// "symbol": "BTC_USDT",
// "order_id": "6707cbdcda0edfaa7f4ab509e4cbf966",
// "id": 28457,
// "price": 0.1,
// "amount": 0,
// "fee": 0.096,
// "fee_currency": "USDT",
// "timestamp": 1499865549,
// "side": "buy", // or "side": "sell_market"
// "is_maker": true
// }
//
// swap: fetchMyTrades
//
// {
// "trade_id": "1590136768424841218",
// "instrument_id": "BTCUSDTPERP",
// "order_id": "1590136768156405760",
// "type": 1,
// "order_type": 8,
// "price": "18514.5",
// "size": "1",
// "fee": "0.00925725",
// "close_profit": "0",
// "leverage": "20",
// "trade_type": 0,
// "match_role": 1,
// "trade_time": 1667953123562
// }
//
let mut id: Value = self.safe_string2(trade.clone(), Value::Str("id".into()), Value::Str("trade_id".into()), &[]);
let mut orderId: Value = self.safe_string_k(trade.clone(), "order_id", &[]);
let mut priceString: Value = self.safe_string_k(trade.clone(), "price", &[]);
let mut amountString: Value = self.safe_string_n(trade.clone(), Value::from(vec![Value::Str("amount".into()), Value::Str("volume".into()), Value::Str("size".into())]), &[]);
let mut marketId: Value = self.safe_string_upper2(trade.clone(), Value::Str("symbol".into()), Value::Str("instrument_id".into()), &[]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[market.clone()]);
let mut marketResolved: Value = self.safe_market(&[(if (market == Value::Null) { marketId } else { Value::Null }), market]);
let mut timestamp: Value = self.safe_timestamp2(trade.clone(), Value::Str("date".into()), Value::Str("timestamp".into()), &[]);
let mut side: Value = self.safe_string2(trade.clone(), Value::Str("type".into()), Value::Str("side".into()), &[]);
let mut type_var: Value = Value::Null;
let mut takerOrMaker: Value = Value::Null;
if (marketResolved.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null).as_str() == Some("swap")) {
timestamp = self.safe_integer_k(trade.clone(), "trade_time", &[]);
let mut orderType: Option<String> = self.safe_string_k(trade.clone(), "order_type", &[]).as_str().map(str::to_owned);
let mut tradeRole: Option<String> = self.safe_string_k(trade.clone(), "match_role", &[]).as_str().map(str::to_owned);
let mut direction: Option<String> = self.safe_string_k(trade.clone(), "direction", &[]).as_str().map(str::to_owned);
if (orderType.is_some()) {
if (orderType.as_deref() == Some("0")) {
type_var = Value::Str("limit".into());
}
}
if (tradeRole.as_deref() == Some("1")) {
takerOrMaker = Value::Str("taker".into());
} else if (tradeRole.as_deref() == Some("2")) {
takerOrMaker = Value::Str("maker".into());
} else {
takerOrMaker = Value::Null;
}
if (side.as_str() == Some("1")) || (direction.as_deref() == Some("1")) {
// side = 'open long';
side = Value::Str("buy".into());
} else if (side.as_str() == Some("2")) || (direction.as_deref() == Some("2")) {
// side = 'open short';
side = Value::Str("sell".into());
} else if (side.as_str() == Some("3")) || (direction.as_deref() == Some("3")) {
// side = 'close long';
side = Value::Str("sell".into());
} else if (side.as_str() == Some("4")) || (direction.as_deref() == Some("4")) {
// side = 'close short';
side = Value::Str("buy".into());
}
} else {
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" parseTrade() returned no side".into()))));
}
let mut parts: Value = split(&side, &Value::Str("_".into()));
side = self.safe_string(parts.clone(), Value::Int(0), &[]);
type_var = self.safe_string(parts, Value::Int(1), &[]);
if (type_var == Value::Null) {
type_var = Value::Str("limit".into());
}
let mut isMaker: Value = self.safe_bool_k(trade.clone(), "is_maker", &[]);
takerOrMaker = (if (isMaker.as_bool() == Some(true)) { Value::Str("maker".into()) } else { Value::Str("taker".into()) });
}
let mut fee: Value = Value::Null;
let mut feeCostString: Value = self.safe_string_k(trade.clone(), "fee", &[]);
if (feeCostString != Value::Null) {
let mut feeCurrencyId: Value = self.safe_string_k(trade.clone(), "fee_currency", &[]);
let mut feeCurrencyCode: Value = Value::Null;
if (feeCurrencyId != Value::Null) {
feeCurrencyCode = self.safe_currency_code(feeCurrencyId, &[]);
}
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCostString);
m.insert("currency".to_string(), feeCurrencyCode);
m
});
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("info".to_string(), trade);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), type_var);
m.insert("order".to_string(), orderId);
m.insert("side".to_string(), side);
m.insert("price".to_string(), priceString);
m.insert("amount".to_string(), amountString);
m.insert("cost".to_string(), Value::Null);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("fee".to_string(), fee);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name digifinex#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#server-timestamp
* @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 response: Value = self.public_spot_get_time(&[params]).await;
return self.safe_timestamp_k(response, "server_time", &[]);
Value::Null
}
/*
* @method
* @name digifinex#fetchStatus
* @description the latest known information on the availability of the exchange API
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#server-ping
* @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 response: Value = self.public_spot_get_ping(&[params]).await;
//
// {
// "msg": "pong",
// "code": 0
// }
//
let mut code: Option<i64> = self.safe_integer_k(response.clone(), "code", &[]).as_i64();
let mut status: Value = Value::Str("maintenance".into());
if (code == Some(0)) {
status = Value::Str("ok".into());
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), status);
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 digifinex#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-recent-trades
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#recenttrades
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), (if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { crate::runtime::Math::min(&limit, &Value::Int(100)) } else { limit.clone() })); }
}
let mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instrument_id".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
let __ws_arg_6 = self.extend(request.clone(), &[params.clone()]);
response = self.public_swap_get_public_trades(&[__ws_arg_6]).await;
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
let __ws_arg_7 = self.extend(request, &[params]);
response = self.public_spot_get_trades(&[__ws_arg_7]).await;
}
//
// spot
//
// {
// "data":[
// {
// "date":1564520003,
// "id":1596149203,
// "amount":0.7073,
// "type":"buy",
// "price":0.02193,
// },
// {
// "date":1564520002,
// "id":1596149165,
// "amount":0.3232,
// "type":"sell",
// "price":0.021927,
// },
// ],
// "code": 0,
// "date": 1564520003,
// }
//
// swap
//
// {
// "code": 0,
// "data": [
// {
// "instrument_id": "BTCUSDTPERP",
// "trade_id": "1595190773677035521",
// "direction": "4",
// "volume": "4",
// "price": "16188.3",
// "trade_time": 1669158092314
// },
// ...
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_trades(data, &[market, 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);
let __market_empty = indexmap::IndexMap::new();
let market = market.as_map().unwrap_or(&__market_empty);
//
// [
// 1556712900,
// 2205.899,
// 0.029967,
// 0.02997,
// 0.029871,
// 0.029927
// ]
//
if matches!((match market.get("swap") { Some(Value::Bool(__b)) => Value::Bool(*__b), _ => Value::Bool(false) }), Value::Bool(true)) {
return Value::from(vec![self.safe_integer(ohlcv.clone(), Value::Int(0), &[]), self.safe_number(ohlcv.clone(), Value::Int(1), &[]), self.safe_number(ohlcv.clone(), Value::Int(2), &[]), self.safe_number(ohlcv.clone(), Value::Int(3), &[]), self.safe_number(ohlcv.clone(), Value::Int(4), &[]), self.safe_number(ohlcv.clone(), Value::Int(5), &[])]);
} else {
return Value::from(vec![self.safe_timestamp(ohlcv.clone(), Value::Int(0), &[]), self.safe_number(ohlcv.clone(), Value::Int(5), &[]), self.safe_number(ohlcv.clone(), Value::Int(3), &[]), self.safe_number(ohlcv.clone(), Value::Int(4), &[]), self.safe_number(ohlcv.clone(), Value::Int(2), &[]), self.safe_number(ohlcv, Value::Int(1), &[])]);
}
Value::Null
}
/*
* @method
* @name digifinex#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-candles-data
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#recentcandle
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instrument_id".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("granularity".into(), timeframe.clone()); }
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(100))); }
}
let __ws_arg_8 = self.extend(request.clone(), &[params.clone()]);
response = self.public_swap_get_public_candles(&[__ws_arg_8]).await;
} else {
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("period".into(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()])); }
let mut startTime: Value = since.clone();
let mut duration: Value = self.parse_timeframe(timeframe.clone());
if (startTime == Value::Null) {
if (limit != Value::Null) || (until != Value::Null) {
let mut endTime: Value = (if (until != Value::Null) { until.clone() } else { self.milliseconds() });
let mut startLimit: Value = (if (limit != Value::Null) { limit.clone() } else { Value::Int(200) });
startTime = (match (&(endTime), &(((match (&((match (&(startLimit), &(duration)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
}
}
if (startTime != Value::Null) {
startTime = self.parse_to_int((match ((startTime).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_time".into(), startTime.clone()); }
if (limit != Value::Null) || (until != Value::Null) {
if (until != Value::Null) {
let mut endByUntil: Value = 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 }));
if (limit != Value::Null) {
let mut endByLimit: Value = self.sum(&[startTime.clone(), (match (&(limit), &(duration)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end_time".into(), crate::runtime::Math::min(&endByLimit, &endByUntil)); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end_time".into(), endByUntil); }
}
} else {
if (limit == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() requires a limit argument".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end_time".into(), self.sum(&[startTime, (match (&(limit), &(duration)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })])); }
}
}
}
let mut paramsOmitted: Value = self.omit(params, Value::Str("until".into()), &[]);
let __ws_arg_9 = self.extend(request, &[paramsOmitted]);
response = self.public_spot_get_kline(&[__ws_arg_9]).await;
}
//
// spot
//
// {
// "code":0,
// "data":[
// [1556712900,2205.899,0.029967,0.02997,0.029871,0.029927],
// [1556713800,1912.9174,0.029992,0.030014,0.029955,0.02996],
// [1556714700,1556.4795,0.029974,0.030019,0.029969,0.02999],
// ]
// }
//
// swap
//
// {
// "code": 0,
// "data": {
// "instrument_id": "BTCUSDTPERP",
// "granularity": "1m",
// "candles": [
// [1588089660000,"6900","6900","6900","6900","0","0"],
// [1588089720000,"6900","6900","6900","6900","0","0"],
// [1588089780000,"6900","6900","6900","6900","0","0"],
// ]
// }
// }
//
let mut candles: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
candles = self.safe_list_k(data, "candles", &[Value::from(vec![])]);
} else {
candles = self.safe_list_k(response, "data", &[Value::from(vec![])]);
}
return self.parse_ohlc_vs(candles, &[market, timeframe, since, limit]);
Value::Null
}
/*
* @method
* @name digifinex#createOrder
* @description create a trade order
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#create-new-order
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#orderplace
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much you want to trade in units of the base currency, spot market orders use the quote currency, swap requires the number of contracts
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.timeInForce] "GTC", "IOC", "FOK", or "PO"
* @param {bool} [params.postOnly] true or false
* @param {bool} [params.reduceOnly] true or false
* @param {string} [params.marginMode] 'cross' or 'isolated', for spot margin trading
* @param {float} [params.cost] *spot market buy only* the quote quantity that can be used as an alternative for the amount
* @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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut marginResult: Value = self.handle_margin_mode_and_params(Value::Str("createOrder".into()), &[params.clone()]);
let mut marginMode: Value = marginResult.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut request: Value = self.create_order_request(symbol, type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params]);
let mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
response = self.private_swap_post_trade_order_place(&[request.clone()]).await;
} else {
if (marginMode != Value::Null) {
response = self.private_spot_post_margin_order_new(&[request.clone()]).await;
} else {
response = self.private_spot_post_spot_order_new(&[request]).await;
}
}
//
// spot and margin
//
// {
// "code": 0,
// "order_id": "198361cecdc65f9c8c9bb2fa68faec40"
// }
//
// swap
//
// {
// "code": 0,
// "data": "1590873693003714560"
// }
//
if (response == Value::Null) {
panic!("{}", crate::exchange_errors::null_response(format!("{}{}", self.id.clone(), Value::Str(" createOrder() returned empty response".into()))));
}
let mut order: Value = self.parse_order(response, &[market.clone()]);
add_element_to_object(&mut order, &Value::Str("symbol".into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
add_element_to_object(&mut order, &Value::Str("type".into()), type_var);
add_element_to_object(&mut order, &Value::Str("side".into()), side);
add_element_to_object(&mut order, &Value::Str("amount".into()), amount);
add_element_to_object(&mut order, &Value::Str("price".into()), price);
return order;
Value::Null
}
/*
* @method
* @name digifinex#createOrders
* @description create a list of trade orders (all orders should be of the same symbol)
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#create-multiple-order
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#batchorder
* @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
* @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 create_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut ordersRequests: Value = Value::from(vec![]);
let mut symbol: Value = Value::Null;
let mut marginMode: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_641: bool = true;
while { if !__for_first_641 { 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_641 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut marketId: Value = self.safe_string_k(rawOrder.clone(), "symbol", &[]);
if (symbol == Value::Null) {
symbol = marketId.clone();
} else {
if (symbol.as_str() != marketId.as_str()) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrders() requires all orders to have the same symbol".into()))));
}
}
let mut type_var: Value = self.safe_string_k(rawOrder.clone(), "type", &[]);
let mut side: Value = self.safe_string_k(rawOrder.clone(), "side", &[]);
let mut amount: Value = self.safe_value_k(rawOrder.clone(), "amount", &[]);
let mut price: Value = self.safe_value_k(rawOrder.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder.clone(), "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marginResult: Value = self.handle_margin_mode_and_params(Value::Str("createOrders".into()), &[orderParams.clone()]);
let mut currentMarginMode: Value = marginResult.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
if (currentMarginMode != Value::Null) {
if (marginMode == Value::Null) {
marginMode = currentMarginMode.clone();
} else {
if (marginMode.as_str() != currentMarginMode.as_str()) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrders() requires all orders to have the same margin mode (isolated or cross)".into()))));
}
}
}
let mut orderRequest: Value = self.create_order_request(marketId, type_var, side, amount, &[price, orderParams]);
append_to_array(&mut ordersRequests, orderRequest);
}
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
response = self.private_swap_post_trade_batch_order(&[ordersRequests.clone()]).await;
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("market".into(), (if (marginMode != Value::Null) { Value::Str("margin".into()) } else { Value::Str("spot".into()) })); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("list".into(), json_stringify(&ordersRequests)); }
response = self.private_spot_post_market_order_batch_new(&[request]).await;
}
//
// spot
//
// {
// "code": 0,
// "order_ids": [
// "064290fbe2d26e7b28d7e6c0a5cf70a5",
// "24c8f9b73d81e4d9d8d7e3280281c258"
// ]
// }
//
// swap
//
// {
// "code": 0,
// "data": [
// "1720297963537829888",
// "1720297963537829889"
// ]
// }
//
let mut data: Value = Value::from(vec![]);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
data = self.safe_list_k(response.clone(), "data", &[Value::from(vec![])]);
} else {
data = self.safe_list_k(response, "order_ids", &[Value::from(vec![])]);
}
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_642: bool = true;
while { if !__for_first_642 { 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_642 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut individualOrder: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if let Value::Dict(__d) = &mut individualOrder { std::sync::Arc::make_mut(__d).insert("order_id".into(), data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut individualOrder { std::sync::Arc::make_mut(__d).insert("instrument_id".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut individualOrder { std::sync::Arc::make_mut(__d).insert("amount".into(), self.safe_number_k(rawOrder.clone(), "amount", &[])); }
if let Value::Dict(__d) = &mut individualOrder { std::sync::Arc::make_mut(__d).insert("price".into(), self.safe_number_k(rawOrder, "price", &[])); }
append_to_array(&mut result, individualOrder);
}
}
return self.parse_orders(result, &[market]);
Value::Null
}
pub fn create_order_request(&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
}));
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a type argument".into()))));
}
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a side argument".into()))));
}
/*
* @method
* @ignore
* @name digifinex#createOrderRequest
* @description helper function to build request
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much you want to trade in units of the base currency, spot market orders use the quote currency, swap requires the number of contracts
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} request to be sent to the exchange
*/
let mut market: Value = self.market(symbol.clone());
let mut marketTypeRawparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("createOrderRequest".into()), &[market.clone(), params]);
let mut marketTypeRaw: Value = marketTypeRawparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = marketTypeRawparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut marginModeparamsMarginModeVariable = self.handle_margin_mode_and_params(Value::Str("createOrderRequest".into()), &[paramsMarketType]);
let mut marginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut marketType: Value = (if (marginMode != Value::Null) { Value::Str("margin".into()) } else { marketTypeRaw });
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut swap: bool = marketType.as_str() == Some("swap");
let mut isMarketOrder: Value = (Value::Bool(type_var.as_str() == Some("market")));
let mut isLimitOrder: bool = type_var.as_str() == Some("limit");
let mut marketIdRequest: Value = Value::Str("symbol".into());
if swap {
marketIdRequest = Value::Str("instrument_id".into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&marketIdRequest), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
let mut postOnly: Value = self.is_post_only(isMarketOrder.clone(), Value::Bool(false), &[paramsMarginMode.clone()]);
let mut postOnlyParsed: Value = Value::Null;
let mut paramsRequest: Value = Value::Null;
if swap {
let mut reduceOnly: Value = self.safe_bool_k(paramsMarginMode.clone(), "reduceOnly", &[Value::Bool(false)]);
let mut timeInForce: Option<String> = self.safe_string_k(paramsMarginMode.clone(), "timeInForce", &[]).as_str().map(str::to_owned);
let mut orderType: Value = Value::Null;
if (side.as_str() == Some("buy")) {
let mut requestType: Value = (if (reduceOnly.as_bool() == Some(true)) { Value::Int(4) } else { Value::Int(1) });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), requestType.clone()); }
} else {
let mut requestType: Value = (if (reduceOnly.as_bool() == Some(true)) { Value::Int(3) } else { Value::Int(2) });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), requestType); }
}
if isLimitOrder {
orderType = Value::Int(0);
}
if (timeInForce.as_deref() == Some("FOK")) {
orderType = (if matches!(&isMarketOrder, Value::Bool(true)) { Value::Int(15) } else { Value::Int(9) });
} else if (timeInForce.as_deref() == Some("IOC")) {
orderType = (if matches!(&isMarketOrder, Value::Bool(true)) { Value::Int(13) } else { Value::Int(4) });
} else if (timeInForce.as_deref() == Some("GTC")) || matches!(&isMarketOrder, Value::Bool(true)) {
orderType = Value::Int(14);
} else if (timeInForce.as_deref() == Some("PO")) {
postOnly = Value::Bool(true);
}
if (price != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.price_to_precision(symbol.clone(), price.clone())); }
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("order_type".into(), orderType); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("size".into(), amount.clone()); }; // swap orders require the amount to be the number of contracts
paramsRequest = self.omit(paramsMarginMode.clone(), Value::from(vec![Value::Str("reduceOnly".into()), Value::Str("timeInForce".into()), Value::Str("postOnly".into())]), &[]);
} else {
postOnlyParsed = (if (postOnly.as_bool() == Some(true)) { Value::Int(1) } else { Value::Int(2) });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("market".into(), marketType); }
let mut suffix: Value = Value::Str("".into());
if (type_var.as_str() == Some("market")) {
suffix = Value::Str("_market".into());
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.price_to_precision(symbol.clone(), price.clone())); }
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str(format!("{}{}", side, suffix).into())); }
// limit orders require the amount in the base currency, market orders require the amount in the quote currency
let mut quantity: Value = Value::Null;
let mut createMarketBuyOrderRequiresPriceparamsRequiresPriceVariable = self.handle_option_bool_and_params(paramsMarginMode, Value::Str("createOrderRequest".into()), Value::Str("createMarketBuyOrderRequiresPrice".into()), &[Value::Bool(true)]);
let mut createMarketBuyOrderRequiresPrice: Value = createMarketBuyOrderRequiresPriceparamsRequiresPriceVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsRequiresPrice: Value = createMarketBuyOrderRequiresPriceparamsRequiresPriceVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut isMarketBuy: bool = matches!(&isMarketOrder, Value::Bool(true)) && (side.as_str() == Some("buy"));
let mut keysToOmit: Value = Value::Null;
if isMarketBuy {
keysToOmit = Value::from(vec![Value::Str("cost".into()), Value::Str("postOnly".into())]);
} else {
keysToOmit = Value::from(vec![Value::Str("postOnly".into())]);
}
paramsRequest = self.omit(paramsRequiresPrice.clone(), keysToOmit, &[]);
if isMarketBuy {
let mut cost: Value = self.safe_number_k(paramsRequiresPrice, "cost", &[]);
if (cost != Value::Null) {
quantity = self.cost_to_precision(symbol.clone(), cost);
} else if is_true(&createMarketBuyOrderRequiresPrice) {
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price argument for market buy orders on spot markets to calculate the total amount to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument".into()))));
} else {
let mut amountString: Value = self.number_to_string(amount.clone());
let mut priceString: Value = self.number_to_string(price);
let mut costRequest: Value = self.parse_number(crate::precise::Precise::stringMul(&amountString, &priceString), &[]);
quantity = self.cost_to_precision(symbol.clone(), costRequest);
}
} else {
quantity = self.cost_to_precision(symbol.clone(), amount.clone());
}
} else {
quantity = self.amount_to_precision(symbol, amount);
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("amount".into(), quantity); }
}
if is_true(&postOnly) {
if (postOnlyParsed != Value::Null) && (postOnlyParsed.as_f64() != Some(0.0)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("post_only".into(), postOnlyParsed); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("post_only".into(), postOnly.clone()); }
}
}
return self.extend(request, &[paramsRequest]);
Value::Null
}
/*
* @method
* @name digifinex#createMarketBuyOrderWithCost
* @description create a market buy order by providing the symbol and cost
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#create-new-order
* @param {string} symbol unified symbol of the market to create an order in
* @param {float} cost how much you want to trade in units of the quote currency
* @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 create_market_buy_order_with_cost(&mut self, mut symbol: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createMarketBuyOrderWithCost() supports spot orders only".into()))));
}
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("createMarketBuyOrderRequiresPrice".into(), Value::Bool(false)); }
return self.create_order(symbol, Value::Str("market".into()), Value::Str("buy".into()), cost, &[Value::Null, params]).await;
Value::Null
}
/*
* @method
* @name digifinex#cancelOrder
* @description cancels an open order
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#cancel-order
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#cancelorder
* @param {string} id order id
* @param {string} symbol not used by cancelOrder ()
* @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 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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut idValue: Value = to_string_val(&id);
let mut marketType: Value = Value::Null;
let mut paramsMarketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("cancelOrder".into()), &[market.clone(), params]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsMarketType = __destr_tmp.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("order_id".to_string(), idValue.clone());
m
});
if (marketType.as_str() == Some("swap")) {
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() requires a symbol argument".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instrument_id".into(), self.safe_string_k(market, "id", &[])); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("market".into(), marketType.clone()); }
}
let mut marginModequeryVariable = self.handle_margin_mode_and_params(Value::Str("cancelOrder".into()), &[paramsMarketType]);
let mut marginMode: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut response: Value = Value::Null;
if (marginMode != Value::Null) || (marketType.as_str() == Some("margin")) {
marketType = Value::Str("margin".into());
let __ws_arg_10 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_post_margin_order_cancel(&[__ws_arg_10]).await;
} else if (marketType.as_str() == Some("spot")) {
let __ws_arg_11 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_post_spot_order_cancel(&[__ws_arg_11]).await;
} else if (marketType.as_str() == Some("swap")) {
let __ws_arg_12 = self.extend(request, &[query]);
response = self.private_swap_post_trade_cancel_order(&[__ws_arg_12]).await;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() not support this market type".into()))));
}
//
// spot and margin
//
// {
// "code": 0,
// "success": [
// "198361cecdc65f9c8c9bb2fa68faec40",
// "3fb0d98e51c18954f10d439a9cf57de0"
// ],
// "error": [
// "78a7104e3c65cc0c5a212a53e76d0205"
// ]
// }
//
// swap
//
// {
// "code": 0,
// "data": "1590923061186531328"
// }
//
if (marketType.as_str() == Some("spot")) || (marketType.as_str() == Some("margin")) {
let mut canceledOrders: Value = self.safe_list_k(response.clone(), "success", &[Value::from(vec![])]);
let mut numCanceledOrders: f64 = ((canceledOrders.len() as i64) as f64);
if (numCanceledOrders != 1.0) {
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() ".into())).into()), idValue).into()), Value::Str(" not found".into()))));
}
let mut orders: Value = self.parse_cancel_orders(response.clone(), &[]);
let mut canceled: Value = self.safe_dict(orders, Value::Int(0), &[]);
return canceled;
} else {
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m.insert("id".to_string(), self.safe_string_k(response, "data", &[]));
m
}), &[]);
}
Value::Null
}
pub fn parse_cancel_orders(&self, mut response: Value, optional_args: &[Value]) -> Value {
let mut symbolsById = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __response_empty = indexmap::IndexMap::new();
let response = response.as_map().unwrap_or(&__response_empty);
let mut success: Value = (match response.get("success") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut error: Value = (match response.get("error") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_643: bool = true;
while { if !__for_first_643 { 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_643 = false; i.as_f64().unwrap_or(f64::NAN) < ((success.len() as i64) as f64) } {
let mut order: Value = success.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.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), order.clone());
m.insert("symbol".to_string(), self.safe_string(symbolsById.clone(), order.clone(), &[]));
m.insert("status".to_string(), Value::Str("canceled".into()));
m
}), &[]));
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_644: bool = true;
while { if !__for_first_644 { 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_644 = false; i.as_f64().unwrap_or(f64::NAN) < ((error.len() as i64) as f64) } {
let mut order: Value = error.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.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), order.clone());
m.insert("symbol".to_string(), self.safe_string(symbolsById.clone(), order, &[]));
m.insert("status".to_string(), Value::Str("failed".into()));
m
}), &[]));
}
}
return result;
Value::Null
}
/*
* @method
* @name digifinex#cancelOrders
* @description cancel multiple orders
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#cancel-order
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#batchcancel
* @param {string[]} ids order ids
* @param {string} [symbol] unified market symbol, required for swap markets
* @param {object} [params] extra parameters specific to the exchange API endpoint, not forwarded for swap markets (the request body is an array)
* @param {string} [params.type] 'spot', 'margin' or 'swap', defaults to the type of the symbol's market or options.defaultType
* @returns {object} an 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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut marketTypeparamsOmittedVariable = self.handle_market_type_and_params(Value::Str("cancelOrders".into()), &[market.clone(), params]);
let mut marketType: Value = marketTypeparamsOmittedVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsOmitted: Value = marketTypeparamsOmittedVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (marketType.as_str() == Some("swap")) {
if (market == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() requires a symbol argument for swap markets".into()))));
}
let mut marketSymbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut orders: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_645: bool = true;
while { if !__for_first_645 { 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_645 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
let mut orderId: Value = ids.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 orderItem: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), orderId);
m.insert("symbol".to_string(), marketSymbol.clone());
m
});
append_to_array(&mut orders, orderItem);
}
}
return self.cancel_orders_for_symbols(orders, &[paramsOmitted.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market".to_string(), marketType);
m.insert("order_id".to_string(), join(&ids, &Value::Str(",".into())));
m
});
let __ws_arg_13 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_spot_post_spot_order_cancel(&[__ws_arg_13]).await;
return self.parse_cancel_orders(response, &[]);
Value::Null
}
/*
* @method
* @name digifinex#cancelOrdersForSymbols
* @description cancel multiple orders for multiple symbols
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#cancel-order
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#batchcancel
* @param {CancellationRequest[]} orders each order should contain the parameters required by cancelOrder namely id and symbol, all orders must be of the same market type (spot or swap), example [{"id": "a", "symbol": "BTC/USDT"}, {"id": "b", "symbol": "ETH/USDT"}]
* @param {object} [params] extra parameters specific to the exchange API endpoint, not forwarded for swap markets (the request body is an array)
* @param {string} [params.type] 'spot' or 'margin' for spot markets, defaults to 'spot'
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_orders_for_symbols(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut ids: Value = Value::from(vec![]);
let mut symbols: Value = Value::from(vec![]);
let mut symbolsById: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut marketType: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_646: bool = true;
while { if !__for_first_646 { 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_646 = 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);
let mut id: Value = self.safe_string_k(order.clone(), "id", &[]);
if (id == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrdersForSymbols() requires an id for each order".into()))));
}
let mut symbol: Value = self.safe_string_k(order, "symbol", &[]);
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrdersForSymbols() requires a symbol for each order".into()))));
}
let mut market: Value = self.market(symbol);
let mut orderMarketType: Value = market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null);
if (marketType == Value::Null) {
marketType = orderMarketType.clone();
} else if (marketType.as_str() != orderMarketType.as_str()) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" cancelOrdersForSymbols() requires all orders to be of the same market type (spot or swap)".into()))));
}
append_to_array(&mut ids, id.clone());
append_to_array(&mut symbols, market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
if let Value::Dict(__d) = &mut symbolsById { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&id), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)); }
}
}
if (marketType.as_str() == Some("swap")) {
let mut numIds: f64 = ((ids.len() as i64) as f64);
if numIds > ((20i64) as f64) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" cancelOrdersForSymbols() accepts up to 20 orders for swap markets".into()))));
}
let mut ordersRequests: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_647: bool = true;
while { if !__for_first_647 { 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_647 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
let mut market: Value = self.market(symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
let mut marketId: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut orderId: Value = ids.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 ordersRequests, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), marketId);
m.insert("order_id".to_string(), orderId.clone());
m
}));
}
}
let mut swapResponse: Value = self.private_swap_post_trade_batch_cancel_order(&[ordersRequests]).await; // don't extend with params, otherwise the array body is turned into an object
//
// {
// "code": 0,
// "data": [
// "1546771720487047168",
// "1546771720487047169"
// ]
// }
//
// ids that were not canceled are absent from data
let mut data: Value = self.safe_list_k(swapResponse, "data", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_648: bool = true;
while { if !__for_first_648 { 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_648 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
let mut orderId: Value = ids.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 isCanceled: Value = self.in_array(orderId.clone(), data.clone());
let mut status: Value = (if is_true(&(isCanceled)) { Value::Str("canceled".into()) } else { Value::Str("failed".into()) });
append_to_array(&mut result, self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), orderId.clone());
m.insert("id".to_string(), orderId);
m.insert("symbol".to_string(), 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));
m.insert("status".to_string(), status);
m
}), &[]));
}
}
return result;
}
let mut requestTypeparamsRequestVariable = self.handle_market_type_and_params(Value::Str("cancelOrdersForSymbols".into()), &[Value::Null, params, Value::Str("spot".into())]);
let mut requestType: Value = requestTypeparamsRequestVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsRequest: Value = requestTypeparamsRequestVariable.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("market".to_string(), requestType);
m.insert("order_id".to_string(), join(&ids, &Value::Str(",".into())));
m
});
let __ws_arg_14 = self.extend(request, &[paramsRequest]);
let mut response: Value = self.private_spot_post_spot_order_cancel(&[__ws_arg_14]).await;
return self.parse_cancel_orders(response, &[symbolsById]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("-1".to_string(), Value::Str("canceled".into()));
m.insert("0".to_string(), Value::Str("open".into()));
m.insert("1".to_string(), Value::Str("open".into()));
m.insert("2".to_string(), Value::Str("closed".into()));
m.insert("3".to_string(), Value::Str("canceled".into()));
m.insert("4".to_string(), Value::Str("canceled".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// spot: createOrder
//
// {
// "code": 0,
// "order_id": "198361cecdc65f9c8c9bb2fa68faec40"
// }
//
// swap: createOrder
//
// {
// "code": 0,
// "data": "1590873693003714560"
// }
//
// spot and swap: createOrders
//
// {
// "order_id": "d64d92a5e0a120f792f385485bc3d95b",
// "instrument_id": "BTC_USDT",
// "amount": 0.0001,
// "price": 27000
// }
//
// spot: fetchOrder, fetchOpenOrders, fetchOrders
//
// {
// "symbol": "BTC_USDT",
// "order_id": "dd3164b333a4afa9d5730bb87f6db8b3",
// "created_date": 1562303547,
// "finished_date": 0,
// "price": 0.1,
// "amount": 1,
// "cash_amount": 1,
// "executed_amount": 0,
// "avg_price": 0,
// "status": 1,
// "type": "buy",
// "kind": "margin"
// }
//
// swap: fetchOrder, fetchOpenOrders, fetchOrders
//
// {
// "order_id": "1590898207657824256",
// "instrument_id": "BTCUSDTPERP",
// "margin_mode": "crossed",
// "contract_val": "0.001",
// "type": 1,
// "order_type": 0,
// "price": "14000",
// "size": "6",
// "filled_qty": "0",
// "price_avg": "0",
// "fee": "0",
// "state": 0,
// "leverage": "20",
// "turnover": "0",
// "has_stop": 0,
// "insert_time": 1668134664828,
// "time_stamp": 1668134664828
// }
//
let mut timestamp: Value = Value::Null;
let mut lastTradeTimestamp: Value = Value::Null;
let mut timeInForce: Value = Value::Null;
let mut type_var: Value = Value::Null;
let mut reduceOnly: Value = Value::Null;
let mut side: Value = self.safe_string_k(order.clone(), "type", &[]);
let mut marketId: Value = self.safe_string2(order.clone(), Value::Str("symbol".into()), Value::Str("instrument_id".into()), &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market.clone()]);
let mut marketResolved: Value = self.market(symbol.clone());
if (marketResolved.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null).as_str() == Some("swap")) {
let mut orderType: Value = self.safe_integer_k(order.clone(), "order_type", &[]);
if (orderType != Value::Null) {
if (orderType.as_f64() == Some(9.0)) || (orderType.as_f64() == Some(10.0)) || (orderType.as_f64() == Some(11.0)) || (orderType.as_f64() == Some(12.0)) || (orderType.as_f64() == Some(15.0)) {
timeInForce = Value::Str("FOK".into());
} else if (orderType.as_f64() == Some(1.0)) || (orderType.as_f64() == Some(2.0)) || (orderType.as_f64() == Some(3.0)) || (orderType.as_f64() == Some(4.0)) || (orderType.as_f64() == Some(13.0)) {
timeInForce = Value::Str("IOC".into());
} else if (orderType.as_f64() == Some(6.0)) || (orderType.as_f64() == Some(7.0)) || (orderType.as_f64() == Some(8.0)) || (orderType.as_f64() == Some(14.0)) {
timeInForce = Value::Str("GTC".into());
}
if (orderType.as_f64() == Some(0.0)) || (orderType.as_f64() == Some(1.0)) || (orderType.as_f64() == Some(4.0)) || (orderType.as_f64() == Some(5.0)) || (orderType.as_f64() == Some(9.0)) || (orderType.as_f64() == Some(10.0)) {
type_var = Value::Str("limit".into());
} else {
type_var = Value::Str("market".into());
}
}
// 1 open long, 2 open short, 3 close long, 4 close short
if (side.as_str() == Some("1")) {
side = Value::Str("buy".into());
reduceOnly = Value::Bool(false);
} else if (side.as_str() == Some("2")) {
side = Value::Str("sell".into());
reduceOnly = Value::Bool(false);
} else if (side.as_str() == Some("3")) {
side = Value::Str("sell".into());
reduceOnly = Value::Bool(true);
} else if (side.as_str() == Some("4")) {
side = Value::Str("buy".into());
reduceOnly = Value::Bool(true);
}
timestamp = self.safe_integer_k(order.clone(), "insert_time", &[]);
lastTradeTimestamp = self.safe_integer_k(order.clone(), "time_stamp", &[]);
} else {
timestamp = self.safe_timestamp_k(order.clone(), "created_date", &[]);
lastTradeTimestamp = self.safe_timestamp_k(order.clone(), "finished_date", &[]);
if (side != Value::Null) {
let mut parts: Value = split(&side, &Value::Str("_".into()));
let mut numParts: f64 = ((parts.len() as i64) as f64);
if numParts > ((1i64) as f64) {
side = parts.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
type_var = parts.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
} else {
type_var = Value::Str("limit".into());
}
}
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), self.safe_string2(order.clone(), Value::Str("order_id".into()), Value::Str("data".into()), &[]));
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("symbol".to_string(), symbol);
m.insert("type".to_string(), type_var);
m.insert("timeInForce".to_string(), timeInForce);
m.insert("postOnly".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("price".to_string(), self.safe_number_k(order.clone(), "price", &[]));
m.insert("triggerPrice".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), reduceOnly);
m.insert("amount".to_string(), self.safe_number2(order.clone(), Value::Str("amount".into()), Value::Str("size".into()), &[]));
m.insert("filled".to_string(), self.safe_number2(order.clone(), Value::Str("executed_amount".into()), Value::Str("filled_qty".into()), &[]));
m.insert("remaining".to_string(), Value::Null);
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), self.safe_number2(order.clone(), Value::Str("avg_price".into()), Value::Str("price_avg".into()), &[]));
m.insert("status".to_string(), self.parse_order_status(self.safe_string2(order.clone(), Value::Str("status".into()), Value::Str("state".into()), &[])));
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.safe_number_k(order, "fee", &[]));
m
}));
m.insert("trades".to_string(), Value::Null);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name digifinex#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#current-active-orders
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#openorder
* @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 orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut marketType: Value = Value::Null;
let mut paramsMarketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchOpenOrders".into()), &[market.clone(), params]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsMarketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut marginModequeryVariable = self.handle_margin_mode_and_params(Value::Str("fetchOpenOrders".into()), &[paramsMarketType]);
let mut marginMode: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = marginModequeryVariable.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
});
let mut swap: bool = marketType.as_str() == Some("swap");
if swap {
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_timestamp".into(), since.clone()); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("market".into(), marketType.clone()); }
}
if (market != Value::Null) {
let mut marketIdRequest: Value = Value::Str("symbol".into());
if swap {
marketIdRequest = Value::Str("instrument_id".into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&marketIdRequest), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let mut response: Value = Value::Null;
if (marginMode != Value::Null) || (marketType.as_str() == Some("margin")) {
marketType = Value::Str("margin".into());
let __ws_arg_15 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_get_margin_order_current(&[__ws_arg_15]).await;
} else if (marketType.as_str() == Some("spot")) {
let __ws_arg_16 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_get_spot_order_current(&[__ws_arg_16]).await;
} else if (marketType.as_str() == Some("swap")) {
let __ws_arg_17 = self.extend(request, &[query]);
response = self.private_swap_get_trade_open_orders(&[__ws_arg_17]).await;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenOrders() not support this market type".into()))));
}
//
// spot and margin
//
// {
// "code": 0,
// "data": [
// {
// "symbol": "BTC_USDT",
// "order_id": "dd3164b333a4afa9d5730bb87f6db8b3",
// "created_date": 1562303547,
// "finished_date": 0,
// "price": 0.1,
// "amount": 1,
// "cash_amount": 1,
// "executed_amount": 0,
// "avg_price": 0,
// "status": 1,
// "type": "buy",
// "kind": "margin"
// }
// ]
// }
//
// swap
//
// {
// "code": 0,
// "data": [
// {
// "order_id": "1590898207657824256",
// "instrument_id": "BTCUSDTPERP",
// "margin_mode": "crossed",
// "contract_val": "0.001",
// "type": 1,
// "order_type": 0,
// "price": "14000",
// "size": "6",
// "filled_qty": "0",
// "price_avg": "0",
// "fee": "0",
// "state": 0,
// "leverage": "20",
// "turnover": "0",
// "has_stop": 0,
// "insert_time": 1668134664828,
// "time_stamp": 1668134664828
// },
// ...
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name digifinex#fetchOrders
* @description fetches information on multiple orders made by the user
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-all-orders-including-history-orders
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#historyorder
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut marketType: Value = Value::Null;
let mut paramsMarketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchOrders".into()), &[market.clone(), params]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsMarketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut marginModequeryVariable = self.handle_margin_mode_and_params(Value::Str("fetchOrders".into()), &[paramsMarketType]);
let mut marginMode: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = marginModequeryVariable.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
});
if (marketType.as_str() == Some("swap")) {
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_timestamp".into(), since.clone()); }
}
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("market".into(), marketType.clone()); }
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_time".into(), self.parse_to_int((match ((since).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }))); }; // default 3 days from now, max 30 days
}
}
if (market != Value::Null) {
let mut marketIdRequest: Value = Value::Str("symbol".into());
if (marketType.as_str() == Some("swap")) {
marketIdRequest = Value::Str("instrument_id".into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&marketIdRequest), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut response: Value = Value::Null;
if (marginMode != Value::Null) || (marketType.as_str() == Some("margin")) {
marketType = Value::Str("margin".into());
let __ws_arg_18 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_get_margin_order_history(&[__ws_arg_18]).await;
} else if (marketType.as_str() == Some("spot")) {
let __ws_arg_19 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_get_spot_order_history(&[__ws_arg_19]).await;
} else if (marketType.as_str() == Some("swap")) {
let __ws_arg_20 = self.extend(request, &[query]);
response = self.private_swap_get_trade_history_orders(&[__ws_arg_20]).await;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOrders() not support this market type".into()))));
}
//
// spot and margin
//
// {
// "code": 0,
// "data": [
// {
// "symbol": "BTC_USDT",
// "order_id": "dd3164b333a4afa9d5730bb87f6db8b3",
// "created_date": 1562303547,
// "finished_date": 0,
// "price": 0.1,
// "amount": 1,
// "cash_amount": 1,
// "executed_amount": 0,
// "avg_price": 0,
// "status": 1,
// "type": "buy",
// "kind": "margin"
// }
// ]
// }
//
// swap
//
// {
// "code": 0,
// "data": [
// {
// "order_id": "1590136768156405760",
// "instrument_id": "BTCUSDTPERP",
// "margin_mode": "crossed",
// "contract_val": "0.001",
// "type": 1,
// "order_type": 8,
// "price": "18660.2",
// "size": "1",
// "filled_qty": "1",
// "price_avg": "18514.5",
// "fee": "0.00925725",
// "state": 2,
// "leverage": "20",
// "turnover": "18.5145",
// "has_stop": 0,
// "insert_time": 1667953123526,
// "time_stamp": 1667953123596
// },
// ...
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name digifinex#fetchOrder
* @description fetches information on an order made by the user
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-order-status
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#orderinfo
* @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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut marketType: Value = Value::Null;
let mut paramsMarketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchOrder".into()), &[market.clone(), params]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsMarketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut marginModequeryVariable = self.handle_margin_mode_and_params(Value::Str("fetchOrder".into()), &[paramsMarketType]);
let mut marginMode: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = marginModequeryVariable.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("order_id".to_string(), id.clone());
m
});
if (marketType.as_str() == Some("swap")) {
if (market != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instrument_id".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("market".into(), marketType.clone()); }
}
let mut response: Value = Value::Null;
if (marginMode != Value::Null) || (marketType.as_str() == Some("margin")) {
marketType = Value::Str("margin".into());
let __ws_arg_21 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_get_margin_order(&[__ws_arg_21]).await;
} else if (marketType.as_str() == Some("spot")) {
let __ws_arg_22 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_get_spot_order(&[__ws_arg_22]).await;
} else if (marketType.as_str() == Some("swap")) {
let __ws_arg_23 = self.extend(request, &[query]);
response = self.private_swap_get_trade_order_info(&[__ws_arg_23]).await;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOrder() not support this market type".into()))));
}
//
// spot and margin
//
// {
// "code": 0,
// "data": [
// {
// "symbol": "BTC_USDT",
// "order_id": "dd3164b333a4afa9d5730bb87f6db8b3",
// "created_date": 1562303547,
// "finished_date": 0,
// "price": 0.1,
// "amount": 1,
// "cash_amount": 1,
// "executed_amount": 0,
// "avg_price": 0,
// "status": 1,
// "type": "buy",
// "kind": "margin"
// }
// ]
// }
//
// swap
//
// {
// "code": 0,
// "data": {
// "order_id": "1590923061186531328",
// "instrument_id": "ETHUSDTPERP",
// "margin_mode": "crossed",
// "contract_val": "0.01",
// "type": 1,
// "order_type": 0,
// "price": "900",
// "size": "6",
// "filled_qty": "0",
// "price_avg": "0",
// "fee": "0",
// "state": 0,
// "leverage": "20",
// "turnover": "0",
// "has_stop": 0,
// "insert_time": 1668140590372,
// "time_stamp": 1668140590372
// }
// }
//
let mut data: Value = self.safe_value_k(response, "data", &[]);
let mut order: Value = (if (marketType.as_str() == Some("swap")) { data.clone() } else { self.safe_value(data, Value::Int(0), &[]) });
if (order == Value::Null) {
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchOrder() order ".into())).into()), to_string_val(&id)).into()), Value::Str(" not found".into()))));
}
return self.parse_order(order, &[market]);
Value::Null
}
/*
* @method
* @name digifinex#fetchMyTrades
* @description fetch all trades made by the user
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#customer-39-s-trades
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#historytrade
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut marketType: Value = Value::Null;
let mut paramsMarketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchMyTrades".into()), &[market.clone(), params]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsMarketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut marginModequeryVariable = self.handle_margin_mode_and_params(Value::Str("fetchMyTrades".into()), &[paramsMarketType]);
let mut marginMode: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (marketType.as_str() == Some("swap")) {
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_timestamp".into(), since.clone()); }
}
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("market".into(), marketType.clone()); }
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_time".into(), self.parse_to_int((match ((since).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }))); }; // default 3 days from now, max 30 days
}
}
let mut marketIdRequest: Value = Value::Str("symbol".into());
if (marketType.as_str() == Some("swap")) {
marketIdRequest = Value::Str("instrument_id".into());
}
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&marketIdRequest), self.safe_string_k(market.clone(), "id", &[])); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut response: Value = Value::Null;
if (marginMode != Value::Null) || (marketType.as_str() == Some("margin")) {
marketType = Value::Str("margin".into());
let __ws_arg_24 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_get_margin_mytrades(&[__ws_arg_24]).await;
} else if (marketType.as_str() == Some("spot")) {
let __ws_arg_25 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_get_spot_mytrades(&[__ws_arg_25]).await;
} else if (marketType.as_str() == Some("swap")) {
let __ws_arg_26 = self.extend(request, &[query]);
response = self.private_swap_get_trade_history_trades(&[__ws_arg_26]).await;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchMyTrades() not support this market type".into()))));
}
//
// spot and margin
//
// {
// "list":[
// {
// "timestamp":1639506068,
// "is_maker":false,
// "id":"8975951332",
// "amount":31.83,
// "side":"sell_market",
// "symbol":"DOGE_USDT",
// "fee_currency":"USDT",
// "fee":0.01163774826
// ,"order_id":"32b169792f4a7a19e5907dc29fc123d4",
// "price":0.182811
// }
// ],
// "code": 0
// }
//
// swap
//
// {
// "code": 0,
// "data": [
// {
// "trade_id": "1590136768424841218",
// "instrument_id": "BTCUSDTPERP",
// "order_id": "1590136768156405760",
// "type": 1,
// "order_type": 8,
// "price": "18514.5",
// "size": "1",
// "fee": "0.00925725",
// "close_profit": "0",
// "leverage": "20",
// "trade_type": 0,
// "match_role": 1,
// "trade_time": 1667953123562
// },
// ...
// ]
// }
//
let mut responseRequest: Value = Value::Str("list".into());
if (marketType.as_str() == Some("swap")) {
responseRequest = Value::Str("data".into());
}
let mut data: Value = self.safe_list(response, responseRequest, &[Value::from(vec![])]);
return self.parse_trades(data, &[market, since, limit]);
Value::Null
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Value {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]);
Value::Null
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// spot and margin
//
// {
// "currency_mark": "BTC",
// "type": 100234,
// "num": -10,
// "balance": 0.1,
// "time": 1546272000
// }
//
// swap
//
// {
// "currency": "USDT",
// "finance_type": 17,
// "change": "-3.01",
// "timestamp": 1650809432000
// }
//
let mut type_var: Value = self.parse_ledger_entry_type(self.safe_string2(item.clone(), Value::Str("type".into()), Value::Str("finance_type".into()), &[]));
let mut currencyId: Value = self.safe_string2(item.clone(), Value::Str("currency_mark".into()), Value::Str("currency".into()), &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[currency.clone()]);
let mut currencyResolved: Value = self.safe_currency(currencyId, &[currency]);
let mut amount: Value = self.safe_number2(item.clone(), Value::Str("num".into()), Value::Str("change".into()), &[]);
let mut after: Value = self.safe_number_k(item.clone(), "balance", &[]);
let mut timestamp: Value = self.safe_timestamp_k(item.clone(), "time", &[]);
if (timestamp == Value::Null) {
timestamp = self.safe_integer_k(item.clone(), "timestamp", &[]);
}
return self.safe_ledger_entry(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), item);
m.insert("id".to_string(), Value::Null);
m.insert("direction".to_string(), Value::Null);
m.insert("account".to_string(), Value::Null);
m.insert("referenceId".to_string(), Value::Null);
m.insert("referenceAccount".to_string(), Value::Null);
m.insert("type".to_string(), type_var);
m.insert("currency".to_string(), code);
m.insert("amount".to_string(), amount);
m.insert("before".to_string(), Value::Null);
m.insert("after".to_string(), after);
m.insert("status".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("fee".to_string(), Value::Null);
m
}), &[currencyResolved]);
Value::Null
}
/*
* @method
* @name digifinex#fetchLedger
* @description fetch the history of changes, actions done by the user or operations that altered the balance of the user
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#spot-margin-otc-financial-logs
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#bills
* @param {string} [code] unified currency code, default is undefined
* @param {int} [since] timestamp in ms of the earliest ledger entry, default is undefined
* @param {int} [limit] max number of ledger entries to return, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ledger structure]{@link https://docs.ccxt.com/?id=ledger-entry-structure}
*/
pub async fn fetch_ledger(&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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut marketType: Value = Value::Null;
let mut paramsMarketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchLedger".into()), &[Value::Null, params]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsMarketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut marginModequeryVariable = self.handle_margin_mode_and_params(Value::Str("fetchLedger".into()), &[paramsMarketType]);
let mut marginMode: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (marketType.as_str() == Some("swap")) {
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_timestamp".into(), since.clone()); }
}
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("market".into(), marketType.clone()); }
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_time".into(), self.parse_to_int((match ((since).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }))); }; // default 3 days from now, max 30 days
}
}
let mut currencyIdRequest: Value = Value::Str("currency_mark".into());
if (marketType.as_str() == Some("swap")) {
currencyIdRequest = Value::Str("currency".into());
}
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(¤cyIdRequest), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut response: Value = Value::Null;
if (marginMode != Value::Null) || (marketType.as_str() == Some("margin")) {
marketType = Value::Str("margin".into());
let __ws_arg_27 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_get_margin_financelog(&[__ws_arg_27]).await;
} else if (marketType.as_str() == Some("spot")) {
let __ws_arg_28 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_get_spot_financelog(&[__ws_arg_28]).await;
} else if (marketType.as_str() == Some("swap")) {
let __ws_arg_29 = self.extend(request, &[query]);
response = self.private_swap_get_account_finance_record(&[__ws_arg_29]).await;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchLedger() not support this market type".into()))));
}
//
// spot and margin
//
// {
// "code": 0,
// "data": {
// "total": 521,
// "finance": [
// {
// "currency_mark": "BTC",
// "type": 100234,
// "num": 28457,
// "balance": 0.1,
// "time": 1546272000
// }
// ]
// }
// }
//
// swap
//
// {
// "code": 0,
// "data": [
// {
// "currency": "USDT",
// "finance_type": 17,
// "change": "3.01",
// "timestamp": 1650809432000
// },
// ]
// }
//
let mut ledger: Value = Value::Null;
if (marketType.as_str() == Some("swap")) {
ledger = self.safe_list_k(response.clone(), "data", &[Value::from(vec![])]);
} else {
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
ledger = self.safe_list_k(data, "finance", &[Value::from(vec![])]);
}
return self.parse_ledger(ledger, &[currency, since, limit]);
Value::Null
}
pub fn parse_deposit_address(&self, mut depositAddress: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "addressTag":"",
// "address":"0xf1104d9f8624f89775a3e9d480fc0e75a8ef4373",
// "currency":"USDT",
// "chain":"ERC20"
// }
//
let mut address: Value = self.safe_string_k(depositAddress.clone(), "address", &[]);
let mut tag: Value = self.safe_string_k(depositAddress.clone(), "addressTag", &[]);
let mut currencyId: Value = self.safe_string_upper_k(depositAddress.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), depositAddress);
m.insert("currency".to_string(), code);
m.insert("network".to_string(), Value::Null);
m.insert("address".to_string(), address);
m.insert("tag".to_string(), tag);
m
});
Value::Null
}
/*
* @method
* @name digifinex#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#deposit-address-inquiry
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [address structure]{@link https://docs.ccxt.com/?id=address-structure}
*/
pub async fn fetch_deposit_address(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_30 = self.extend(request, &[params]);
let mut response: Value = self.private_spot_get_deposit_address(&[__ws_arg_30]).await;
//
// {
// "data":[
// {
// "addressTag":"",
// "address":"0xf1104d9f8624f89775a3e9d480fc0e75a8ef4373",
// "currency":"USDT",
// "chain":"ERC20"
// }
// ],
// "code":200
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut addresses: Value = self.parse_deposit_addresses(data, &[Value::from(vec![currency.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null)])]);
let mut address: Value = self.safe_dict(addresses, code.clone(), &[]);
if (address == Value::Null) {
panic!("{}", crate::exchange_errors::invalid_address(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchDepositAddress() did not return an address for ".into())).into()), code).into()), Value::Str(" - create the deposit address in the user settings on the exchange website first.".into()))));
}
return address;
Value::Null
}
pub async fn fetch_transactions_by_type(&mut self, mut type_var: 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.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("currency".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("size".into(), crate::runtime::Math::min(&Value::Int(500), &limit)); }
}
let mut response: Value = Value::Null;
if (type_var.as_str() == Some("deposit")) {
let __ws_arg_31 = self.extend(request.clone(), &[params.clone()]);
response = self.private_spot_get_deposit_history(&[__ws_arg_31]).await;
} else {
let __ws_arg_32 = self.extend(request, &[params]);
response = self.private_spot_get_withdraw_history(&[__ws_arg_32]).await;
}
//
// {
// "code": 200,
// "data": [
// {
// "id": 1171,
// "currency": "xrp",
// "hash": "ed03094b84eafbe4bc16e7ef766ee959885ee5bcb265872baaa9c64e1cf86c2b",
// "chain": "",
// "amount": 7.457467,
// "address": "rae93V8d2mdoUQHwBDBdM4NHCMehRJAsbm",
// "memo": "100040",
// "fee": 0,
// "state": "safe",
// "created_date": "2020-04-20 11:23:00",
// "finished_date": "2020-04-20 13:23:00"
// },
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_transactions(data, &[currency, since, limit, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var);
m
})]);
Value::Null
}
/*
* @method
* @name digifinex#fetchDeposits
* @description fetch all deposits made to an account
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#deposit-history
* @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
* @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.fetch_transactions_by_type(Value::Str("deposit".into()), &[code, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name digifinex#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#withdrawal-history
* @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
* @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.fetch_transactions_by_type(Value::Str("withdrawal".into()), &[code, since, limit, params]).await;
Value::Null
}
pub fn parse_transaction_status(&self, mut status: Value) -> Value {
// deposit state includes: 1 (in deposit), 2 (to be confirmed), 3 (successfully deposited), 4 (stopped)
// withdrawal state includes: 1 (application in progress), 2 (to be confirmed), 3 (completed), 4 (rejected)
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1".to_string(), Value::Str("pending".into()));
m.insert("2".to_string(), Value::Str("pending".into()));
m.insert("3".to_string(), Value::Str("ok".into()));
m.insert("4".to_string(), Value::Str("failed".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// withdraw
//
// {
// "code": 200,
// "withdraw_id": 700
// }
//
// fetchDeposits, fetchWithdrawals
//
// {
// "id": 1171,
// "currency": "xrp",
// "hash": "ed03094b84eafbe4bc16e7ef766ee959885ee5bcb265872baaa9c64e1cf86c2b",
// "chain": "",
// "amount": 7.457467,
// "address": "rae93V8d2mdoUQHwBDBdM4NHCMehRJAsbm",
// "memo": "100040",
// "fee": 0,
// "state": "safe",
// "created_date": "2020-04-20 11:23:00",
// "finished_date": "2020-04-20 13:23:00"
// }
//
let mut id: Value = self.safe_string2(transaction.clone(), Value::Str("id".into()), Value::Str("withdraw_id".into()), &[]);
let mut address: Value = self.safe_string_k(transaction.clone(), "address", &[]);
let mut tag: Value = self.safe_string_k(transaction.clone(), "memo", &[]);
let mut txid: Value = self.safe_string_k(transaction.clone(), "hash", &[]);
let mut currencyId: Value = self.safe_string_upper_k(transaction.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[currency]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(transaction.clone(), "created_date", &[]));
let mut updated: Value = self.parse8601(self.safe_string_k(transaction.clone(), "finished_date", &[]));
let mut status: Value = self.parse_transaction_status(self.safe_string_k(transaction.clone(), "state", &[]));
let mut amount: Value = self.safe_number_k(transaction.clone(), "amount", &[]);
let mut feeCost: Value = self.safe_number_k(transaction.clone(), "fee", &[]);
let mut fee: Value = Value::Null;
if (feeCost != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), code.clone());
m.insert("cost".to_string(), feeCost);
m
});
}
let mut network: Value = self.safe_string_k(transaction.clone(), "chain", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction);
m.insert("id".to_string(), id);
m.insert("txid".to_string(), txid);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("network".to_string(), network);
m.insert("address".to_string(), address.clone());
m.insert("addressTo".to_string(), address);
m.insert("addressFrom".to_string(), Value::Null);
m.insert("tag".to_string(), tag.clone());
m.insert("tagTo".to_string(), tag);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("amount".to_string(), amount);
m.insert("currency".to_string(), code);
m.insert("status".to_string(), status);
m.insert("updated".to_string(), updated);
m.insert("internal".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
});
Value::Null
}
pub fn parse_transfer_status(&self, mut status: Value) -> Option<String> {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("0".to_string(), Value::Str("ok".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub fn parse_transfer(&self, mut transfer: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// transfer between spot, margin and OTC
//
// {
// "code": 0
// }
//
// transfer between spot and swap
//
// {
// "code": 0,
// "data": {
// "type": 2,
// "currency": "USDT",
// "transfer_amount": "5"
// }
// }
//
// fetchTransfers
//
// {
// "transfer_id": 130524,
// "type": 1,
// "currency": "USDT",
// "amount": "24",
// "timestamp": 1666505659000
// }
//
let mut fromAccount: Value = Value::Null;
let mut toAccount: Value = Value::Null;
let mut data: Value = self.safe_dict_k(transfer.clone(), "data", &[transfer.clone()]);
let mut type_var: Option<i64> = self.safe_integer_k(data.clone(), "type", &[]).as_i64();
if (type_var == Some(1)) {
fromAccount = Value::Str("spot".into());
toAccount = Value::Str("swap".into());
} else if (type_var == Some(2)) {
fromAccount = Value::Str("swap".into());
toAccount = Value::Str("spot".into());
}
let mut timestamp: Value = self.safe_integer_k(transfer.clone(), "timestamp", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transfer.clone());
m.insert("id".to_string(), self.safe_string_k(transfer.clone(), "transfer_id", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("currency".to_string(), self.safe_currency_code(self.safe_string_k(data.clone(), "currency", &[]), &[currency]));
m.insert("amount".to_string(), self.safe_number2(data, Value::Str("amount".into()), Value::Str("transfer_amount".into()), &[]));
m.insert("fromAccount".to_string(), fromAccount);
m.insert("toAccount".to_string(), toAccount);
m.insert("status".to_string(), self.parse_transfer_status(self.safe_string_k(transfer, "code", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m
});
Value::Null
}
/*
* @method
* @name digifinex#transfer
* @description transfer currency internally between wallets on the same account
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#transfer-assets-among-accounts
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#accounttransfer
* @param {string} code unified currency code
* @param {float} amount amount to transfer
* @param {string} fromAccount 'spot', 'swap', 'margin', 'OTC' - account to transfer from
* @param {string} toAccount 'spot', 'swap', 'margin', 'OTC' - account to transfer to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transfer structure]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn transfer(&mut self, mut code: Value, mut amount: Value, mut fromAccount: Value, mut toAccount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut currencyId: Value = currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut accountsByType: Value = self.safe_dict_k(self.options.clone(), "accountsByType", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fromId: Value = self.safe_string(accountsByType.clone(), fromAccount.clone(), &[fromAccount.clone()]);
let mut toId: Value = self.safe_string(accountsByType, toAccount.clone(), &[toAccount.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut fromSwap: bool = fromAccount.as_str() == Some("swap");
let mut toSwap: bool = toAccount.as_str() == Some("swap");
let mut response: Value = Value::Null;
let mut amountString: Value = self.currency_to_precision(code, amount, &[]);
if fromSwap || toSwap {
if (fromId.as_str() != Some("1")) && (toId.as_str() != Some("1")) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" transfer() supports transferring between spot and swap, spot and margin, spot and OTC only".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), (if toSwap { Value::Int(1) } else { Value::Int(2) })); }; // 1 = spot to swap, 2 = swap to spot
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("currency".into(), currencyId.clone()); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("transfer_amount".into(), amountString.clone()); }
//
// {
// "code": 0,
// "data": {
// "type": 2,
// "currency": "USDT",
// "transfer_amount": "5"
// }
// }
//
let __ws_arg_33 = self.extend(request.clone(), &[params.clone()]);
response = self.private_swap_post_account_transfer(&[__ws_arg_33]).await;
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("currency_mark".into(), currencyId); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("num".into(), amountString); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("from".into(), fromId); }; // 1 = SPOT, 2 = MARGIN, 3 = OTC
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("to".into(), toId); }; // 1 = SPOT, 2 = MARGIN, 3 = OTC
//
// {
// "code": 0
// }
//
let __ws_arg_34 = self.extend(request, &[params]);
response = self.private_spot_post_transfer(&[__ws_arg_34]).await;
}
if (response == Value::Null) {
panic!("{}", crate::exchange_errors::null_response(format!("{}{}", self.id.clone(), Value::Str(" transfer() returned empty response".into()))));
}
return self.parse_transfer(response, &[currency]);
Value::Null
}
/*
* @method
* @name digifinex#withdraw
* @description make a withdrawal
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {string} tag
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut tag = 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 tagWithdrawTagparamsWithdrawTagVariable = self.handle_withdraw_tag_and_params(tag, params);
let mut tagWithdrawTag: Value = tagWithdrawTagparamsWithdrawTagVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWithdrawTag: Value = tagWithdrawTagparamsWithdrawTagVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
self.check_address(&[address.clone()]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("address".to_string(), address);
m.insert("amount".to_string(), self.currency_to_precision(code, amount, &[]));
m.insert("currency".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (tagWithdrawTag != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("memo".into(), tagWithdrawTag); }
}
let __ws_arg_35 = self.extend(request, &[paramsWithdrawTag]);
let mut response: Value = self.private_spot_post_withdraw_new(&[__ws_arg_35]).await;
return self.parse_transaction(response, &[currency]);
Value::Null
}
pub async fn fetch_borrow_interest(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut symbol = get_arg(optional_args, 1, Value::Null);
let mut since = get_arg(optional_args, 2, Value::Null);
let mut limit = get_arg(optional_args, 3, Value::Null);
let mut params = get_arg(optional_args, 4, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let __ws_arg_36 = self.extend(request, &[params]);
let mut response: Value = self.private_spot_get_margin_positions(&[__ws_arg_36]).await;
//
// {
// "margin": "45.71246418952618",
// "code": 0,
// "margin_rate": "7.141978570340037",
// "positions": [
// {
// "amount": 0.0006103,
// "side": "go_long",
// "entry_price": 31428.72,
// "liquidation_rate": 0.3,
// "liquidation_price": 10225.335481159,
// "unrealized_roe": -0.0076885829266987,
// "symbol": "BTC_USDT",
// "unrealized_pnl": -0.049158102631999,
// "leverage_ratio": 3
// }
// ],
// "unrealized_pnl": "-0.049158102631998504"
// }
//
let mut rows: Value = self.safe_list_k(response, "positions", &[]);
let mut interest: Value = self.parse_borrow_interests(rows, &[market]);
return self.filter_by_currency_since_limit(interest, &[code, since, limit]);
Value::Null
}
pub fn parse_borrow_interest(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "amount": 0.0006103,
// "side": "go_long",
// "entry_price": 31428.72,
// "liquidation_rate": 0.3,
// "liquidation_price": 10225.335481159,
// "unrealized_roe": -0.0076885829266987,
// "symbol": "BTC_USDT",
// "unrealized_pnl": -0.049158102631999,
// "leverage_ratio": 3
// }
//
let mut marketId: Value = self.safe_string_k(info.clone(), "symbol", &[]);
let mut amountString: Value = self.safe_string_k(info.clone(), "amount", &[]);
let mut leverageString: Value = self.safe_string_k(info.clone(), "leverage_ratio", &[]);
let mut amountInvested: Value = crate::precise::Precise::stringDiv(&amountString, &leverageString);
let mut amountBorrowed: Value = crate::precise::Precise::stringSub(&amountString, &amountInvested);
let mut currency: Value = (if (market == Value::Null) { Value::Null } else { market.as_map().and_then(|__m| __m.get("base")).cloned().unwrap_or(Value::Null) });
let mut symbol: Value = self.safe_symbol(marketId, &[market]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), info);
m.insert("symbol".to_string(), symbol);
m.insert("currency".to_string(), currency);
m.insert("interest".to_string(), Value::Null);
m.insert("interestRate".to_string(), Value::Float(0.001));
m.insert("amountBorrowed".to_string(), self.parse_number(amountBorrowed, &[]));
m.insert("marginMode".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name digifinex#fetchCrossBorrowRate
* @description fetch the rate of interest to borrow a currency for margin trading
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#margin-assets
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [borrow rate structure]{@link https://github.com/ccxt/ccxt/wiki/Manual#borrow-rate-structure}
*/
pub async fn fetch_cross_borrow_rate(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let __ws_arg_37 = self.extend(request, &[params]);
let mut response: Value = self.private_spot_get_margin_assets(&[__ws_arg_37]).await;
//
// {
// "list": [
// {
// "valuation_rate": 1,
// "total": 1.92012186174,
// "free": 1.92012186174,
// "currency": "USDT"
// },
// ],
// "total": 45.133305540922,
// "code": 0,
// "unrealized_pnl": 0,
// "free": 45.133305540922,
// "equity": 45.133305540922
// }
//
let mut data: Value = self.safe_list_k(response, "list", &[Value::from(vec![])]);
let mut result: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_649: bool = true;
while { if !__for_first_649 { 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_649 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut entry: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if (self.safe_string_k(entry.clone(), "currency", &[]).as_str() == code.as_str()) {
result = entry;
}
}
}
let mut currency: Value = self.currency(code);
return self.parse_borrow_rate(result, &[currency]);
Value::Null
}
/*
* @method
* @name digifinex#fetchCrossBorrowRates
* @description fetch the borrow interest rates of all currencies
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#margin-assets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [borrow rate structures]{@link https://docs.ccxt.com/?id=borrow-rate-structure}
*/
pub async fn fetch_cross_borrow_rates(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.private_spot_get_margin_assets(&[params]).await;
//
// {
// "list": [
// {
// "valuation_rate": 1,
// "total": 1.92012186174,
// "free": 1.92012186174,
// "currency": "USDT"
// },
// ],
// "total": 45.133305540922,
// "code": 0,
// "unrealized_pnl": 0,
// "free": 45.133305540922,
// "equity": 45.133305540922
// }
//
let mut result: Value = self.safe_list_k(response, "list", &[Value::from(vec![])]);
return self.parse_borrow_rates(result, Value::Str("currency".into()));
Value::Null
}
pub fn parse_borrow_rate(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "valuation_rate": 1,
// "total": 1.92012186174,
// "free": 1.92012186174,
// "currency": "USDT"
// }
//
let mut currencyId: Value = self.safe_string_k(info.clone(), "currency", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), self.safe_currency_code(currencyId, &[currency]));
m.insert("rate".to_string(), Value::Float(0.001));
m.insert("period".to_string(), Value::Int(86400000));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("info".to_string(), info);
m
});
Value::Null
}
pub fn parse_borrow_rates(&self, mut info: Value, mut codeKey: Value) -> Value {
//
// {
// "valuation_rate": 1,
// "total": 1.92012186174,
// "free": 1.92012186174,
// "currency": "USDT"
// },
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_650: bool = true;
while { if !__for_first_650 { 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_650 = false; i.as_f64().unwrap_or(f64::NAN) < ((info.len() as i64) as f64) } {
let mut item: Value = info.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 currency: Value = self.safe_string(item.clone(), codeKey.clone(), &[]);
let mut code: Value = self.safe_currency_code(currency, &[]);
let mut borrowRate: Value = self.parse_borrow_rate(item, &[]);
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), borrowRate); }
}
}
}
return result;
Value::Null
}
/*
* @method
* @name digifinex#fetchFundingRate
* @description fetch the current funding rate
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#currentfundingrate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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
}));
if (self.markets.clone() == Value::Null) {
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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_38 = self.extend(request, &[params]);
let mut response: Value = self.public_swap_get_public_funding_rate(&[__ws_arg_38]).await;
//
// {
// "code": 0,
// "data": {
// "instrument_id": "BTCUSDTPERP",
// "funding_rate": "-0.00012",
// "funding_time": 1662710400000,
// "next_funding_rate": "0.0001049907085171607",
// "next_funding_time": 1662739200000
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_funding_rate(data, &[market]);
Value::Null
}
/*
* @method
* @name digifinex#fetchFundingInterval
* @description fetch the current funding rate interval
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#currentfundingrate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn fetch_funding_interval(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_funding_rate(symbol, &[params]).await;
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);
//
// {
// "instrument_id": "BTCUSDTPERP",
// "funding_rate": "-0.00012",
// "funding_time": 1662710400000,
// "next_funding_rate": "0.0001049907085171607",
// "next_funding_time": 1662739200000
// }
//
let mut marketId: Value = self.safe_string_k(contract.clone(), "instrument_id", &[]);
let mut timestamp: Value = self.safe_integer_k(contract.clone(), "funding_time", &[]);
let mut nextTimestamp: Value = self.safe_integer_k(contract.clone(), "next_funding_time", &[]);
let mut fundingTimeString: Value = self.safe_string_k(contract.clone(), "funding_time", &[]);
let mut nextFundingTimeString: Value = self.safe_string_k(contract.clone(), "next_funding_time", &[]);
let mut millisecondsInterval: Value = crate::precise::Precise::stringSub(&nextFundingTimeString, &fundingTimeString);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), contract.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market]));
m.insert("markPrice".to_string(), Value::Null);
m.insert("indexPrice".to_string(), Value::Null);
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.clone(), "funding_rate", &[]));
m.insert("fundingTimestamp".to_string(), timestamp.clone());
m.insert("fundingDatetime".to_string(), self.iso8601(timestamp));
m.insert("nextFundingRate".to_string(), self.safe_number_k(contract, "next_funding_rate", &[]));
m.insert("nextFundingTimestamp".to_string(), nextTimestamp.clone());
m.insert("nextFundingDatetime".to_string(), self.iso8601(nextTimestamp));
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(), self.parse_funding_interval(millisecondsInterval).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m
});
Value::Null
}
pub fn parse_funding_interval(&self, mut interval: Value) -> Option<String> {
let mut intervals: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("3600000".to_string(), Value::Str("1h".into()));
m.insert("14400000".to_string(), Value::Str("4h".into()));
m.insert("28800000".to_string(), Value::Str("8h".into()));
m.insert("57600000".to_string(), Value::Str("16h".into()));
m.insert("86400000".to_string(), Value::Str("24h".into()));
m
});
return self.safe_string(intervals, interval.clone(), &[interval.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name digifinex#fetchFundingRateHistory
* @description fetches historical funding rate prices
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#fundingratehistory
* @param {string} symbol unified symbol of the market to fetch the funding rate history for
* @param {int} [since] timestamp in ms of the earliest funding rate to fetch
* @param {int} [limit] the maximum amount of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure} to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure}
*/
pub async fn fetch_funding_rate_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(" fetchFundingRateHistory() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
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(" fetchFundingRateHistory() supports swap contracts only".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_timestamp".into(), since.clone()); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_39 = self.extend(request, &[params]);
let mut response: Value = self.public_swap_get_public_funding_rate_history(&[__ws_arg_39]).await;
//
// {
// "code": 0,
// "data": {
// "instrument_id": "BTCUSDTPERP",
// "funding_rates": [
// {
// "rate": "-0.00375",
// "time": 1607673600000
// },
// ...
// ]
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut result: Value = self.safe_list_k(data.clone(), "funding_rates", &[Value::from(vec![])]);
let mut rates: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_651: bool = true;
while { if !__for_first_651 { 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_651 = false; i.as_f64().unwrap_or(f64::NAN) < ((result.len() as i64) as f64) } {
let mut entry: Value = result.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 marketId: Value = self.safe_string_k(data.clone(), "instrument_id", &[]);
let mut symbolInner: Value = self.safe_symbol(marketId, &[]);
let mut timestamp: Value = self.safe_integer_k(entry.clone(), "time", &[]);
append_to_array(&mut rates, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), entry.clone());
m.insert("symbol".to_string(), symbolInner);
m.insert("fundingRate".to_string(), self.safe_number_k(entry, "rate", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
}));
}
}
let mut sorted: Value = self.sort_by(rates, Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[symbol, since, limit]);
Value::Null
}
/*
* @method
* @name digifinex#fetchTradingFee
* @description fetch the trading fees for a market
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#tradingfee
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [fee structure]{@link https://docs.ccxt.com/?id=fee-structure}
*/
pub async fn fetch_trading_fee(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchTradingFee() supports swap markets only".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_40 = self.extend(request, &[params]);
let mut response: Value = self.private_swap_get_account_trading_fee_rate(&[__ws_arg_40]).await;
//
// {
// "code": 0,
// "data": {
// "instrument_id": "BTCUSDTPERP",
// "taker_fee_rate": "0.0005",
// "maker_fee_rate": "0.0003"
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_trading_fee(data, &[market]);
Value::Null
}
pub fn parse_trading_fee(&self, mut fee: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "instrument_id": "BTCUSDTPERP",
// "taker_fee_rate": "0.0005",
// "maker_fee_rate": "0.0003"
// }
//
let mut marketId: Value = self.safe_string_k(fee.clone(), "instrument_id", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), fee.clone());
m.insert("symbol".to_string(), symbol);
m.insert("maker".to_string(), self.safe_number_k(fee.clone(), "maker_fee_rate", &[]));
m.insert("taker".to_string(), self.safe_number_k(fee, "taker_fee_rate", &[]));
m.insert("percentage".to_string(), Value::Null);
m.insert("tierBased".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name digifinex#fetchPositions
* @description fetch all open positions
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#margin-positions
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#positions
* @param {string[]|undefined} symbols list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} 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.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
let mut marketType: Value = Value::Null;
if (symbolsNormalized != Value::Null) {
let mut symbol: Value = Value::Null;
if (matches!(&symbolsNormalized, Value::Arr(_))) {
let mut symbolsLength: f64 = ((symbolsNormalized.len() as i64) as f64);
if symbolsLength > ((1i64) as f64) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchPositions() symbols argument cannot contain more than 1 symbol".into()))));
}
symbol = symbolsNormalized.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
} else {
symbol = symbolsNormalized.clone();
}
market = self.market(symbol);
}
let mut paramsMarketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchPositions".into()), &[market.clone(), params]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsMarketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut marginModequeryVariable = self.handle_margin_mode_and_params(Value::Str("fetchPositions".into()), &[paramsMarketType]);
let mut marginMode: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (marginMode != Value::Null) {
marketType = Value::Str("margin".into());
}
if (market != Value::Null) {
let mut marketIdRequest: Value = Value::Str("symbol".into());
if (marketType.as_str() == Some("swap")) {
marketIdRequest = Value::Str("instrument_id".into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&marketIdRequest), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let mut response: Value = Value::Null;
if (marketType.as_str() == Some("spot")) || (marketType.as_str() == Some("margin")) {
let __ws_arg_41 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_get_margin_positions(&[__ws_arg_41]).await;
} else if (marketType.as_str() == Some("swap")) {
let __ws_arg_42 = self.extend(request, &[query]);
response = self.private_swap_get_account_positions(&[__ws_arg_42]).await;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchPositions() not support this market type".into()))));
}
//
// swap
//
// {
// "code": 0,
// "data": [
// {
// "instrument_id": "BTCUSDTPERP",
// "margin_mode": "crossed",
// "avail_position": "1",
// "avg_cost": "18369.3",
// "last": "18404.7",
// "leverage": "20",
// "liquidation_price": "451.12820512820264",
// "maint_margin_ratio": "0.005",
// "margin": "0.918465",
// "position": "1",
// "realized_pnl": "0",
// "unrealized_pnl": "0.03410000000000224",
// "unrealized_pnl_rate": "0.03712716325608732",
// "side": "long",
// "open_outstanding": "0",
// "risk_score": "0.495049504950495",
// "margin_ratio": "0.4029464788983229",
// "timestamp": 1667960497145
// },
// ...
// ]
// }
//
// margin
//
// {
// "margin": "77.71534772983289",
// "code": 0,
// "margin_rate": "10.284503769497306",
// "positions": [
// {
// "amount": 0.0010605,
// "side": "go_long",
// "entry_price": 18321.39,
// "liquidation_rate": 0.3,
// "liquidation_price": -52754.371758471,
// "unrealized_roe": -0.002784390267332,
// "symbol": "BTC_USDT",
// "unrealized_pnl": -0.010820048189999,
// "leverage_ratio": 5
// },
// ...
// ],
// "unrealized_pnl": "-0.10681600018999979"
// }
//
let mut positionRequest: Value = Value::Str("positions".into());
if (marketType.as_str() == Some("swap")) {
positionRequest = Value::Str("data".into());
}
let mut positions: Value = self.safe_list(response, positionRequest, &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_652: bool = true;
while { if !__for_first_652 { 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_652 = false; i.as_f64().unwrap_or(f64::NAN) < ((positions.len() as i64) as f64) } {
append_to_array(&mut result, self.parse_position(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), &[market.clone()]));
}
}
return self.filter_by_array_positions(result, Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name digifinex#fetchPosition
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#margin-positions
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#positions
* @description fetch data on a single open contract trade position
* @param {string} symbol unified market symbol of the market the position is held in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut marketType: Value = Value::Null;
let mut paramsMarketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchPosition".into()), &[market.clone(), params]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsMarketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut marginModequeryVariable = self.handle_margin_mode_and_params(Value::Str("fetchPosition".into()), &[paramsMarketType]);
let mut marginMode: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = marginModequeryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (marginMode != Value::Null) {
marketType = Value::Str("margin".into());
}
let mut marketIdRequest: Value = Value::Str("symbol".into());
if (marketType.as_str() == Some("swap")) {
marketIdRequest = Value::Str("instrument_id".into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&marketIdRequest), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
let mut response: Value = Value::Null;
if (marketType.as_str() == Some("spot")) || (marketType.as_str() == Some("margin")) {
let __ws_arg_43 = self.extend(request.clone(), &[query.clone()]);
response = self.private_spot_get_margin_positions(&[__ws_arg_43]).await;
} else if (marketType.as_str() == Some("swap")) {
let __ws_arg_44 = self.extend(request, &[query]);
response = self.private_swap_get_account_positions(&[__ws_arg_44]).await;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchPosition() not support this market type".into()))));
}
//
// swap
//
// {
// "code": 0,
// "data": [
// {
// "instrument_id": "BTCUSDTPERP",
// "margin_mode": "crossed",
// "avail_position": "1",
// "avg_cost": "18369.3",
// "last": "18388.9",
// "leverage": "20",
// "liquidation_price": "383.38712921065553",
// "maint_margin_ratio": "0.005",
// "margin": "0.918465",
// "position": "1",
// "realized_pnl": "0",
// "unrealized_pnl": "0.021100000000004115",
// "unrealized_pnl_rate": "0.02297311274790451",
// "side": "long",
// "open_outstanding": "0",
// "risk_score": "0.4901960784313725",
// "margin_ratio": "0.40486964045976204",
// "timestamp": 1667960241758
// }
// ]
// }
//
// margin
//
// {
// "margin": "77.71534772983289",
// "code": 0,
// "margin_rate": "10.284503769497306",
// "positions": [
// {
// "amount": 0.0010605,
// "side": "go_long",
// "entry_price": 18321.39,
// "liquidation_rate": 0.3,
// "liquidation_price": -52754.371758471,
// "unrealized_roe": -0.002784390267332,
// "symbol": "BTC_USDT",
// "unrealized_pnl": -0.010820048189999,
// "leverage_ratio": 5
// }
// ],
// "unrealized_pnl": "-0.10681600018999979"
// }
//
let mut dataRequest: Value = Value::Str("positions".into());
if (marketType.as_str() == Some("swap")) {
dataRequest = Value::Str("data".into());
}
let mut data: Value = self.safe_list(response.clone(), dataRequest, &[Value::from(vec![])]);
let mut position: Value = self.parse_position(data.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), &[market]);
if (marketType.as_str() == Some("swap")) {
return position;
} else {
add_element_to_object(&mut position, &Value::Str("collateral".into()), self.safe_number_k(response.clone(), "margin", &[]));
add_element_to_object(&mut position, &Value::Str("marginRatio".into()), self.safe_number_k(response, "margin_rate", &[]));
return position;
}
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// swap
//
// {
// "instrument_id": "BTCUSDTPERP",
// "margin_mode": "crossed",
// "avail_position": "1",
// "avg_cost": "18369.3",
// "last": "18388.9",
// "leverage": "20",
// "liquidation_price": "383.38712921065553",
// "maint_margin_ratio": "0.005",
// "margin": "0.918465",
// "position": "1",
// "realized_pnl": "0",
// "unrealized_pnl": "0.021100000000004115",
// "unrealized_pnl_rate": "0.02297311274790451",
// "side": "long",
// "open_outstanding": "0",
// "risk_score": "0.4901960784313725",
// "margin_ratio": "0.40486964045976204",
// "timestamp": 1667960241758
// }
//
// margin
//
// {
// "amount": 0.0010605,
// "side": "go_long",
// "entry_price": 18321.39,
// "liquidation_rate": 0.3,
// "liquidation_price": -52754.371758471,
// "unrealized_roe": -0.002784390267332,
// "symbol": "BTC_USDT",
// "unrealized_pnl": -0.010820048189999,
// "leverage_ratio": 5
// }
//
let mut marketId: Value = self.safe_string2(position.clone(), Value::Str("instrument_id".into()), Value::Str("symbol".into()), &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut marginMode: Value = self.safe_string_k(position.clone(), "margin_mode", &[]);
if (marginMode != Value::Null) {
marginMode = (if (marginMode.as_str() == Some("crossed")) { Value::Str("cross".into()) } else { Value::Str("isolated".into()) });
} else {
marginMode = Value::Str("crossed".into());
}
let mut timestamp: Value = self.safe_integer_k(position.clone(), "timestamp", &[]);
let mut side: Value = self.safe_string_k(position.clone(), "side", &[]);
if (side.as_str() == Some("go_long")) {
side = Value::Str("long".into());
} else if (side.as_str() == Some("go_short")) {
side = Value::Str("short".into());
}
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol);
m.insert("notional".to_string(), self.safe_number_k(position.clone(), "amount", &[]));
m.insert("marginMode".to_string(), marginMode);
m.insert("liquidationPrice".to_string(), self.safe_number_k(position.clone(), "liquidation_price", &[]));
m.insert("entryPrice".to_string(), self.safe_number2(position.clone(), Value::Str("avg_cost".into()), Value::Str("entry_price".into()), &[]));
m.insert("unrealizedPnl".to_string(), self.safe_number_k(position.clone(), "unrealized_pnl", &[]));
m.insert("contracts".to_string(), self.safe_number_k(position.clone(), "avail_position", &[]));
m.insert("contractSize".to_string(), self.safe_number_k(marketResolved, "contractSize", &[]));
m.insert("markPrice".to_string(), self.safe_number_k(position.clone(), "last", &[]));
m.insert("side".to_string(), side);
m.insert("hedged".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("maintenanceMargin".to_string(), self.safe_number_k(position.clone(), "margin", &[]));
m.insert("maintenanceMarginPercentage".to_string(), self.safe_number_k(position.clone(), "maint_margin_ratio", &[]));
m.insert("collateral".to_string(), Value::Null);
m.insert("initialMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("leverage".to_string(), self.safe_number2(position.clone(), Value::Str("leverage".into()), Value::Str("leverage_ratio".into()), &[]));
m.insert("marginRatio".to_string(), self.safe_number_k(position, "margin_ratio", &[]));
m.insert("percentage".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
/*
* @method
* @name digifinex#setLeverage
* @description set the level of leverage for a market
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#setleverage
* @param {float} leverage the rate of leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.marginMode] either 'cross' or 'isolated', default is cross
* @param {string} [params.side] either 'long' or 'short', required for isolated markets only
* @returns {object} response from the exchange
*/
pub async fn set_leverage(&mut self, mut leverage: 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(" setLeverage() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null).as_str() != Some("swap")) {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() supports swap contracts only".into()))));
}
if (leverage.as_f64().unwrap_or(f64::NAN) < ((1i64) as f64)) || (leverage.as_f64().unwrap_or(f64::NAN) > ((100i64) as f64)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" leverage should be between 1 and 100".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("leverage".to_string(), leverage);
m
});
let mut defaultMarginMode: Value = self.safe_string2(self.options.clone(), Value::Str("marginMode".into()), Value::Str("defaultMarginMode".into()), &[]);
let mut marginMode: Value = self.safe_string_lower2(params.clone(), Value::Str("marginMode".into()), Value::Str("defaultMarginMode".into()), &[defaultMarginMode]);
if (marginMode != Value::Null) {
marginMode = (if (marginMode.as_str() == Some("cross")) { Value::Str("crossed".into()) } else { Value::Str("isolated".into()) });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("margin_mode".into(), marginMode.clone()); }
}
let mut omitKeys: Value = Value::from(vec![]);
if (marginMode != Value::Null) {
append_to_array(&mut omitKeys, Value::Str("marginMode".into()));
append_to_array(&mut omitKeys, Value::Str("defaultMarginMode".into()));
}
let mut side: Value = self.safe_string_k(params.clone(), "side", &[]);
let mut isIsolated: bool = marginMode.as_str() == Some("isolated");
if isIsolated {
if (side != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("side".into(), side.clone()); }
} else {
self.check_required_argument(Value::Str("setLeverage".into()), side.clone(), Value::Str("side".into()), &[Value::from(vec![Value::Str("long".into()), Value::Str("short".into())])]);
}
}
if isIsolated && (side != Value::Null) {
append_to_array(&mut omitKeys, Value::Str("side".into()));
}
let mut paramsRequest: Value = self.omit(params, omitKeys, &[]);
let __ws_arg_45 = self.extend(request, &[paramsRequest]);
return self.private_swap_post_account_leverage(&[__ws_arg_45]).await;
Value::Null
}
/*
* @method
* @name digifinex#fetchTransfers
* @description fetch the transfer history, only transfers between spot and swap accounts are supported
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#transferrecord
* @param {string} code unified currency code of the currency transferred
* @param {int} [since] the earliest time in ms to fetch transfers for
* @param {int} [limit] the maximum number of transfers to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transfer structures]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn fetch_transfers(&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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (code != Value::Null) {
currency = self.currency(code);
if (currency == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchTransfers() could not resolve currency".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("currency".into(), self.safe_string_k(currency.clone(), "id", &[])); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_timestamp".into(), since.clone()); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 20 max 100
}
let __ws_arg_46 = self.extend(request, &[params]);
let mut response: Value = self.private_swap_get_account_transfer_record(&[__ws_arg_46]).await;
//
// {
// "code": 0,
// "data": [
// {
// "transfer_id": 130524,
// "type": 1,
// "currency": "USDT",
// "amount": "24",
// "timestamp": 1666505659000
// },
// ...
// ]
// }
//
let mut transfers: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_transfers(transfers, &[currency, since, limit]);
Value::Null
}
/*
* @method
* @name digifinex#fetchLeverageTiers
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#instruments
* @description retrieve information on the maximum leverage, for different trade sizes
* @param {string[]|undefined} symbols a list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [leverage tiers structures]{@link https://docs.ccxt.com/?id=leverage-tiers-structure}, indexed by market symbols
*/
pub async fn fetch_leverage_tiers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.public_swap_get_public_instruments(&[params]).await;
//
// {
// "code": 0,
// "data": [
// {
// "instrument_id": "BTCUSDTPERP",
// "type": "REAL",
// "contract_type": "PERPETUAL",
// "base_currency": "BTC",
// "quote_currency": "USDT",
// "clear_currency": "USDT",
// "contract_value": "0.001",
// "contract_value_currency": "BTC",
// "is_inverse": false,
// "is_trading": true,
// "status": "ONLINE",
// "price_precision": 1,
// "tick_size": "0.1",
// "min_order_amount": 1,
// "open_max_limits": [
// {
// "leverage": "50",
// "max_limit": "1000000"
// },
// ]
// },
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
return self.parse_leverage_tiers(data, &[symbolsNormalized, Value::Str("instrument_id".into())]);
Value::Null
}
/*
* @method
* @name digifinex#fetchMarketLeverageTiers
* @description retrieve information on the maximum leverage, for different trade sizes for a single market
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#instrument
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [leverage tiers structure]{@link https://docs.ccxt.com/?id=leverage-tiers-structure}
*/
pub async fn fetch_market_leverage_tiers(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchMarketLeverageTiers() supports swap markets only".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_47 = self.extend(request, &[params]);
let mut response: Value = self.public_swap_get_public_instrument(&[__ws_arg_47]).await;
//
// {
// "code": 0,
// "data": {
// "instrument_id": "BTCUSDTPERP",
// "type": "REAL",
// "contract_type": "PERPETUAL",
// "base_currency": "BTC",
// "quote_currency": "USDT",
// "clear_currency": "USDT",
// "contract_value": "0.001",
// "contract_value_currency": "BTC",
// "is_inverse": false,
// "is_trading": true,
// "status": "ONLINE",
// "price_precision": 1,
// "tick_size": "0.1",
// "min_order_amount": 1,
// "open_max_limits": [
// {
// "leverage": "50",
// "max_limit": "1000000"
// }
// ]
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_market_leverage_tiers(data, &[market]);
Value::Null
}
pub fn parse_market_leverage_tiers(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "instrument_id": "BTCUSDTPERP",
// "type": "REAL",
// "contract_type": "PERPETUAL",
// "base_currency": "BTC",
// "quote_currency": "USDT",
// "clear_currency": "USDT",
// "contract_value": "0.001",
// "contract_value_currency": "BTC",
// "is_inverse": false,
// "is_trading": true,
// "status": "ONLINE",
// "price_precision": 1,
// "tick_size": "0.1",
// "min_order_amount": 1,
// "open_max_limits": [
// {
// "leverage": "50",
// "max_limit": "1000000"
// }
// ]
// }
//
let mut tiers: Value = Value::from(vec![]);
let mut brackets: Value = self.safe_list_k(info.clone(), "open_max_limits", &[Value::from(vec![])]);
let mut marketId: Value = self.safe_string_k(info, "instrument_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.clone(), market]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_653: bool = true;
while { if !__for_first_653 { 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_653 = false; i.as_f64().unwrap_or(f64::NAN) < ((brackets.len() as i64) as f64) } {
let mut tier: Value = self.safe_dict(brackets.clone(), i.clone(), &[]);
append_to_array(&mut tiers, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tier".to_string(), self.sum(&[i.clone(), Value::Int(1)]));
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[marketResolved.clone(), Value::Null, Value::Str("swap".into())]));
m.insert("currency".to_string(), marketResolved.as_map().and_then(|__m| __m.get("settle")).cloned().unwrap_or(Value::Null));
m.insert("minNotional".to_string(), Value::Null);
m.insert("maxNotional".to_string(), self.safe_number_k(tier.clone(), "max_limit", &[]));
m.insert("maintenanceMarginRate".to_string(), Value::Null);
m.insert("maxLeverage".to_string(), self.safe_number_k(tier.clone(), "leverage", &[]));
m.insert("info".to_string(), tier);
m
}));
}
}
return tiers;
Value::Null
}
pub fn handle_margin_mode_and_params(&self, mut methodName: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut defaultValue = get_arg(optional_args, 1, Value::Null);
/*
* @ignore
* @method
* @description marginMode specified by params["marginMode"], this.options["marginMode"], this.options["defaultMarginMode"], params["margin"] = true or this.options["defaultType"] = 'margin'
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Array} the marginMode in lowercase
*/
let mut defaultType: Option<String> = self.safe_string_k(self.options.clone(), "defaultType", &[]).as_str().map(str::to_owned);
let mut isMargin: Value = self.safe_bool_k(params.clone(), "margin", &[Value::Bool(false)]);
let mut marginModeparamsMarginModeVariable = self.super_handle_margin_mode_and_params(methodName, params, defaultValue);
let mut marginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (marginMode != Value::Null) {
if (marginMode.as_str() != Some("cross")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" only cross margin is supported".into()))));
}
} else if (defaultType.as_deref() == Some("margin")) || (isMargin.as_bool() == Some(true)) {
return Value::from(vec![Value::Str("cross".into()), paramsMarginMode.clone()]);
}
return Value::from(vec![marginMode, paramsMarginMode]);
Value::Null
}
/*
* @method
* @name digifinex#fetchDepositWithdrawFees
* @description fetch deposit and withdraw fees
* @see https://docs.digifinex.com/en-ww/spot/v3/rest.html#get-currency-deposit-and-withdrawal-information
* @param {string[]|undefined} codes not used by fetchDepositWithdrawFees ()
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [fee structures]{@link https://docs.ccxt.com/?id=fee-structure}
*/
pub async fn fetch_deposit_withdraw_fees(&mut self, optional_args: &[Value]) -> Value {
let mut codes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.public_spot_get_currencies(&[params]).await;
//
// {
// "data": [
// {
// "deposit_status": 0,
// "min_withdraw_fee": 5,
// "withdraw_fee_currency": "USDT",
// "chain": "OMNI",
// "withdraw_fee_rate": 0,
// "min_withdraw_amount": 10,
// "currency": "USDT",
// "withdraw_status": 0,
// "min_deposit_amount": 10
// },
// {
// "deposit_status": 1,
// "min_withdraw_fee": 5,
// "withdraw_fee_currency": "USDT",
// "chain": "ERC20",
// "withdraw_fee_rate": 0,
// "min_withdraw_amount": 10,
// "currency": "USDT",
// "withdraw_status": 1,
// "min_deposit_amount": 10
// },
// ],
// "code": 200,
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[]);
return self.parse_deposit_withdraw_fees(data, &[codes]);
Value::Null
}
pub fn parse_deposit_withdraw_fees(&self, mut response: Value, optional_args: &[Value]) -> Value {
let mut codes = get_arg(optional_args, 0, Value::Null);
let mut currencyIdKey = get_arg(optional_args, 1, Value::Null);
//
// [
// {
// "deposit_status": 0,
// "min_withdraw_fee": 5,
// "withdraw_fee_currency": "USDT",
// "chain": "OMNI",
// "withdraw_fee_rate": 0,
// "min_withdraw_amount": 10,
// "currency": "USDT",
// "withdraw_status": 0,
// "min_deposit_amount": 10
// },
// {
// "deposit_status": 1,
// "min_withdraw_fee": 5,
// "withdraw_fee_currency": "USDT",
// "chain": "ERC20",
// "withdraw_fee_rate": 0,
// "min_withdraw_amount": 10,
// "currency": "USDT",
// "withdraw_status": 1,
// "min_deposit_amount": 10
// },
// ]
//
let mut depositWithdrawFees: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut codesValue: Value = self.market_codes(&[codes]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_654: bool = true;
while { if !__for_first_654 { 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_654 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&response).as_f64().unwrap_or(f64::NAN) } {
let mut entry: Value = self.safe_dict(response.clone(), i.clone(), &[]);
let mut currencyId: Value = self.safe_string_k(entry.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
if (code != Value::Null) && ((codesValue == Value::Null) || self.in_array(code.clone(), codesValue.clone()).as_bool() == Some(true)) {
let mut depositWithdrawFee: Value = self.safe_dict(depositWithdrawFees.clone(), code.clone(), &[]);
if (depositWithdrawFee == Value::Null) {
if let Value::Dict(__d) = &mut depositWithdrawFees { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), self.deposit_withdraw_fee(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}))); }
add_element_to_object(get_value_mut(&mut depositWithdrawFees, &code), &Value::Str("info".into()), Value::from(vec![]));
}
let mut depositWithdrawInfo: Value = crate::value::get_value_k(&depositWithdrawFees.as_map().and_then(|__m| code.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null), "info");
append_to_array(&mut depositWithdrawInfo, entry.clone());
let mut networkId: Value = self.safe_string_k(entry.clone(), "chain", &[]);
let mut withdrawFee: Value = self.safe_value_k(entry, "min_withdraw_fee", &[]);
let mut withdrawResult: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fee".to_string(), withdrawFee.clone());
m.insert("percentage".to_string(), (if (withdrawFee != Value::Null) { Value::Bool(false) } else { Value::Null }));
m
});
let mut depositResult: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fee".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m
});
if (networkId != Value::Null) {
let mut networkCode: Value = self.network_id_to_code(&[networkId, code.clone()]);
if (networkCode != Value::Null) {
add_element_to_object(get_value_mut(get_value_mut(&mut depositWithdrawFees, &code), &Value::Str("networks".into())), &networkCode, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("withdraw".to_string(), withdrawResult.clone());
m.insert("deposit".to_string(), depositResult.clone());
m
}));
}
} else {
add_element_to_object(get_value_mut(&mut depositWithdrawFees, &code), &Value::Str("withdraw".into()), withdrawResult);
add_element_to_object(get_value_mut(&mut depositWithdrawFees, &code), &Value::Str("deposit".into()), depositResult);
}
}
}
}
let mut depositWithdrawCodes: Value = object_keys(&depositWithdrawFees);
{
let mut i: Value = Value::Int(0);
let mut __for_first_655: bool = true;
while { if !__for_first_655 { 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_655 = false; i.as_f64().unwrap_or(f64::NAN) < ((depositWithdrawCodes.len() as i64) as f64) } {
let mut code: Value = depositWithdrawCodes.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 currency: Value = self.currency(code.clone());
{ let __be_tmp = self.assign_default_deposit_withdraw_fees(get_value(&depositWithdrawFees, &code), &[currency]); if let Value::Dict(__d) = &mut depositWithdrawFees { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), __be_tmp); } }
}
}
return depositWithdrawFees;
Value::Null
}
/*
* @method
* @name digifinex#addMargin
* @description add margin to a position
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#positionmargin
* @param {string} symbol unified market symbol
* @param {float} amount amount of margin to add
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} params.side the position side: 'long' or 'short'
* @returns {object} a [margin structure]{@link https://docs.ccxt.com/?id=margin-structure}
*/
pub async fn add_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut side: Value = self.safe_string_k(params.clone(), "side", &[]);
self.check_required_argument(Value::Str("addMargin".into()), side, Value::Str("side".into()), &[Value::from(vec![Value::Str("long".into()), Value::Str("short".into())])]);
return self.modify_margin_helper(symbol, amount, Value::Int(1), &[params]).await;
Value::Null
}
/*
* @method
* @name digifinex#reduceMargin
* @description remove margin from a position
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#positionmargin
* @param {string} symbol unified market symbol
* @param {float} amount the amount of margin to remove
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} params.side the position side: 'long' or 'short'
* @returns {object} a [margin structure]{@link https://docs.ccxt.com/?id=margin-structure}
*/
pub async fn reduce_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut side: Value = self.safe_string_k(params.clone(), "side", &[]);
self.check_required_argument(Value::Str("reduceMargin".into()), side, Value::Str("side".into()), &[Value::from(vec![Value::Str("long".into()), Value::Str("short".into())])]);
return self.modify_margin_helper(symbol, amount, Value::Int(2), &[params]).await;
Value::Null
}
pub async fn modify_margin_helper(&mut self, mut symbol: Value, mut amount: Value, mut type_var: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut side: Value = self.safe_string_k(params.clone(), "side", &[]);
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("amount".to_string(), self.number_to_string(amount));
m.insert("type".to_string(), type_var);
m.insert("side".to_string(), side);
m
});
let __ws_arg_48 = self.extend(request, &[params]);
let mut response: Value = self.private_swap_post_account_position_margin(&[__ws_arg_48]).await;
//
// {
// "code": 0,
// "data": {
// "instrument_id": "BTCUSDTPERP",
// "side": "long",
// "type": 1,
// "amount": "3.6834"
// }
// }
//
let mut code: Option<i64> = self.safe_integer_k(response.clone(), "code", &[]).as_i64();
let mut status: Value = Value::Str("failed".into());
if (code == Some(0)) {
status = Value::Str("ok".into());
}
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let __ws_arg_49 = self.parse_margin_modification(data, &[market]);
return self.extend(__ws_arg_49, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), status);
m
})]);
Value::Null
}
pub fn parse_margin_modification(&self, mut data: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "instrument_id": "BTCUSDTPERP",
// "side": "long",
// "type": 1,
// "amount": "3.6834"
// }
//
let mut marketId: Value = self.safe_string_k(data.clone(), "instrument_id", &[]);
let mut rawType: Option<i64> = self.safe_integer_k(data.clone(), "type", &[]).as_i64();
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market.clone(), Value::Null, Value::Str("swap".into())]));
m.insert("type".to_string(), (if (rawType == Some(1)) { Value::Str("add".into()) } else { Value::Str("reduce".into()) }));
m.insert("marginMode".to_string(), Value::Str("isolated".into()));
m.insert("amount".to_string(), self.safe_number_k(data, "amount", &[]));
m.insert("total".to_string(), Value::Null);
m.insert("code".to_string(), self.safe_string_k(market, "settle", &[]));
m.insert("status".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name digifinex#fetchFundingHistory
* @description fetch the history of funding payments paid and received on this account
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#funding-fee
* @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 {int} [params.until] timestamp in ms of the latest funding payment
* @returns {object} a [funding history structure]{@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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("end_timestamp".into()), request, params, &[]);
let mut requestUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
add_element_to_object(&mut requestUntil, &Value::Str("instrument_id".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
}
if (limit != Value::Null) {
add_element_to_object(&mut requestUntil, &Value::Str("limit".into()), limit.clone());
}
if (since != Value::Null) {
add_element_to_object(&mut requestUntil, &Value::Str("start_timestamp".into()), since.clone());
}
let __ws_arg_50 = self.extend(requestUntil, &[paramsUntil]);
let mut response: Value = self.private_swap_get_account_funding_fee(&[__ws_arg_50]).await;
//
// {
// "code": 0,
// "data": [
// {
// "instrument_id": "BTCUSDTPERP",
// "currency": "USDT",
// "amount": "-0.000342814",
// "timestamp": 1698768009440
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_incomes(data, &[market, since, limit]);
Value::Null
}
pub fn parse_income(&self, mut income: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "instrument_id": "BTCUSDTPERP",
// "currency": "USDT",
// "amount": "-0.000342814",
// "timestamp": 1698768009440
// }
//
let mut marketId: Value = self.safe_string_k(income.clone(), "instrument_id", &[]);
let mut currencyId: Value = self.safe_string_k(income.clone(), "currency", &[]);
let mut timestamp: Value = self.safe_integer_k(income.clone(), "timestamp", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), income.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market, Value::Null, Value::Str("swap".into())]));
m.insert("code".to_string(), self.safe_currency_code(currencyId, &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("id".to_string(), Value::Null);
m.insert("amount".to_string(), self.safe_number_k(income, "amount", &[]));
m
});
Value::Null
}
/*
* @method
* @name digifinex#setMarginMode
* @description set margin mode to 'cross' or 'isolated'
* @see https://docs.digifinex.com/en-ww/swap/v2/rest.html#positionmode
* @param {string} marginMode 'cross' or 'isolated'
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} response from the exchange
*/
pub async fn set_margin_mode(&mut self, mut marginMode: 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(" setMarginMode() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut marginModeLower: Value = to_lower(&marginMode);
let mut marginModeResolved: Value = (if (marginModeLower.as_str() == Some("cross")) { Value::Str("crossed".into()) } else { marginModeLower });
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("margin_mode".to_string(), marginModeResolved);
m
});
let __ws_arg_51 = self.extend(request, &[params]);
return self.private_swap_post_account_position_mode(&[__ws_arg_51]).await;
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 signed: bool = self.safe_string(api.clone(), Value::Int(0), &[]).as_str() == Some("private");
let mut endpoint: Option<String> = self.safe_string(api, Value::Int(1), &[]).as_str().map(str::to_owned);
let mut pathPart: Value = Value::Str("/swap/v2".into());
if (endpoint.as_deref() == Some("spot")) {
pathPart = Value::Str("/v3".into());
}
let mut request: Value = Value::Str(format!("{}{}", Value::Str("/".into()), self.implode_params(path.clone(), params.clone())).into());
let mut payload: Value = Value::Str(format!("{}{}", pathPart, request).into());
let mut apiUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), Value::Str("rest".into()), &[]);
if (apiUrl == 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 = Value::Str(format!("{}{}", apiUrl, payload).into());
let mut query: Value = self.omit(params.clone(), self.extract_params(path), &[]);
let mut urlencoded: Value = Value::Null;
if signed && (pathPart.as_str() == Some("/swap/v2")) && (method.as_str() == Some("POST")) {
urlencoded = json_stringify(¶ms);
} else {
urlencoded = self.urlencode(self.keysort(query, &[]), &[]);
}
if signed {
let mut auth: Value = Value::Null;
let mut nonce: Value = Value::Null;
if (pathPart.as_str() == Some("/swap/v2")) {
nonce = to_string_val(&self.milliseconds());
auth = Value::Str(format!("{}{}", Value::Str(format!("{}{}", nonce, method).into()), payload).into());
if (method.as_str() == Some("GET")) {
if (urlencoded != Value::Null) && (urlencoded.as_str() != Some("")) {
auth = Value::Str(format!("{}{}", auth, Value::Str(format!("{}{}", Value::Str("?".into()), urlencoded).into())).into());
}
} else if (method.as_str() == Some("POST")) {
auth = Value::Str(format!("{}{}", auth, urlencoded).into());
}
} else {
nonce = to_string_val(&self.nonce());
auth = urlencoded.clone();
}
let mut signature: Value = self.hmac(self.encode(auth), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[]);
if (method.as_str() == Some("GET")) {
if (urlencoded != Value::Null) && (urlencoded.as_str() != Some("")) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), urlencoded).into())).into());
}
}
let mut hasPostBody: bool = (method.as_str() == Some("POST")) && (urlencoded != Value::Null) && (urlencoded.as_str() != Some(""));
let mut requestBody: Value = body.clone();
if hasPostBody {
requestBody = urlencoded.clone();
}
let mut privateHeaders: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ACCESS-KEY".to_string(), self.apiKey.clone());
m.insert("ACCESS-SIGN".to_string(), signature);
m.insert("ACCESS-TIMESTAMP".to_string(), nonce);
m
});
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), requestBody);
m.insert("headers".to_string(), privateHeaders);
m
});
} else {
if (urlencoded != Value::Null) && (urlencoded.as_str() != Some("")) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), urlencoded).into())).into());
}
}
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(), body);
m.insert("headers".to_string(), headers);
m
});
Value::Null
}
pub fn handle_errors(&self, mut statusCode: Value, mut statusText: Value, mut url: Value, mut method: Value, mut responseHeaders: Value, mut responseBody: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) {
return Value::Null;
}
let mut code: Value = self.safe_string_k(response, "code", &[]);
if (code.as_str() == Some("0")) || (code.as_str() == Some("200")) {
return Value::Null;
}
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), responseBody).into());
if (code == Value::Null) {
panic!("{}", crate::exchange_errors::bad_response(feedback));
}
let mut unknownError: Value = Value::from(vec![Value::Str("ExchangeError".into()), feedback]);
let mut ExceptionClassmessageVariable = self.safe_value(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), code, &[unknownError]);
let mut ExceptionClass: Value = get_value(&ExceptionClassmessageVariable, &Value::Int(0));
let mut message: Value = get_value(&ExceptionClassmessageVariable, &Value::Int(1));
panic!("{}", crate::exchange_errors::create_error(&crate::runtime::stringify_param(&(ExceptionClass)), &crate::runtime::stringify_param(&(message))));
Value::Null
}
}