// 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 DeltaCore {
pub exchange: crate::exchange::Exchange,
}
impl DeltaCore {
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 = DeltaCore::describe(self);
self.initialize_properties(described);
// compatibility for sandbox/testnet options in userConfig
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
/// 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 DeltaCore {
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_order(self, order, &[market])
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::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 DeltaCore.
DeltaCore::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 DeltaCore.
DeltaCore::parse_ledger_entry(self, entry, &[currency])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_currency(self, currency)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_open_interest(self, interest, &[market])
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_margin_modification(self, data, &[market])
}
fn parse_adl_rank(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_adl_rank(self, info, &[market])
}
fn parse_greeks(&self, greeks: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_greeks(self, greeks, &[market])
}
fn parse_margin_mode(&self, margin_mode: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_margin_mode(self, margin_mode, &[market])
}
fn parse_leverage(&self, leverage: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::parse_leverage(self, leverage, &[market])
}
fn create_expired_option_market(&self, symbol: crate::Value) -> crate::Value {
// Forward to the inherent method on DeltaCore.
DeltaCore::create_expired_option_market(self, symbol)
}
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 DeltaCore.
DeltaCore::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 DeltaCore.
DeltaCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for DeltaCore {
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_all_orders" => self.cancel_all_orders(&args[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"close_all_positions" => self.close_all_positions(&args[..]).await,
"create_expired_option_market" => self.create_expired_option_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&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_funding_rate" => self.fetch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_funding_rates" => self.fetch_funding_rates(&args[..]).await,
"fetch_greeks" => self.fetch_greeks(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_ledger" => self.fetch_ledger(&args[..]).await,
"fetch_leverage" => self.fetch_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_margin_mode" => self.fetch_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_option" => self.fetch_option(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_with_method" => self.fetch_orders_with_method(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_positions_adl_rank" => self.fetch_positions_adl_rank(&args[..]).await,
"fetch_settlement_history" => self.fetch_settlement_history(&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,
"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)),
"index_by_stringified_numeric_id" => self.index_by_stringified_numeric_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"load_markets" => self.load_markets(&args[..]).await,
"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_adl_rank" => self.parse_adl_rank(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_currency" => self.parse_currency(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_deposit_address" => self.parse_deposit_address(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_greeks" => self.parse_greeks(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_leverage" => self.parse_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_margin_mode" => self.parse_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_margin_modification" => self.parse_margin_modification(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_open_interest" => self.parse_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_option" => self.parse_option(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_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_settlement" => self.parse_settlement(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_settlements" => self.parse_settlements(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"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())..]),
"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,
"safe_market" => self.safe_market(&args[..]),
"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())..]),
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for DeltaCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for DeltaCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl DeltaCore {
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("delta".into()));
m.insert("name".to_string(), Value::Str("Delta Exchange".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("VC".into())]));
m.insert("rateLimit".to_string(), Value::Int(300));
m.insert("version".to_string(), Value::Str("v2".into()));
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(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(true));
m.insert("addMargin".to_string(), Value::Bool(true));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("closeAllPositions".to_string(), Value::Bool(true));
m.insert("closePosition".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDeposit".to_string(), Value::Null);
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::Null);
m.insert("fetchFundingHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingRates".to_string(), Value::Bool(true));
m.insert("fetchGreeks".to_string(), Value::Bool(true));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(true));
m.insert("fetchLedger".to_string(), Value::Bool(true));
m.insert("fetchLeverage".to_string(), Value::Bool(true));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchMarginMode".to_string(), Value::Bool(true));
m.insert("fetchMarginModes".to_string(), Value::Bool(false));
m.insert("fetchMarketLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(true));
m.insert("fetchMySettlementHistory".to_string(), Value::Bool(false));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOption".to_string(), Value::Bool(true));
m.insert("fetchOptionChain".to_string(), Value::Bool(false));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchPosition".to_string(), Value::Bool(true));
m.insert("fetchPositionADLRank".to_string(), Value::Bool(true));
m.insert("fetchPositionMode".to_string(), Value::Bool(false));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsADLRank".to_string(), Value::Bool(true));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchSettlementHistory".to_string(), Value::Bool(true));
m.insert("fetchStatus".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTime".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTransfer".to_string(), Value::Null);
m.insert("fetchTransfers".to_string(), Value::Null);
m.insert("fetchUnderlyingAssets".to_string(), Value::Bool(false));
m.insert("fetchVolatilityHistory".to_string(), Value::Bool(false));
m.insert("fetchWithdrawal".to_string(), Value::Null);
m.insert("fetchWithdrawals".to_string(), Value::Null);
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(false));
m.insert("withdraw".to_string(), Value::Bool(false));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".into()));
m.insert("3m".to_string(), Value::Str("3m".into()));
m.insert("5m".to_string(), Value::Str("5m".into()));
m.insert("15m".to_string(), Value::Str("15m".into()));
m.insert("30m".to_string(), Value::Str("30m".into()));
m.insert("1h".to_string(), Value::Str("1h".into()));
m.insert("2h".to_string(), Value::Str("2h".into()));
m.insert("4h".to_string(), Value::Str("4h".into()));
m.insert("6h".to_string(), Value::Str("6h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m.insert("7d".to_string(), Value::Str("7d".into()));
m.insert("1w".to_string(), Value::Str("1w".into()));
m.insert("2w".to_string(), Value::Str("2w".into()));
m.insert("1M".to_string(), Value::Str("30d".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/1294454/99450025-3be60a00-2931-11eb-9302-f4fd8d8589aa.jpg".into()));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://testnet-api.delta.exchange".into()));
m.insert("private".to_string(), Value::Str("https://testnet-api.delta.exchange".into()));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://api.delta.exchange".into()));
m.insert("private".to_string(), Value::Str("https://api.delta.exchange".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://www.delta.exchange".into()));
m.insert("doc".to_string(), Value::from(vec![Value::Str("https://docs.delta.exchange".into())]));
m.insert("fees".to_string(), Value::Str("https://www.delta.exchange/fees".into()));
m.insert("referral".to_string(), Value::Str("https://www.delta.exchange/app/signup/?code=IULYNB".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("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("indices".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("products".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("products/{symbol}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tickers/{symbol}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("l2orderbook/{symbol}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trades/{symbol}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("stats".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("history/candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("history/sparklines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("settings".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/client_order_id/{client_oid}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("products/{product_id}/orders/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/margined".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("fills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("fills/history/download/csv".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wallet/balances".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wallet/transactions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wallet/transactions/download".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wallets/sub_accounts_transfer_history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("users/trading_preferences".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sub_accounts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("profile".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rate_limits/quota".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("heartbeat".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("deposits/address".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("orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/bracket".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/batch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("products/{product_id}/orders/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/change_margin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/close_all".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wallets/sub_account_balance_transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("heartbeat/create".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("heartbeat".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/cancel_after".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("put".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/bracket".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/batch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/auto_topup".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("users/update_mmp".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("users/reset_mmp".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("users/margin_mode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("users/trading_preferences".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/all".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/batch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
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("taker".to_string(), self.parse_number(Value::Str("0.0015".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.0010".into()), &[]));
m.insert("tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.0015".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100".into()), &[]), self.parse_number(Value::Str("0.0013".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("250".into()), &[]), self.parse_number(Value::Str("0.0013".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000".into()), &[]), self.parse_number(Value::Str("0.001".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("5000".into()), &[]), self.parse_number(Value::Str("0.0009".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000".into()), &[]), self.parse_number(Value::Str("0.00075".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("20000".into()), &[]), self.parse_number(Value::Str("0.00065".into()), &[])])]));
m.insert("maker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.001".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100".into()), &[]), self.parse_number(Value::Str("0.001".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("250".into()), &[]), self.parse_number(Value::Str("0.0009".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000".into()), &[]), self.parse_number(Value::Str("0.00075".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("5000".into()), &[]), self.parse_number(Value::Str("0.0006".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000".into()), &[]), self.parse_number(Value::Str("0.0005".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("20000".into()), &[]), self.parse_number(Value::Str("0.0005".into()), &[])])]));
m
}));
m
}));
m
}));
m.insert("userAgent".to_string(), self.userAgents.as_map().and_then(|__m| __m.get("chrome39")).cloned().unwrap_or(Value::Null));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("TRC20".to_string(), Value::Str("TRC20(TRON)".into()));
m.insert("BEP20".to_string(), Value::Str("BEP20(BSC)".into()));
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(true));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("triggerPrice".to_string(), Value::Bool(true));
m.insert("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("last".to_string(), Value::Bool(true));
m.insert("mark".to_string(), Value::Bool(true));
m.insert("index".to_string(), Value::Bool(true));
m
}));
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::Map({
let mut m = indexmap::IndexMap::new();
m.insert("triggerPriceType".to_string(), Value::Null);
m.insert("price".to_string(), Value::Bool(true));
m
}));
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("IOC".to_string(), Value::Bool(true));
m.insert("FOK".to_string(), Value::Bool(true));
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("iceberg".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
}));
m.insert("createOrders".to_string(), Value::Null);
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.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Null);
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.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::Null);
m.insert("fetchClosedOrders".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(500));
m.insert("daysBack".to_string(), Value::Int(100000));
m.insert("daysBackCanceled".to_string(), Value::Int(1));
m.insert("untilDays".to_string(), Value::Int(100000));
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("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(2000));
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("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("default".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m
}));
m.insert("future".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("default".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m
}));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(true));
m.insert("secret".to_string(), Value::Bool(true));
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("insufficient_margin".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("order_size_exceed_available".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("risk_limits_breached".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("invalid_contract".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("immediate_liquidation".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("out_of_bankruptcy".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("self_matching_disrupted_post_only".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("immediate_execution_post_only".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("bad_schema".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("invalid_api_key".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("invalid_signature".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("open_order_not_found".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("unavailable".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
m
})]);
Value::Null
}
pub fn create_expired_option_market(&self, mut symbol: Value) -> Value {
// support expired option contracts
let mut quote: Value = Value::Str("USDT".into());
let mut optionParts: Value = Value::Array(symbol.as_str().map(|__s| __s.split("-").map(|__p| Value::Str(__p.to_string().into())).collect()).unwrap_or_default());
let mut symbolBase: Value = Value::Array(symbol.as_str().map(|__s| __s.split("/").map(|__p| Value::Str(__p.to_string().into())).collect()).unwrap_or_default());
let mut hasSlash: bool = Value::Int(symbol.as_str().and_then(|__s| __s.find("/")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64);
let mut base: Value = Value::Null;
let mut optionType: Value = Value::Null;
if hasSlash {
base = self.safe_string(symbolBase, Value::Int(0), &[]);
optionType = self.safe_string(optionParts.clone(), Value::Int(3), &[]);
} else {
base = self.safe_string(optionParts.clone(), Value::Int(1), &[]);
optionType = self.safe_string(optionParts.clone(), Value::Int(0), &[]);
}
let mut rawExpiry: Value = self.safe_string(optionParts.clone(), (if hasSlash { Value::Int(1) } else { Value::Int(3) }), &[]);
let mut expiry: Value = Value::Null;
if (rawExpiry != Value::Null) {
expiry = Value::Str(format!("{}{}", Value::Str(format!("{}{}", rawExpiry.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(4); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null), rawExpiry.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(2); let __j = __l.min(4); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)).into()), rawExpiry.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(0); let __j = __l.min(2); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)).into());
}
let mut settle: Value = quote.clone();
let mut strike: Value = self.safe_string(optionParts, Value::Int(2), &[]);
let mut datetime: Value = self.convert_expire_date(expiry.clone());
let mut timestamp: Value = self.parse8601(datetime.clone());
let mut optionTypeUnified: Value = Value::Str("put".into());
if (optionType.as_str() == Some("C")) {
optionTypeUnified = Value::Str("call".into());
}
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", optionType, Value::Str("-".into())).into()), base).into()), Value::Str("-".into())).into()), strike).into()), Value::Str("-".into())).into()), expiry).into()));
m.insert("symbol".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", 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()), Value::Str("-".into())).into()), expiry).into()), Value::Str("-".into())).into()), strike).into()), Value::Str("-".into())).into()), optionType).into()));
m.insert("base".to_string(), base.clone());
m.insert("quote".to_string(), quote.clone());
m.insert("settle".to_string(), settle.clone());
m.insert("baseId".to_string(), base);
m.insert("quoteId".to_string(), quote);
m.insert("settleId".to_string(), settle);
m.insert("active".to_string(), Value::Bool(false));
m.insert("type".to_string(), Value::Str("option".into()));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("contract".to_string(), Value::Bool(true));
m.insert("contractSize".to_string(), self.parse_number(Value::Str("1".into()), &[]));
m.insert("expiry".to_string(), timestamp);
m.insert("expiryDatetime".to_string(), datetime);
m.insert("optionType".to_string(), optionTypeUnified);
m.insert("strike".to_string(), self.parse_number(strike, &[]));
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Null);
m.insert("price".to_string(), Value::Null);
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("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(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("info".to_string(), Value::Null);
m
})]);
Value::Null
}
pub fn safe_market(&self, optional_args: &[Value]) -> Value {
let mut marketId = get_arg(optional_args, 0, Value::Null);
let mut market = get_arg(optional_args, 1, Value::Null);
let mut delimiter = get_arg(optional_args, 2, Value::Null);
let mut marketType = get_arg(optional_args, 3, Value::Null);
let mut isOption: bool = (marketId != Value::Null) && ((marketId.as_str().is_some_and(|__s| __s.ends_with("-C"))) || (marketId.as_str().is_some_and(|__s| __s.ends_with("-P"))) || (marketId.as_str().is_some_and(|__s| __s.starts_with("C-"))) || (marketId.as_str().is_some_and(|__s| __s.starts_with("P-"))));
if isOption && ((self.markets_by_id.clone() == Value::Null) || !(matches!((&self.markets_by_id, &marketId), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref())))) {
return self.create_expired_option_market(marketId.clone());
}
return self.super_safe_market(marketId, market, delimiter, marketType);
Value::Null
}
/*
* @method
* @name delta#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @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_get_settings(&[params]).await;
// full response sample under `fetchStatus`
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_integer_product_k(result, "server_time", Value::Float(0.001), &[]);
Value::Null
}
/*
* @method
* @name delta#fetchStatus
* @description the latest known information on the availability of the exchange API
* @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_get_settings(&[params]).await;
//
// {
// "result": {
// "deto_liquidity_mining_daily_reward": "40775",
// "deto_msp": "1.0",
// "deto_staking_daily_reward": "23764.08",
// "enabled_wallets": [
// "BTC",
// ...
// ],
// "portfolio_margin_params": {
// "enabled_portfolios": {
// ".DEAVAXUSDT": {
// "asset_id": 5,
// "futures_contingency_margin_percent": "1",
// "interest_rate": "0",
// "maintenance_margin_multiplier": "0.8",
// "max_price_shock": "20",
// "max_short_notional_limit": "2000",
// "options_contingency_margin_percent": "1",
// "options_discount_range": "10",
// "options_liq_band_range_percentage": "25",
// "settling_asset": "USDT",
// "sort_priority": 5,
// "underlying_asset": "AVAX",
// "volatility_down_shock": "30",
// "volatility_up_shock": "45"
// },
// ...
// },
// "portfolio_enabled_contracts": [
// "futures",
// "perpetual_futures",
// "call_options",
// "put_options"
// ]
// },
// "server_time": 1650640673500273,
// "trade_farming_daily_reward": "100000",
// "circulating_supply": "140000000",
// "circulating_supply_update_time": "1636752800",
// "deto_referral_mining_daily_reward": "0",
// "deto_total_reward_pool": "100000000",
// "deto_trade_mining_daily_reward": "0",
// "kyc_deposit_limit": "20",
// "kyc_withdrawal_limit": "10000",
// "maintenance_start_time": "1650387600000000",
// "msp_deto_commission_percent": "25",
// "under_maintenance": "false"
// },
// "success": true
// }
//
let mut result: Value = self.safe_dict_k(response.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut underMaintenance: Option<String> = self.safe_string_k(result.clone(), "under_maintenance", &[]).as_str().map(str::to_owned);
let mut status: Value = Value::Str("ok".into());
if (underMaintenance.as_deref() == Some("true")) {
status = Value::Str("maintenance".into());
}
let mut updated: Value = self.safe_integer_product_k(result, "server_time", Value::Float(0.001), &[self.milliseconds()]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), status);
m.insert("updated".to_string(), updated);
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 delta#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://docs.delta.exchange/#get-list-of-all-assets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
pub async fn fetch_currencies(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_assets(&[params]).await;
//
// {
// "result": [
// {
// "base_withdrawal_fee": "0.005000000000000000",
// "id": "1",
// "interest_credit": false,
// "interest_slabs": null,
// "kyc_deposit_limit": "0.000000000000000000",
// "kyc_withdrawal_limit": "0.000000000000000000",
// "min_withdrawal_amount": "0.010000000000000000",
// "minimum_precision": "4",
// "name": "Ethereum",
// "networks": [
// {
// "allowed_deposit_groups": null,
// "base_withdrawal_fee": "0.0025",
// "deposit_status": "enabled",
// "memo_required": false,
// "min_deposit_amount": "0.000050000000000000",
// "min_withdrawal_amount": "0.010000000000000000",
// "minimum_deposit_confirmations": "12",
// "network": "ERC20",
// "variable_withdrawal_fee": "0",
// "withdrawal_status": "enabled"
// },
// {
// "allowed_deposit_groups": null,
// "base_withdrawal_fee": "0.0001",
// "deposit_status": "enabled",
// "memo_required": false,
// "min_deposit_amount": "0.000050000000000000",
// "min_withdrawal_amount": "0.000300000000000000",
// "minimum_deposit_confirmations": "15",
// "network": "BEP20(BSC)",
// "variable_withdrawal_fee": "0",
// "withdrawal_status": "enabled"
// }
// ],
// "precision": "18",
// "sort_priority": "3",
// "symbol": "ETH",
// "variable_withdrawal_fee": "0.000000000000000000"
// },
// ],
// "success":true
// }
//
let mut currencies: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
return self.parse_currencies(currencies);
Value::Null
}
pub fn parse_currency(&self, mut rawCurrency: Value) -> Value {
let mut id: Value = self.safe_string_k(rawCurrency.clone(), "symbol", &[]);
let mut numericId: Value = self.safe_integer_k(rawCurrency.clone(), "id", &[]);
let mut code: Value = self.safe_currency_code(id.clone(), &[]);
let mut chains: Value = self.safe_list_k(rawCurrency.clone(), "networks", &[Value::from(vec![])]);
let mut networks: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut j: Value = Value::Int(0);
let mut __for_first_610: bool = true;
while { if !__for_first_610 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_610 = false; j.as_f64().unwrap_or(f64::NAN) < ((chains.len() as i64) as f64) } {
let mut chain: Value = chains.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_string_k(chain.clone(), "network", &[]);
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("name".to_string(), self.safe_string_k(chain.clone(), "name", &[]));
m.insert("info".to_string(), chain.clone());
m.insert("active".to_string(), Value::Bool(self.safe_string_k(chain.clone(), "status", &[]).as_str() == Some("enabled")));
m.insert("deposit".to_string(), Value::Bool(self.safe_string_k(chain.clone(), "deposit_status", &[]).as_str() == Some("enabled")));
m.insert("withdraw".to_string(), Value::Bool(self.safe_string_k(chain.clone(), "withdrawal_status", &[]).as_str() == Some("enabled")));
m.insert("fee".to_string(), self.safe_number_k(chain.clone(), "base_withdrawal_fee", &[]));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(chain.clone(), "min_deposit_amount", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(chain, "min_withdrawal_amount", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m
})); }
}
}
}
return self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("numericId".to_string(), numericId);
m.insert("code".to_string(), code);
m.insert("name".to_string(), self.safe_string_k(rawCurrency.clone(), "name", &[]));
m.insert("info".to_string(), rawCurrency.clone());
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), Value::Bool(self.safe_string_k(rawCurrency.clone(), "deposit_status", &[]).as_str() == Some("enabled")));
m.insert("withdraw".to_string(), Value::Bool(self.safe_string_k(rawCurrency.clone(), "withdrawal_status", &[]).as_str() == Some("enabled")));
m.insert("fee".to_string(), self.safe_number_k(rawCurrency.clone(), "base_withdrawal_fee", &[]));
m.insert("precision".to_string(), self.parse_number(self.parse_precision(&[self.safe_string_k(rawCurrency.clone(), "precision", &[])]), &[]));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(rawCurrency, "min_withdrawal_amount", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("networks".to_string(), networks);
m.insert("type".to_string(), Value::Str("crypto".into()));
m
}));
Value::Null
}
pub async fn load_markets(&mut self, optional_args: &[Value]) -> Value {
let mut reload = get_arg(optional_args, 0, Value::Bool(false));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut markets: Value = self.super_load_markets(reload.clone(), params).await;
let mut currenciesByNumericId: Value = self.safe_dict_k(self.options.clone(), "currenciesByNumericId", &[]);
if (currenciesByNumericId == Value::Null) || is_true(&reload) {
{ let __be_tmp = self.index_by_stringified_numeric_id(self.currencies.clone()); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("currenciesByNumericId".into(), __be_tmp); } }
}
let mut marketsByNumericId: Value = self.safe_dict_k(self.options.clone(), "marketsByNumericId", &[]);
if (marketsByNumericId == Value::Null) || is_true(&reload) {
{ let __be_tmp = self.index_by_stringified_numeric_id(self.markets.clone()); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("marketsByNumericId".into(), __be_tmp); } }
}
return markets;
Value::Null
}
pub fn index_by_stringified_numeric_id(&self, mut input: Value) -> Value {
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (input == Value::Null) {
return Value::Null;
}
let mut keys: Value = Value::Array(input.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default());
{
let mut i: Value = Value::Int(0);
let mut __for_first_611: bool = true;
while { if !__for_first_611 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_611 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut key: Value = keys.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut item: Value = input.as_map().and_then(|__m| key.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
let mut numericIdString: Value = self.safe_string_k(item.clone(), "numericId", &[]);
if (numericIdString == Value::Null) {
continue;
}
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&numericIdString), item); }
}
}
return result;
Value::Null
}
/*
* @method
* @name delta#fetchMarkets
* @description retrieves data on all markets for delta
* @see https://docs.delta.exchange/#get-list-of-products
* @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 response: Value = self.public_get_products(&[params]).await;
//
// {
// "meta":{ "after":null, "before":null, "limit":100, "total_count":81 },
// "result":[
// // the below response represents item from perpetual market
// {
// "annualized_funding":"5.475000000000000000",
// "is_quanto":false,
// "ui_config":{
// "default_trading_view_candle":"15",
// "leverage_slider_values":[1,3,5,10,25,50],
// "price_clubbing_values":[0.001,0.005,0.05,0.1,0.5,1,5],
// "show_bracket_orders":false,
// "sort_priority":29,
// "tags":[]
// },
// "basis_factor_max_limit":"0.15",
// "symbol":"P-LINK-D-151120",
// "id":1584,
// "default_leverage":"5.000000000000000000",
// "maker_commission_rate":"0.0005",
// "contract_unit_currency":"LINK",
// "strike_price":"12.507948",
// "settling_asset":{
// // asset structure
// },
// "auction_start_time":null,
// "auction_finish_time":null,
// "settlement_time":"2020-11-15T12:00:00Z",
// "launch_time":"2020-11-14T11:55:05Z",
// "spot_index":{
// // index structure
// },
// "trading_status":"operational",
// "tick_size":"0.001",
// "position_size_limit":100000,
// "notional_type":"vanilla", // vanilla, inverse
// "price_band":"0.4",
// "barrier_price":null,
// "description":"Daily LINK PUT options quoted in USDT and settled in USDT",
// "insurance_fund_margin_contribution":"1",
// "quoting_asset":{
// // asset structure
// },
// "liquidation_penalty_factor":"0.2",
// "product_specs":{"max_volatility":3,"min_volatility":0.3,"spot_price_band":"0.40"},
// "initial_margin_scaling_factor":"0.0001",
// "underlying_asset":{
// // asset structure
// },
// "state":"live",
// "contract_value":"1",
// "initial_margin":"2",
// "impact_size":5000,
// "settlement_price":null,
// "contract_type":"put_options", // put_options, call_options, move_options, perpetual_futures, interest_rate_swaps, futures, spreads
// "taker_commission_rate":"0.0005",
// "maintenance_margin":"1",
// "short_description":"LINK Daily PUT Options",
// "maintenance_margin_scaling_factor":"0.00005",
// "funding_method":"mark_price",
// "max_leverage_notional":"20000"
// },
// // the below response represents item from spot market
// {
// "position_size_limit": 10000000,
// "settlement_price": null,
// "funding_method": "mark_price",
// "settling_asset": null,
// "impact_size": 10,
// "id": 32258,
// "auction_finish_time": null,
// "description": "Solana tether spot market",
// "trading_status": "operational",
// "tick_size": "0.01",
// "liquidation_penalty_factor": "1",
// "spot_index": {
// "config": { "quoting_asset": "USDT", "service_id": 8, "underlying_asset": "SOL" },
// "constituent_exchanges": [
// { "exchange": "binance", "health_interval": 60, "health_priority": 1, "weight": 1 },
// { "exchange": "huobi", "health_interval": 60, "health_priority": 2, "weight": 1 }
// ],
// "constituent_indices": null,
// "description": "Solana index from binance and huobi",
// "health_interval": 300,
// "id": 105,
// "impact_size": "40.000000000000000000",
// "index_type": "spot_pair",
// "is_composite": false,
// "price_method": "ltp",
// "quoting_asset_id": 5,
// "symbol": ".DESOLUSDT",
// "tick_size": "0.000100000000000000",
// "underlying_asset_id": 66
// },
// "contract_type": "spot",
// "launch_time": "2022-02-03T10:18:11Z",
// "symbol": "SOL_USDT",
// "disruption_reason": null,
// "settlement_time": null,
// "insurance_fund_margin_contribution": "1",
// "is_quanto": false,
// "maintenance_margin": "5",
// "taker_commission_rate": "0.0005",
// "auction_start_time": null,
// "max_leverage_notional": "10000000",
// "state": "live",
// "annualized_funding": "0",
// "notional_type": "vanilla",
// "price_band": "100",
// "product_specs": { "kyc_required": false, "max_order_size": 2000, "min_order_size": 0.01, "quoting_precision": 4, "underlying_precision": 2 },
// "default_leverage": "1.000000000000000000",
// "initial_margin": "10",
// "maintenance_margin_scaling_factor": "1",
// "ui_config": {
// "default_trading_view_candle": "1d",
// "leverage_slider_values": [],
// "price_clubbing_values": [ 0.01, 0.05, 0.1, 0.5, 1, 2.5, 5 ],
// "show_bracket_orders": false,
// "sort_priority": 2,
// "tags": []
// },
// "basis_factor_max_limit": "10000",
// "contract_unit_currency": "SOL",
// "strike_price": null,
// "quoting_asset": {
// "base_withdrawal_fee": "10.000000000000000000",
// "deposit_status": "enabled",
// "id": 5,
// "interest_credit": false,
// "interest_slabs": null,
// "kyc_deposit_limit": "100000.000000000000000000",
// "kyc_withdrawal_limit": "10000.000000000000000000",
// "min_withdrawal_amount": "30.000000000000000000",
// "minimum_precision": 2,
// "name": "Tether",
// "networks": [
// { "base_withdrawal_fee": "25", "deposit_status": "enabled", "memo_required": false, "network": "ERC20", "variable_withdrawal_fee": "0", "withdrawal_status": "enabled" },
// { "base_withdrawal_fee": "1", "deposit_status": "enabled", "memo_required": false, "network": "BEP20(BSC)", "variable_withdrawal_fee": "0", "withdrawal_status": "enabled" },
// { "base_withdrawal_fee": "1", "deposit_status": "disabled", "memo_required": false, "network": "TRC20(TRON)", "variable_withdrawal_fee": "0", "withdrawal_status": "disabled" }
// ],
// "precision": 8,
// "sort_priority": 1,
// "symbol": "USDT",
// "variable_withdrawal_fee": "0.000000000000000000",
// "withdrawal_status": "enabled"
// },
// "maker_commission_rate": "0.0005",
// "initial_margin_scaling_factor": "2",
// "underlying_asset": {
// "base_withdrawal_fee": "0.000000000000000000",
// "deposit_status": "enabled",
// "id": 66,
// "interest_credit": false,
// "interest_slabs": null,
// "kyc_deposit_limit": "0.000000000000000000",
// "kyc_withdrawal_limit": "0.000000000000000000",
// "min_withdrawal_amount": "0.020000000000000000",
// "minimum_precision": 4,
// "name": "Solana",
// "networks": [
// { "base_withdrawal_fee": "0.01", "deposit_status": "enabled", "memo_required": false, "network": "SOLANA", "variable_withdrawal_fee": "0", "withdrawal_status": "enabled" },
// { "base_withdrawal_fee": "0.01", "deposit_status": "enabled", "memo_required": false, "network": "BEP20(BSC)", "variable_withdrawal_fee": "0", "withdrawal_status": "enabled" }
// ],
// "precision": 8,
// "sort_priority": 7,
// "symbol": "SOL",
// "variable_withdrawal_fee": "0.000000000000000000",
// "withdrawal_status": "enabled"
// },
// "barrier_price": null,
// "contract_value": "1",
// "short_description": "SOL-USDT spot market"
// },
// ],
// "success":true
// }
//
let mut markets: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
let mut result: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_612: bool = true;
while { if !__for_first_612 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_612 = 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 type_var: Value = self.safe_string_k(market.clone(), "contract_type", &[]);
if (type_var.as_str() == Some("options_combos")) || (type_var.as_str() == Some("binary_call_options")) || (type_var.as_str() == Some("binary_put_options")) {
continue;
}
// const settlingAsset = this.safeValue (market, 'settling_asset', {});
let mut quotingAsset: Value = self.safe_dict_k(market.clone(), "quoting_asset", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut underlyingAsset: Value = self.safe_dict_k(market.clone(), "underlying_asset", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut settlingAsset: Value = self.safe_dict_k(market.clone(), "settling_asset", &[]);
let mut productSpecs: Value = self.safe_dict_k(market.clone(), "product_specs", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut baseId: Value = self.safe_string_k(underlyingAsset, "symbol", &[]);
let mut quoteId: Value = self.safe_string_k(quotingAsset, "symbol", &[]);
let mut settleId: Value = self.safe_string_k(settlingAsset, "symbol", &[]);
let mut id: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut numericId: Value = self.safe_integer_k(market.clone(), "id", &[]);
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(), &[]);
let mut callOptions: bool = type_var.as_str() == Some("call_options");
let mut putOptions: bool = type_var.as_str() == Some("put_options");
let mut moveOptions: bool = type_var.as_str() == Some("move_options");
let mut spot: Value = (Value::Bool(type_var.as_str() == Some("spot")));
let mut swap: Value = (Value::Bool(type_var.as_str() == Some("perpetual_futures")));
let mut future: Value = (Value::Bool(type_var.as_str() == Some("futures")));
let mut option: Value = Value::Bool(callOptions || putOptions || moveOptions);
let mut strike: Value = self.safe_string_k(market.clone(), "strike_price", &[]);
let mut expiryDatetime: Value = self.safe_string_k(market.clone(), "settlement_time", &[]);
let mut expiry: Value = self.parse8601(expiryDatetime);
let mut contractSize: Value = self.safe_number_k(market.clone(), "contract_value", &[]);
let mut amountPrecision: Value = Value::Null;
if matches!(&spot, Value::Bool(true)) {
amountPrecision = self.parse_number(self.parse_precision(&[self.safe_string_k(productSpecs, "underlying_precision", &[])]), &[]); // seems inverse of 'impact_size'
} else {
// other markets (swap, futures, move, spread, irs) seem to use the step of '1' contract
amountPrecision = self.parse_number(Value::Str("1".into()), &[]);
}
let mut linear: Value = (Value::Bool(settle.as_str() == quote.as_str()));
let mut optionType: Value = Value::Null;
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
if matches!(&swap, Value::Bool(true)) || matches!(&future, Value::Bool(true)) || matches!(&option, Value::Bool(true)) {
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbol, Value::Str(":".into())).into()), settle).into());
if matches!(&future, Value::Bool(true)) || matches!(&option, Value::Bool(true)) {
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbol, Value::Str("-".into())).into()), self.yymmdd(expiry.clone(), &[])).into());
if matches!(&option, Value::Bool(true)) {
type_var = Value::Str("option".into());
let mut letter: Value = Value::Str("C".into());
optionType = Value::Str("call".into());
if putOptions {
letter = Value::Str("P".into());
optionType = Value::Str("put".into());
} else if moveOptions {
letter = Value::Str("M".into());
optionType = Value::Str("move".into());
}
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbol, Value::Str("-".into())).into()), strike).into()), Value::Str("-".into())).into()), letter).into());
} else {
type_var = Value::Str("future".into());
}
} else {
type_var = Value::Str("swap".into());
}
}
let mut state: Option<String> = self.safe_string_k(market.clone(), "state", &[]).as_str().map(str::to_owned);
result.push(self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("numericId".to_string(), numericId);
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.clone());
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), swap);
m.insert("future".to_string(), future);
m.insert("option".to_string(), option);
m.insert("active".to_string(), (Value::Bool(state.as_deref() == Some("live"))));
m.insert("contract".to_string(), Value::Bool(!(matches!(&spot, Value::Bool(true)))));
m.insert("linear".to_string(), (if matches!(&spot, Value::Bool(true)) { Value::Null } else { linear.clone() }));
m.insert("inverse".to_string(), (if matches!(&spot, Value::Bool(true)) { Value::Null } else { Value::Bool(!(matches!(&linear, Value::Bool(true)))) }));
m.insert("taker".to_string(), self.safe_number_k(market.clone(), "taker_commission_rate", &[]));
m.insert("maker".to_string(), self.safe_number_k(market.clone(), "maker_commission_rate", &[]));
m.insert("contractSize".to_string(), (if matches!(&spot, Value::Bool(true)) { Value::Null } else { contractSize }));
m.insert("expiry".to_string(), expiry.clone());
m.insert("expiryDatetime".to_string(), self.iso8601(expiry));
m.insert("strike".to_string(), self.parse_number(strike, &[]));
m.insert("optionType".to_string(), optionType);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), amountPrecision);
m.insert("price".to_string(), self.safe_number_k(market.clone(), "tick_size", &[]));
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.parse_number(Value::Str("1".into()), &[]));
m.insert("max".to_string(), self.safe_number_k(market.clone(), "position_size_limit", &[]));
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_size", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), self.parse8601(self.safe_string_k(market.clone(), "launch_time", &[])));
m.insert("info".to_string(), market);
m
})]));
}
}
return Value::from(result);
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
//
// {
// "close": 30634.0,
// "contract_type": "spot",
// "greeks": null,
// "high": 30780.0,
// "low": 30340.5,
// "mark_price": "48000",
// "oi": "0.0000",
// "oi_change_usd_6h": "0.0000",
// "oi_contracts": "0",
// "oi_value": "0.0000",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "0.0000",
// "open": 30464.0,
// "price_band": null,
// "product_id": 8320,
// "quotes": {},
// "size": 2.6816639999999996,
// "spot_price": "30637.91465121",
// "symbol": "BTC_USDT",
// "timestamp": 1689139767621299,
// "turnover": 2.6816639999999996,
// "turnover_symbol": "BTC",
// "turnover_usd": 81896.45613400004,
// "volume": 2.6816639999999996
// }
//
// swap: fetchTicker, fetchTickers
//
// {
// "close": 30600.5,
// "contract_type": "perpetual_futures",
// "funding_rate": "0.00602961",
// "greeks": null,
// "high": 30803.0,
// "low": 30265.5,
// "mark_basis": "-0.45601594",
// "mark_price": "30600.10481568",
// "oi": "469.9190",
// "oi_change_usd_6h": "2226314.9900",
// "oi_contracts": "469919",
// "oi_value": "469.9190",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "14385640.6802",
// "open": 30458.5,
// "price_band": {
// "lower_limit": "29067.08312627",
// "upper_limit": "32126.77608693"
// },
// "product_id": 139,
// "quotes": {
// "ask_iv": null,
// "ask_size": "965",
// "best_ask": "30600.5",
// "best_bid": "30599.5",
// "bid_iv": null,
// "bid_size": "196",
// "impact_mid_price": null,
// "mark_iv": "-0.44931641"
// },
// "size": 1226303,
// "spot_price": "30612.85362773",
// "symbol": "BTCUSDT",
// "timestamp": 1689136597460456,
// "turnover": 37392218.45999999,
// "turnover_symbol": "USDT",
// "turnover_usd": 37392218.45999999,
// "volume": 1226.3029999999485
// }
//
// option: fetchTicker, fetchTickers
//
// {
// "contract_type": "call_options",
// "greeks": {
// "delta": "0.60873994",
// "gamma": "0.00014854",
// "rho": "7.71808010",
// "spot": "30598.49040622",
// "theta": "-30.44743017",
// "vega": "24.83508248"
// },
// "mark_price": "1347.74819696",
// "mark_vol": "0.39966303",
// "oi": "2.7810",
// "oi_change_usd_6h": "0.0000",
// "oi_contracts": "2781",
// "oi_value": "2.7810",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "85127.4337",
// "price_band": {
// "lower_limit": "91.27423497",
// "upper_limit": "7846.19454697"
// },
// "product_id": 107150,
// "quotes": {
// "ask_iv": "0.41023239",
// "ask_size": "2397",
// "best_ask": "1374",
// "best_bid": "1322",
// "bid_iv": "0.38929375",
// "bid_size": "3995",
// "impact_mid_price": null,
// "mark_iv": "0.39965618"
// },
// "spot_price": "30598.43379314",
// "strike_price": "30000",
// "symbol": "C-BTC-30000-280723",
// "timestamp": 1689136932893181,
// "turnover_symbol": "USDT"
// }
//
let mut timestamp: Value = self.safe_integer_product_k(ticker.clone(), "timestamp", Value::Float(0.001), &[]);
let mut marketId: Value = self.safe_string_k(ticker.clone(), "symbol", &[]);
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 last: Value = self.safe_string_k(ticker.clone(), "close", &[]);
let mut quotes: Value = self.safe_dict_k(ticker.clone(), "quotes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
// turnover_symbol names the currency turnover is denominated in, and on
// spot markets that is the base currency rather than the quote
let mut turnoverSymbol: Value = self.safe_string_upper_k(ticker.clone(), "turnover_symbol", &[]);
let mut quoteId: Value = self.safe_string_upper_k(marketResolved.clone(), "quoteId", &[]);
let mut baseDenominated: bool = (turnoverSymbol != Value::Null) && (quoteId != Value::Null) && (turnoverSymbol != quoteId);
let mut quoteVolume: Value = (if baseDenominated { self.safe_number_k(ticker.clone(), "turnover_usd", &[]) } else { self.safe_number_k(ticker.clone(), "turnover", &[]) });
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_number_k(ticker.clone(), "high", &[]));
m.insert("low".to_string(), self.safe_number_k(ticker.clone(), "low", &[]));
m.insert("bid".to_string(), self.safe_number_k(quotes.clone(), "best_bid", &[]));
m.insert("bidVolume".to_string(), self.safe_number_k(quotes.clone(), "bid_size", &[]));
m.insert("ask".to_string(), self.safe_number_k(quotes.clone(), "best_ask", &[]));
m.insert("askVolume".to_string(), self.safe_number_k(quotes, "ask_size", &[]));
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), self.safe_string_k(ticker.clone(), "open", &[]));
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(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), self.safe_number_k(ticker.clone(), "volume", &[]));
m.insert("quoteVolume".to_string(), quoteVolume);
m.insert("markPrice".to_string(), self.safe_number_k(ticker.clone(), "mark_price", &[]));
m.insert("indexPrice".to_string(), self.safe_number_k(ticker.clone(), "spot_price", &[]));
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name delta#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.delta.exchange/#get-ticker-for-a-product-by-symbol
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_0 = self.extend(request, &[params]);
let mut response: Value = self.public_get_tickers_symbol(&[__ws_arg_0]).await;
//
// spot
//
// {
// "result": {
// "close": 30634.0,
// "contract_type": "spot",
// "greeks": null,
// "high": 30780.0,
// "low": 30340.5,
// "mark_price": "48000",
// "oi": "0.0000",
// "oi_change_usd_6h": "0.0000",
// "oi_contracts": "0",
// "oi_value": "0.0000",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "0.0000",
// "open": 30464.0,
// "price_band": null,
// "product_id": 8320,
// "quotes": {},
// "size": 2.6816639999999996,
// "spot_price": "30637.91465121",
// "symbol": "BTC_USDT",
// "timestamp": 1689139767621299,
// "turnover": 2.6816639999999996,
// "turnover_symbol": "BTC",
// "turnover_usd": 81896.45613400004,
// "volume": 2.6816639999999996
// },
// "success": true
// }
//
// swap
//
// {
// "result": {
// "close": 30600.5,
// "contract_type": "perpetual_futures",
// "funding_rate": "0.00602961",
// "greeks": null,
// "high": 30803.0,
// "low": 30265.5,
// "mark_basis": "-0.45601594",
// "mark_price": "30600.10481568",
// "oi": "469.9190",
// "oi_change_usd_6h": "2226314.9900",
// "oi_contracts": "469919",
// "oi_value": "469.9190",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "14385640.6802",
// "open": 30458.5,
// "price_band": {
// "lower_limit": "29067.08312627",
// "upper_limit": "32126.77608693"
// },
// "product_id": 139,
// "quotes": {
// "ask_iv": null,
// "ask_size": "965",
// "best_ask": "30600.5",
// "best_bid": "30599.5",
// "bid_iv": null,
// "bid_size": "196",
// "impact_mid_price": null,
// "mark_iv": "-0.44931641"
// },
// "size": 1226303,
// "spot_price": "30612.85362773",
// "symbol": "BTCUSDT",
// "timestamp": 1689136597460456,
// "turnover": 37392218.45999999,
// "turnover_symbol": "USDT",
// "turnover_usd": 37392218.45999999,
// "volume": 1226.3029999999485
// },
// "success": true
// }
//
// option
//
// {
// "result": {
// "contract_type": "call_options",
// "greeks": {
// "delta": "0.60873994",
// "gamma": "0.00014854",
// "rho": "7.71808010",
// "spot": "30598.49040622",
// "theta": "-30.44743017",
// "vega": "24.83508248"
// },
// "mark_price": "1347.74819696",
// "mark_vol": "0.39966303",
// "oi": "2.7810",
// "oi_change_usd_6h": "0.0000",
// "oi_contracts": "2781",
// "oi_value": "2.7810",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "85127.4337",
// "price_band": {
// "lower_limit": "91.27423497",
// "upper_limit": "7846.19454697"
// },
// "product_id": 107150,
// "quotes": {
// "ask_iv": "0.41023239",
// "ask_size": "2397",
// "best_ask": "1374",
// "best_bid": "1322",
// "bid_iv": "0.38929375",
// "bid_size": "3995",
// "impact_mid_price": null,
// "mark_iv": "0.39965618"
// },
// "spot_price": "30598.43379314",
// "strike_price": "30000",
// "symbol": "C-BTC-30000-280723",
// "timestamp": 1689136932893181,
// "turnover_symbol": "USDT"
// },
// "success": true
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(result, &[market]);
Value::Null
}
/*
* @method
* @name delta#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://docs.delta.exchange/#get-tickers-for-products
* @param {string[]|undefined} symbols unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut response: Value = self.public_get_tickers(&[params]).await;
//
// spot
//
// {
// "result": [
// {
// "close": 30634.0,
// "contract_type": "spot",
// "greeks": null,
// "high": 30780.0,
// "low": 30340.5,
// "mark_price": "48000",
// "oi": "0.0000",
// "oi_change_usd_6h": "0.0000",
// "oi_contracts": "0",
// "oi_value": "0.0000",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "0.0000",
// "open": 30464.0,
// "price_band": null,
// "product_id": 8320,
// "quotes": {},
// "size": 2.6816639999999996,
// "spot_price": "30637.91465121",
// "symbol": "BTC_USDT",
// "timestamp": 1689139767621299,
// "turnover": 2.6816639999999996,
// "turnover_symbol": "BTC",
// "turnover_usd": 81896.45613400004,
// "volume": 2.6816639999999996
// },
// ],
// "success":true
// }
//
// swap
//
// {
// "result": [
// {
// "close": 30600.5,
// "contract_type": "perpetual_futures",
// "funding_rate": "0.00602961",
// "greeks": null,
// "high": 30803.0,
// "low": 30265.5,
// "mark_basis": "-0.45601594",
// "mark_price": "30600.10481568",
// "oi": "469.9190",
// "oi_change_usd_6h": "2226314.9900",
// "oi_contracts": "469919",
// "oi_value": "469.9190",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "14385640.6802",
// "open": 30458.5,
// "price_band": {
// "lower_limit": "29067.08312627",
// "upper_limit": "32126.77608693"
// },
// "product_id": 139,
// "quotes": {
// "ask_iv": null,
// "ask_size": "965",
// "best_ask": "30600.5",
// "best_bid": "30599.5",
// "bid_iv": null,
// "bid_size": "196",
// "impact_mid_price": null,
// "mark_iv": "-0.44931641"
// },
// "size": 1226303,
// "spot_price": "30612.85362773",
// "symbol": "BTCUSDT",
// "timestamp": 1689136597460456,
// "turnover": 37392218.45999999,
// "turnover_symbol": "USDT",
// "turnover_usd": 37392218.45999999,
// "volume": 1226.3029999999485
// },
// ],
// "success":true
// }
//
// option
//
// {
// "result": [
// {
// "contract_type": "call_options",
// "greeks": {
// "delta": "0.60873994",
// "gamma": "0.00014854",
// "rho": "7.71808010",
// "spot": "30598.49040622",
// "theta": "-30.44743017",
// "vega": "24.83508248"
// },
// "mark_price": "1347.74819696",
// "mark_vol": "0.39966303",
// "oi": "2.7810",
// "oi_change_usd_6h": "0.0000",
// "oi_contracts": "2781",
// "oi_value": "2.7810",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "85127.4337",
// "price_band": {
// "lower_limit": "91.27423497",
// "upper_limit": "7846.19454697"
// },
// "product_id": 107150,
// "quotes": {
// "ask_iv": "0.41023239",
// "ask_size": "2397",
// "best_ask": "1374",
// "best_bid": "1322",
// "bid_iv": "0.38929375",
// "bid_size": "3995",
// "impact_mid_price": null,
// "mark_iv": "0.39965618"
// },
// "spot_price": "30598.43379314",
// "strike_price": "30000",
// "symbol": "C-BTC-30000-280723",
// "timestamp": 1689136932893181,
// "turnover_symbol": "USDT"
// },
// ],
// "success":true
// }
//
let mut tickers: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_613: bool = true;
while { if !__for_first_613 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_613 = false; i.as_f64().unwrap_or(f64::NAN) < ((tickers.len() as i64) as f64) } {
let mut rawTicker: Value = tickers.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut contractType: Option<String> = self.safe_string_k(rawTicker.clone(), "contract_type", &[]).as_str().map(str::to_owned);
if (contractType.as_deref() == Some("options_combos")) || (contractType.as_deref() == Some("binary_call_options")) || (contractType.as_deref() == Some("binary_put_options")) {
continue;
}
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 delta#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.delta.exchange/#get-l2-orderbook
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn fetch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("depth".into(), limit); }
}
let __ws_arg_1 = self.extend(request, &[params]);
let mut response: Value = self.public_get_l2orderbook_symbol(&[__ws_arg_1]).await;
//
// {
// "result":{
// "buy":[
// {"price":"15814.0","size":912},
// {"price":"15813.5","size":1279},
// {"price":"15813.0","size":1634},
// ],
// "sell":[
// {"price":"15814.5","size":625},
// {"price":"15815.0","size":982},
// {"price":"15815.5","size":1328},
// ],
// "symbol":"BTCUSDT"
// },
// "success":true
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order_book(result, market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[Value::Null, Value::Str("buy".into()), Value::Str("sell".into()), Value::Str("price".into()), Value::Str("size".into())]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// public fetchTrades
//
// {
// "buyer_role":"maker",
// "price":"15896.5",
// "seller_role":"taker",
// "size":241,
// "symbol":"BTCUSDT",
// "timestamp":1605376684714595
// }
//
// private fetchMyTrades
//
// {
// "commission":"0.008335000000000000",
// "created_at":"2020-11-16T19:07:19Z",
// "fill_type":"normal",
// "id":"e7ff05c233a74245b72381f8dd91d1ce",
// "meta_data":{
// "effective_commission_rate":"0.0005",
// "order_price":"16249",
// "order_size":1,
// "order_type":"market_order",
// "order_unfilled_size":0,
// "trading_fee_credits_used":"0"
// },
// "order_id":"152999629",
// "price":"16669",
// "product":{
// "contract_type":"perpetual_futures",
// "contract_unit_currency":"BTC",
// "contract_value":"0.001",
// "id":139,
// "notional_type":"vanilla",
// "quoting_asset":{"minimum_precision":2,"precision":6,"symbol":"USDT"},
// "settling_asset":{"minimum_precision":2,"precision":6,"symbol":"USDT"},
// "symbol":"BTCUSDT",
// "tick_size":"0.5",
// "underlying_asset":{"minimum_precision":4,"precision":8,"symbol":"BTC"}
// },
// "product_id":139,
// "role":"taker",
// "side":"sell",
// "size":1
// }
//
let mut id: Value = self.safe_string_k(trade.clone(), "id", &[]);
let mut orderId: Value = self.safe_string_k(trade.clone(), "order_id", &[]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(trade.clone(), "created_at", &[]));
timestamp = self.safe_integer_product_k(trade.clone(), "timestamp", Value::Float(0.001), &[timestamp.clone()]);
let mut priceString: Value = self.safe_string_k(trade.clone(), "price", &[]);
let mut amountString: Value = self.safe_string_k(trade.clone(), "size", &[]);
let mut product: Value = self.safe_dict_k(trade.clone(), "product", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketId: Value = self.safe_string_k(product.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market.clone()]);
let mut sellerRole: Option<String> = self.safe_string_k(trade.clone(), "seller_role", &[]).as_str().map(str::to_owned);
let mut side: Value = self.safe_string_k(trade.clone(), "side", &[]);
if (side == Value::Null) {
if (sellerRole.as_deref() == Some("taker")) {
side = Value::Str("sell".into());
} else if (sellerRole.as_deref() == Some("maker")) {
side = Value::Str("buy".into());
}
}
let mut takerOrMaker: Value = self.safe_string_k(trade.clone(), "role", &[]);
let mut metaData: Value = self.safe_dict_k(trade.clone(), "meta_data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut type_var: Value = self.safe_string_k(metaData, "order_type", &[]);
if (type_var != Value::Null) {
type_var = type_var.as_str().map(|__s| Value::Str(__s.replace("_order", "").into())).unwrap_or_else(|| type_var.clone());
}
let mut feeCostString: Value = self.safe_string_k(trade.clone(), "commission", &[]);
let mut fee: Value = Value::Null;
if (feeCostString != Value::Null) {
let mut settlingAsset: Value = self.safe_dict_k(product, "settling_asset", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut feeCurrencyId: Value = self.safe_string_k(settlingAsset, "symbol", &[]);
let mut feeCurrencyCode: Value = 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("order".to_string(), orderId);
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("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.insert("info".to_string(), trade);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name delta#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://docs.delta.exchange/#get-public-trades
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_2 = self.extend(request, &[params]);
let mut response: Value = self.public_get_trades_symbol(&[__ws_arg_2]).await;
//
// {
// "result":[
// {
// "buyer_role":"maker",
// "price":"15896.5",
// "seller_role":"taker",
// "size":241,
// "symbol":"BTCUSDT",
// "timestamp":1605376684714595
// }
// ],
// "success":true
// }
//
let mut result: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
return self.parse_trades(result, &[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);
return Value::from(vec![self.safe_timestamp_k(ohlcv.clone(), "time", &[]), self.safe_number_k(ohlcv.clone(), "open", &[]), self.safe_number_k(ohlcv.clone(), "high", &[]), self.safe_number_k(ohlcv.clone(), "low", &[]), self.safe_number_k(ohlcv.clone(), "close", &[]), self.safe_number_k(ohlcv, "volume", &[])]);
Value::Null
}
/*
* @method
* @name delta#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://docs.delta.exchange/#delta-exchange-api-v2-historical-ohlc-candles-sparklines
* @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 {string} [params.until] timestamp in ms of the latest candle to fetch
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("resolution".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m
});
let mut duration: Value = self.parse_timeframe(timeframe.clone());
let mut limitValue: Value = Value::Int(2000);
let mut windowSeconds: Value = (match (&(Value::Int(2000)), &(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 (limit != Value::Null) && (limit != Value::Null) && (limit.as_f64() != Some(0.0)) {
limitValue = limit.clone(); // max 2000
windowSeconds = (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 until: Value = self.safe_integer_product_k(params.clone(), "until", Value::Float(0.001), &[]);
let mut untilIsDefined: bool = until != Value::Null;
if untilIsDefined {
until = self.parse_to_int(until.clone());
}
if (since == Value::Null) {
let mut end: Value = self.seconds();
if untilIsDefined {
end = self.parse_to_int(until.clone());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), end.clone()); }
if (end == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() missing end".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start".into(), (match (&(end), &(windowSeconds)) { (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 })); }
} else {
let mut start: Value = 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 }));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start".into(), start.clone()); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), (if untilIsDefined { until } else { self.sum(&[start, windowSeconds]) })); }
}
let mut price: Option<String> = self.safe_string_k(params.clone(), "price", &[]).as_str().map(str::to_owned);
if (price.as_deref() == Some("mark")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), Value::Str(format!("{}{}", Value::Str("MARK:".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into())); }
} else if (price.as_deref() == Some("index")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), crate::value::get_value_k(&crate::value::get_value_k(&market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), "spot_index"), "symbol")); }
} 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 mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("price".into()), Value::Str("until".into())]), &[]);
let __ws_arg_3 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.public_get_history_candles(&[__ws_arg_3]).await;
//
// {
// "success":true,
// "result":[
// {"time":1605393120,"open":15989,"high":15989,"low":15987.5,"close":15987.5,"volume":565},
// {"time":1605393180,"open":15966,"high":15966,"low":15959,"close":15959,"volume":24},
// {"time":1605393300,"open":15973,"high":15973,"low":15973,"close":15973,"volume":1288},
// ]
// }
//
let mut result: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
return self.parse_ohlc_vs(result, &[market, timeframe, since, limitValue]);
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
let mut balances: Value = self.safe_list_k(response.clone(), "result", &[Value::from(vec![])]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
});
let mut currenciesByNumericId: Value = self.safe_dict_k(self.options.clone(), "currenciesByNumericId", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_614: bool = true;
while { if !__for_first_614 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_614 = false; i.as_f64().unwrap_or(f64::NAN) < ((balances.len() as i64) as f64) } {
let mut balance: Value = self.safe_dict(balances.clone(), i.clone(), &[]);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "asset_id", &[]);
let mut currency: Value = self.safe_dict(currenciesByNumericId.clone(), currencyId.clone(), &[]);
let mut code: Value = (if (currency == Value::Null) { currencyId } else { currency.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null) });
let mut account: Value = self.account();
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string_k(balance.clone(), "balance", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_k(balance, "available_balance", &[])); }
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 delta#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://docs.delta.exchange/#get-wallet-balances
* @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
}));
self.load_markets(&[]).await;
let mut response: Value = self.private_get_wallet_balances(&[params]).await;
return self.parse_balance(response);
Value::Null
}
/*
* @method
* @name delta#fetchPosition
* @description fetch data on a single open contract trade position
* @see https://docs.delta.exchange/#get-position
* @param {string} symbol unified market symbol of the market the position is held in, default is undefined
* @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
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), market.as_map().and_then(|__m| __m.get("numericId")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_4 = self.extend(request, &[params]);
let mut response: Value = self.private_get_positions(&[__ws_arg_4]).await;
//
// {
// "result":{
// "entry_price":null,
// "size":0,
// "timestamp":1605454074268079
// },
// "success":true
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_position(result, &[market]);
Value::Null
}
/*
* @method
* @name delta#fetchPositions
* @description fetch all open positions
* @see https://docs.delta.exchange/#get-margined-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 structure]{@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
}));
self.load_markets(&[]).await;
let mut response: Value = self.private_get_positions_margined(&[params]).await;
//
// {
// "success": true,
// "result": [
// {
// "user_id": 0,
// "size": 0,
// "entry_price": "string",
// "margin": "string",
// "liquidation_price": "string",
// "bankruptcy_price": "string",
// "adl_level": 0,
// "product_id": 0,
// "product_symbol": "string",
// "commission": "string",
// "realized_pnl": "string",
// "realized_funding": "string"
// }
// ]
// }
//
let mut result: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
return self.parse_positions(result, &[symbols]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchPosition
//
// {
// "entry_price":null,
// "size":0,
// "timestamp":1605454074268079
// }
//
//
// fetchPositions
//
// {
// "user_id": 0,
// "size": 0,
// "entry_price": "string",
// "margin": "string",
// "liquidation_price": "string",
// "bankruptcy_price": "string",
// "adl_level": 0,
// "product_id": 0,
// "product_symbol": "string",
// "commission": "string",
// "realized_pnl": "string",
// "realized_funding": "string"
// }
//
let mut marketId: Value = self.safe_string_k(position.clone(), "product_symbol", &[]);
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 timestamp: Value = self.safe_integer_product_k(position.clone(), "timestamp", Value::Float(0.001), &[]);
let mut sizeString: Value = self.safe_string_k(position.clone(), "size", &[]);
let mut side: Value = Value::Null;
if (sizeString != Value::Null) {
if crate::precise::Precise::stringGt(&sizeString, &Value::Str("0".into())).as_bool() == Some(true) {
side = Value::Str("long".into());
} else if crate::precise::Precise::stringLt(&sizeString, &Value::Str("0".into())).as_bool() == Some(true) {
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(), Value::Null);
m.insert("marginMode".to_string(), self.safe_string_k(position.clone(), "margin_mode", &[]));
m.insert("liquidationPrice".to_string(), self.safe_number_k(position.clone(), "liquidation_price", &[]));
m.insert("entryPrice".to_string(), self.safe_number_k(position.clone(), "entry_price", &[]));
m.insert("unrealizedPnl".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("contracts".to_string(), self.parse_number(sizeString, &[]));
m.insert("contractSize".to_string(), self.safe_number_k(marketResolved, "contractSize", &[]));
m.insert("markPrice".to_string(), Value::Null);
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(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("positionMargin".to_string(), self.safe_number_k(position, "margin", &[]));
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(), Value::Null);
m.insert("marginRatio".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Option<String> {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("open".to_string(), Value::Str("open".into()));
m.insert("pending".to_string(), Value::Str("open".into()));
m.insert("closed".to_string(), Value::Str("closed".into()));
m.insert("cancelled".to_string(), Value::Str("canceled".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// createOrder, cancelOrder, editOrder, fetchOpenOrders, fetchClosedOrders
//
// {
// "average_fill_price":null,
// "bracket_order":null,
// "bracket_stop_loss_limit_price":null,
// "bracket_stop_loss_price":null,
// "bracket_take_profit_limit_price":null,
// "bracket_take_profit_price":null,
// "bracket_trail_amount":null,
// "cancellation_reason":null,
// "client_order_id":null,
// "close_on_trigger":"false",
// "commission":"0",
// "created_at":"2020-11-16T02:38:26Z",
// "id":152870626,
// "limit_price":"10000",
// "meta_data":{"source":"api"},
// "order_type":"limit_order",
// "paid_commission":"0",
// "product_id":139,
// "reduce_only":false,
// "side":"buy",
// "size":0,
// "state":"open",
// "stop_order_type":null,
// "stop_price":null,
// "stop_trigger_method":"mark_price",
// "time_in_force":"gtc",
// "trail_amount":null,
// "unfilled_size":0,
// "user_id":22142
// }
//
// fetchOrder
//
// {
// "id": 123,
// "user_id": 453671,
// "size": 10,
// "unfilled_size": 2,
// "side": "buy",
// "order_type": "limit_order",
// "limit_price": "59000",
// "stop_order_type": "stop_loss_order",
// "stop_price": "55000",
// "paid_commission": "0.5432",
// "commission": "0.5432",
// "reduce_only": false,
// "client_order_id": "my_signal_34521712",
// "state": "open",
// "created_at": "1725865012000000",
// "product_id": 27,
// "product_symbol": "BTCUSD"
// }
//
let mut id: Value = self.safe_string_k(order.clone(), "id", &[]);
let mut clientOrderId: Value = self.safe_string_k(order.clone(), "client_order_id", &[]);
let mut createdAt: Value = self.safe_string_k(order.clone(), "created_at", &[]);
let mut timestamp: Value = Value::Null;
if (createdAt != Value::Null) {
if Value::Int(createdAt.as_str().and_then(|__s| __s.find("-")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
timestamp = self.parse8601(createdAt);
} else {
timestamp = self.safe_integer_product_k(order.clone(), "created_at", Value::Float(0.001), &[]);
}
}
let mut marketId: Value = self.safe_string_k(order.clone(), "product_id", &[]);
let mut marketsByNumericId: Value = self.safe_dict_k(self.options.clone(), "marketsByNumericId", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketValue: Value = self.safe_value(marketsByNumericId, marketId.clone(), &[market]);
let mut symbol: Value = Value::Null;
if (marketValue == Value::Null) {
symbol = marketId;
} else {
symbol = marketValue.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
}
let mut status: Value = self.parse_order_status(self.safe_string_k(order.clone(), "state", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut side: Value = self.safe_string_k(order.clone(), "side", &[]);
let mut type_var: Value = self.safe_string_k(order.clone(), "order_type", &[]);
if (type_var != Value::Null) {
type_var = type_var.as_str().map(|__s| Value::Str(__s.replace("_order", "").into())).unwrap_or_else(|| type_var.clone());
}
let mut price: Value = self.safe_string_k(order.clone(), "limit_price", &[]);
let mut amount: Value = self.safe_string_k(order.clone(), "size", &[]);
let mut remaining: Value = self.safe_string_k(order.clone(), "unfilled_size", &[]);
let mut average: Value = self.safe_string_k(order.clone(), "average_fill_price", &[]);
let mut fee: Value = Value::Null;
let mut feeCostString: Value = self.safe_string_k(order.clone(), "paid_commission", &[]);
if (feeCostString != Value::Null) {
let mut feeCurrencyCode: Value = Value::Null;
if (marketValue != Value::Null) {
let mut settlingAsset: Value = self.safe_dict(marketValue.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("settling_asset".into()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut feeCurrencyId: Value = self.safe_string_k(settlingAsset, "symbol", &[]);
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_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order);
m.insert("id".to_string(), id);
m.insert("clientOrderId".to_string(), clientOrderId);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), type_var);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), average);
m.insert("filled".to_string(), Value::Null);
m.insert("remaining".to_string(), remaining);
m.insert("status".to_string(), status);
m.insert("fee".to_string(), fee);
m.insert("trades".to_string(), Value::Null);
m
}), &[marketValue]);
Value::Null
}
/*
* @method
* @name delta#createOrder
* @description create a trade order
* @see https://docs.delta.exchange/#place-order
* @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 of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {bool} [params.reduceOnly] *contract only* indicates if this order is to reduce the size of a position
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_order(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut orderType: Value = Value::Str(format!("{}{}", type_var, Value::Str("_order".into())).into());
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), market.as_map().and_then(|__m| __m.get("numericId")).cloned().unwrap_or(Value::Null));
m.insert("size".to_string(), self.amount_to_precision(market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), amount));
m.insert("side".to_string(), side);
m.insert("order_type".to_string(), orderType);
m
});
if (type_var.as_str() == Some("limit")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit_price".into(), self.price_to_precision(market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), price)); }
}
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clientOrderId".into()), Value::Str("client_order_id".into()), &[]);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("client_order_id".into())]), &[]);
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("client_order_id".into(), clientOrderId); }
}
let mut reduceOnly: Value = self.safe_bool_k(paramsOmitted.clone(), "reduceOnly", &[]);
if (reduceOnly.as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("reduce_only".into(), reduceOnly.clone()); }
}
let mut paramsOmitted2: Value = (if (reduceOnly.as_bool() == Some(true)) { self.omit(paramsOmitted.clone(), Value::Str("reduceOnly".into()), &[]) } else { paramsOmitted });
let __ws_arg_5 = self.extend(request, &[paramsOmitted2]);
let mut response: Value = self.private_post_orders(&[__ws_arg_5]).await;
//
// {
// "result":{
// "average_fill_price":null,
// "bracket_order":null,
// "bracket_stop_loss_limit_price":null,
// "bracket_stop_loss_price":null,
// "bracket_take_profit_limit_price":null,
// "bracket_take_profit_price":null,
// "bracket_trail_amount":null,
// "cancellation_reason":null,
// "client_order_id":null,
// "close_on_trigger":"false",
// "commission":"0",
// "created_at":"2020-11-16T02:38:26Z",
// "id":152870626,
// "limit_price":"10000",
// "meta_data":{"source":"api"},
// "order_type":"limit_order",
// "paid_commission":"0",
// "product_id":139,
// "reduce_only":false,
// "side":"buy",
// "size":0,
// "state":"open",
// "stop_order_type":null,
// "stop_price":null,
// "stop_trigger_method":"mark_price",
// "time_in_force":"gtc",
// "trail_amount":null,
// "unfilled_size":0,
// "user_id":22142
// },
// "success":true
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(result, &[market]);
Value::Null
}
/*
* @method
* @name delta#editOrder
* @description edit a trade order
* @see https://docs.delta.exchange/#edit-order
* @param {string} id order id
* @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 of the currency you want to trade in units of the base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), (match &id { Value::Str(__parse_s) => __parse_s.trim().parse::<i64>().map(Value::Int).unwrap_or(Value::Null), Value::Int(__parse_n) => Value::Int(*__parse_n), Value::Float(__parse_f) => Value::Int(*__parse_f as i64), _ => Value::Null }));
m.insert("product_id".to_string(), market.as_map().and_then(|__m| __m.get("numericId")).cloned().unwrap_or(Value::Null));
m
});
if (amount != Value::Null) {
let mut sizeString: Value = self.amount_to_precision(symbol.clone(), amount);
if (sizeString == Value::Null) {
sizeString = Value::Str("0".into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("size".into(), (match &sizeString { Value::Str(__parse_s) => __parse_s.trim().parse::<i64>().map(Value::Int).unwrap_or(Value::Null), Value::Int(__parse_n) => Value::Int(*__parse_n), Value::Float(__parse_f) => Value::Int(*__parse_f as i64), _ => Value::Null })); }
}
if (price != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit_price".into(), self.price_to_precision(symbol, price)); }
}
let __ws_arg_6 = self.extend(request, &[params]);
let mut response: Value = self.private_put_orders(&[__ws_arg_6]).await;
//
// {
// "success": true,
// "result": {
// "id": "ashb1212",
// "product_id": 27,
// "limit_price": "9200",
// "side": "buy",
// "size": 100,
// "unfilled_size": 50,
// "user_id": 1,
// "order_type": "limit_order",
// "state": "open",
// "created_at": "..."
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(result, &[market]);
Value::Null
}
/*
* @method
* @name delta#cancelOrder
* @description cancels an open order
* @see https://docs.delta.exchange/#cancel-order
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn 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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() requires a symbol argument".into()))));
}
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), (match &id { Value::Str(__parse_s) => __parse_s.trim().parse::<i64>().map(Value::Int).unwrap_or(Value::Null), Value::Int(__parse_n) => Value::Int(*__parse_n), Value::Float(__parse_f) => Value::Int(*__parse_f as i64), _ => Value::Null }));
m.insert("product_id".to_string(), market.as_map().and_then(|__m| __m.get("numericId")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_7 = self.extend(request, &[params]);
let mut response: Value = self.private_delete_orders(&[__ws_arg_7]).await;
//
// {
// "result":{
// "average_fill_price":null,
// "bracket_order":null,
// "bracket_stop_loss_limit_price":null,
// "bracket_stop_loss_price":null,
// "bracket_take_profit_limit_price":null,
// "bracket_take_profit_price":null,
// "bracket_trail_amount":null,
// "cancellation_reason":"cancelled_by_user",
// "client_order_id":null,
// "close_on_trigger":"false",
// "commission":"0",
// "created_at":"2020-11-16T02:38:26Z",
// "id":152870626,
// "limit_price":"10000",
// "meta_data":{"source":"api"},
// "order_type":"limit_order",
// "paid_commission":"0",
// "product_id":139,
// "reduce_only":false,
// "side":"buy",
// "size":0,
// "state":"cancelled",
// "stop_order_type":null,
// "stop_price":null,
// "stop_trigger_method":"mark_price",
// "time_in_force":"gtc",
// "trail_amount":null,
// "unfilled_size":0,
// "user_id":22142
// },
// "success":true
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(result, &[market]);
Value::Null
}
/*
* @method
* @name delta#cancelAllOrders
* @description cancel all open orders in a market
* @see https://docs.delta.exchange/#cancel-all-open-orders
* @param {string} symbol unified market symbol of the market to cancel orders in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_all_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelAllOrders() requires a symbol argument".into()))));
}
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), market.as_map().and_then(|__m| __m.get("numericId")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_8 = self.extend(request, &[params]);
let mut response: Value = self.private_delete_orders_all(&[__ws_arg_8]).await;
return Value::from(vec![self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
}), &[])]);
Value::Null
}
/*
* @method
* @name delta#fetchOrder
* @description fetches information on an order made by the user
* @see https://docs.delta.exchange/#get-order-by-id
* @see https://docs.delta.exchange/#get-order-by-client-oid
* @param {string} id the order id
* @param {string} [symbol] unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] client order id of the order
* @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
}));
self.load_markets(&[]).await;
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut clientOrderId: Value = self.safe_string_n(params.clone(), Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("client_oid".into()), Value::Str("clientOid".into())]), &[]);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("client_oid".into()), Value::Str("clientOid".into())]), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("client_oid".into(), clientOrderId); }
let __ws_arg_9 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.private_get_orders_client_order_id_client_oid(&[__ws_arg_9]).await;
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("order_id".into(), id); }
let __ws_arg_10 = self.extend(request, &[paramsOmitted]);
response = self.private_get_orders_order_id(&[__ws_arg_10]).await;
}
//
// {
// "success": true,
// "result": {
// "id": 123,
// "user_id": 453671,
// "size": 10,
// "unfilled_size": 2,
// "side": "buy",
// "order_type": "limit_order",
// "limit_price": "59000",
// "stop_order_type": "stop_loss_order",
// "stop_price": "55000",
// "paid_commission": "0.5432",
// "commission": "0.5432",
// "reduce_only": false,
// "client_order_id": "my_signal_34521712",
// "state": "open",
// "created_at": "1725865012000000",
// "product_id": 27,
// "product_symbol": "BTCUSD"
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(result, &[market]);
Value::Null
}
/*
* @method
* @name delta#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://docs.delta.exchange/#get-active-orders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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
}));
return self.fetch_orders_with_method(Value::Str("privateGetOrders".into()), &[symbol, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name delta#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://docs.delta.exchange/#get-order-history-cancelled-and-closed
* @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_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_orders_with_method(Value::Str("privateGetOrdersHistory".into()), &[symbol, since, limit, params]).await;
Value::Null
}
pub async fn fetch_orders_with_method(&mut self, mut method: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut 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("product_ids".into(), market.as_map().and_then(|__m| __m.get("numericId")).cloned().unwrap_or(Value::Null)); }; // accepts a comma-separated list of ids
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_time".into(), Value::Str(format!("{}{}", Value::Str(format!("{}", since).into()), Value::Str("000".into())).into())); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("page_size".into(), limit.clone()); }
}
let mut response: Value = Value::Null;
if (method.as_str() == Some("privateGetOrders")) {
let __ws_arg_11 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_orders(&[__ws_arg_11]).await;
} else if (method.as_str() == Some("privateGetOrdersHistory")) {
let __ws_arg_12 = self.extend(request, &[params]);
response = self.private_get_orders_history(&[__ws_arg_12]).await;
}
//
// {
// "success": true,
// "result": [
// {
// "id": "ashb1212",
// "product_id": 27,
// "limit_price": "9200",
// "side": "buy",
// "size": 100,
// "unfilled_size": 50,
// "user_id": 1,
// "order_type": "limit_order",
// "state": "open",
// "created_at": "..."
// }
// ],
// "meta": {
// "after": "string",
// "before": "string"
// }
// }
//
let mut result: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
return self.parse_orders(result, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name delta#fetchMyTrades
* @description fetch all trades made by the user
* @see https://docs.delta.exchange/#get-user-fills-by-filters
* @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
}));
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("product_ids".into(), market.as_map().and_then(|__m| __m.get("numericId")).cloned().unwrap_or(Value::Null)); }; // accepts a comma-separated list of ids
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_time".into(), Value::Str(format!("{}{}", Value::Str(format!("{}", since).into()), Value::Str("000".into())).into())); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("page_size".into(), limit.clone()); }
}
let __ws_arg_13 = self.extend(request, &[params]);
let mut response: Value = self.private_get_fills(&[__ws_arg_13]).await;
//
// {
// "meta":{
// "after":null,
// "before":null,
// "limit":10,
// "total_count":2
// },
// "result":[
// {
// "commission":"0.008335000000000000",
// "created_at":"2020-11-16T19:07:19Z",
// "fill_type":"normal",
// "id":"e7ff05c233a74245b72381f8dd91d1ce",
// "meta_data":{
// "effective_commission_rate":"0.0005",
// "order_price":"16249",
// "order_size":1,
// "order_type":"market_order",
// "order_unfilled_size":0,
// "trading_fee_credits_used":"0"
// },
// "order_id":"152999629",
// "price":"16669",
// "product":{
// "contract_type":"perpetual_futures",
// "contract_unit_currency":"BTC",
// "contract_value":"0.001",
// "id":139,
// "notional_type":"vanilla",
// "quoting_asset":{"minimum_precision":2,"precision":6,"symbol":"USDT"},
// "settling_asset":{"minimum_precision":2,"precision":6,"symbol":"USDT"},
// "symbol":"BTCUSDT",
// "tick_size":"0.5",
// "underlying_asset":{"minimum_precision":4,"precision":8,"symbol":"BTC"}
// },
// "product_id":139,
// "role":"taker",
// "side":"sell",
// "size":1
// }
// ],
// "success":true
// }
//
let mut result: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
return self.parse_trades(result, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name delta#fetchLedger
* @description fetch the history of changes, actions done by the user or operations that altered the balance of the user
* @see https://docs.delta.exchange/#get-wallet-transactions
* @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
}));
self.load_markets(&[]).await;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
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("asset_id".into(), currency.as_map().and_then(|__m| __m.get("numericId")).cloned().unwrap_or(Value::Null)); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("page_size".into(), limit.clone()); }
}
let __ws_arg_14 = self.extend(request, &[params]);
let mut response: Value = self.private_get_wallet_transactions(&[__ws_arg_14]).await;
//
// {
// "meta":{"after":null,"before":null,"limit":10,"total_count":1},
// "result":[
// {
// "amount":"29.889184",
// "asset_id":5,
// "balance":"29.889184",
// "created_at":"2020-11-15T21:25:01Z",
// "meta_data":{
// "deposit_id":3884,
// "transaction_id":"0x41a60174849828530abb5008e98fc63c9b598288743ec4ba9620bcce900a3b8d"
// },
// "transaction_type":"deposit",
// "user_id":22142,
// "uuid":"70bb5679da3c4637884e2dc63efaa846"
// }
// ],
// "success":true
// }
//
let mut result: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
return self.parse_ledger(result, &[currency, since, limit]);
Value::Null
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pnl".to_string(), Value::Str("pnl".into()));
m.insert("deposit".to_string(), Value::Str("transaction".into()));
m.insert("withdrawal".to_string(), Value::Str("transaction".into()));
m.insert("commission".to_string(), Value::Str("fee".into()));
m.insert("conversion".to_string(), Value::Str("trade".into()));
m.insert("referral_bonus".to_string(), Value::Str("referral".into()));
m.insert("commission_rebate".to_string(), Value::Str("rebate".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "amount":"29.889184",
// "asset_id":5,
// "balance":"29.889184",
// "created_at":"2020-11-15T21:25:01Z",
// "meta_data":{
// "deposit_id":3884,
// "transaction_id":"0x41a60174849828530abb5008e98fc63c9b598288743ec4ba9620bcce900a3b8d"
// },
// "transaction_type":"deposit",
// "user_id":22142,
// "uuid":"70bb5679da3c4637884e2dc63efaa846"
// }
//
let mut id: Value = self.safe_string_k(item.clone(), "uuid", &[]);
let mut direction: Value = Value::Null;
let mut account: Value = Value::Null;
let mut metaData: Value = self.safe_dict_k(item.clone(), "meta_data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut referenceId: Value = self.safe_string_k(metaData, "transaction_id", &[]);
let mut referenceAccount: Value = Value::Null;
let mut type_var: Value = self.safe_string_k(item.clone(), "transaction_type", &[]);
if (type_var.as_str() == Some("deposit")) || (type_var.as_str() == Some("commission_rebate")) || (type_var.as_str() == Some("referral_bonus")) || (type_var.as_str() == Some("pnl")) || (type_var.as_str() == Some("withdrawal_cancellation")) || (type_var.as_str() == Some("promo_credit")) {
direction = Value::Str("in".into());
} else if (type_var.as_str() == Some("withdrawal")) || (type_var.as_str() == Some("commission")) || (type_var.as_str() == Some("conversion")) || (type_var.as_str() == Some("perpetual_futures_funding")) {
direction = Value::Str("out".into());
}
type_var = self.parse_ledger_entry_type(type_var.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut currencyId: Value = self.safe_string_k(item.clone(), "asset_id", &[]);
let mut currenciesByNumericId: Value = self.safe_dict_k(self.options.clone(), "currenciesByNumericId", &[]);
let mut currencyValue: Value = self.safe_value(currenciesByNumericId, currencyId, &[currency]);
let mut code: Value = (if (currencyValue == Value::Null) { Value::Null } else { currencyValue.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null) });
let mut amount: Value = self.safe_string_k(item.clone(), "amount", &[]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(item.clone(), "created_at", &[]));
let mut after: Value = self.safe_string_k(item.clone(), "balance", &[]);
let mut before: Value = crate::precise::Precise::stringMax(&Value::Str("0".into()), &crate::precise::Precise::stringSub(&after, &amount));
let mut status: Value = Value::Str("ok".into());
return self.safe_ledger_entry(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), item);
m.insert("id".to_string(), id);
m.insert("direction".to_string(), direction);
m.insert("account".to_string(), account);
m.insert("referenceId".to_string(), referenceId);
m.insert("referenceAccount".to_string(), referenceAccount);
m.insert("type".to_string(), type_var);
m.insert("currency".to_string(), code);
m.insert("amount".to_string(), self.parse_number(amount, &[]));
m.insert("before".to_string(), self.parse_number(before, &[]));
m.insert("after".to_string(), self.parse_number(after, &[]));
m.insert("status".to_string(), status);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("fee".to_string(), Value::Null);
m
}), &[currencyValue]);
Value::Null
}
/*
* @method
* @name delta#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.network] unified network code
* @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
}));
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("asset_symbol".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut networkCode: Value = self.safe_string_upper_k(params.clone(), "network", &[]);
if (networkCode != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("network".into(), self.network_code_to_id(networkCode.clone(), &[code])); }
}
let mut paramsOmitted: Value = (if (networkCode != Value::Null) { self.omit(params.clone(), Value::Str("network".into()), &[]) } else { params });
let __ws_arg_15 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_get_deposits_address(&[__ws_arg_15]).await;
//
// {
// "success": true,
// "result": {
// "id": 1915615,
// "user_id": 27854758,
// "address": "TXYB4GdKsXKEWbeSNPsmGZu4ZVCkhVh1Zz",
// "memo": "",
// "status": "active",
// "updated_at": "2023-01-12T06:03:46.000Z",
// "created_at": "2023-01-12T06:03:46.000Z",
// "asset_symbol": "USDT",
// "network": "TRC20(TRON)",
// "custodian": "fireblocks"
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_deposit_address(result, &[currency]);
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);
//
// {
// "id": 1915615,
// "user_id": 27854758,
// "address": "TXYB4GdKsXKEWbeSNPsmGZu4ZVCkhVh1Zz",
// "memo": "",
// "status": "active",
// "updated_at": "2023-01-12T06:03:46.000Z",
// "created_at": "2023-01-12T06:03:46.000Z",
// "asset_symbol": "USDT",
// "network": "TRC20(TRON)",
// "custodian": "fireblocks"
// }
//
let mut address: Value = self.safe_string_k(depositAddress.clone(), "address", &[]);
let mut marketId: Value = self.safe_string_k(depositAddress.clone(), "asset_symbol", &[]);
let mut networkId: Value = self.safe_string_k(depositAddress.clone(), "network", &[]);
let mut code: Value = self.safe_currency_code(marketId, &[currency]);
self.check_address(&[address.clone()]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), depositAddress.clone());
m.insert("currency".to_string(), code.clone());
m.insert("network".to_string(), self.network_id_to_code(&[networkId, code]));
m.insert("address".to_string(), address);
m.insert("tag".to_string(), self.safe_string_k(depositAddress, "memo", &[]));
m
});
Value::Null
}
/*
* @method
* @name delta#fetchFundingRate
* @description fetch the current funding rate
* @see https://docs.delta.exchange/#get-ticker-for-a-product-by-symbol
* @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
}));
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("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_16 = self.extend(request, &[params]);
let mut response: Value = self.public_get_tickers_symbol(&[__ws_arg_16]).await;
//
// {
// "result": {
// "close": 30600.5,
// "contract_type": "perpetual_futures",
// "funding_rate": "0.00602961",
// "greeks": null,
// "high": 30803.0,
// "low": 30265.5,
// "mark_basis": "-0.45601594",
// "mark_price": "30600.10481568",
// "oi": "469.9190",
// "oi_change_usd_6h": "2226314.9900",
// "oi_contracts": "469919",
// "oi_value": "469.9190",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "14385640.6802",
// "open": 30458.5,
// "price_band": {
// "lower_limit": "29067.08312627",
// "upper_limit": "32126.77608693"
// },
// "product_id": 139,
// "quotes": {
// "ask_iv": null,
// "ask_size": "965",
// "best_ask": "30600.5",
// "best_bid": "30599.5",
// "bid_iv": null,
// "bid_size": "196",
// "impact_mid_price": null,
// "mark_iv": "-0.44931641"
// },
// "size": 1226303,
// "spot_price": "30612.85362773",
// "symbol": "BTCUSDT",
// "timestamp": 1689136597460456,
// "turnover": 37392218.45999999,
// "turnover_symbol": "USDT",
// "turnover_usd": 37392218.45999999,
// "volume": 1226.3029999999485
// },
// "success": true
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_funding_rate(result, &[market]);
Value::Null
}
/*
* @method
* @name delta#fetchFundingRates
* @description fetch the funding rate for multiple markets
* @see https://docs.delta.exchange/#get-tickers-for-products
* @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 [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rates-structure}, indexed by market symbols
*/
pub async fn fetch_funding_rates(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("contract_types".to_string(), Value::Str("perpetual_futures".into()));
m
});
let __ws_arg_17 = self.extend(request, &[params]);
let mut response: Value = self.public_get_tickers(&[__ws_arg_17]).await;
//
// {
// "result": [
// {
// "close": 30600.5,
// "contract_type": "perpetual_futures",
// "funding_rate": "0.00602961",
// "greeks": null,
// "high": 30803.0,
// "low": 30265.5,
// "mark_basis": "-0.45601594",
// "mark_price": "30600.10481568",
// "oi": "469.9190",
// "oi_change_usd_6h": "2226314.9900",
// "oi_contracts": "469919",
// "oi_value": "469.9190",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "14385640.6802",
// "open": 30458.5,
// "price_band": {
// "lower_limit": "29067.08312627",
// "upper_limit": "32126.77608693"
// },
// "product_id": 139,
// "quotes": {
// "ask_iv": null,
// "ask_size": "965",
// "best_ask": "30600.5",
// "best_bid": "30599.5",
// "bid_iv": null,
// "bid_size": "196",
// "impact_mid_price": null,
// "mark_iv": "-0.44931641"
// },
// "size": 1226303,
// "spot_price": "30612.85362773",
// "symbol": "BTCUSDT",
// "timestamp": 1689136597460456,
// "turnover": 37392218.45999999,
// "turnover_symbol": "USDT",
// "turnover_usd": 37392218.45999999,
// "volume": 1226.3029999999485
// },
// ],
// "success":true
// }
//
let mut rates: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
return self.parse_funding_rates(rates, &[symbolsNormalized]);
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);
//
// {
// "close": 30600.5,
// "contract_type": "perpetual_futures",
// "funding_rate": "0.00602961",
// "greeks": null,
// "high": 30803.0,
// "low": 30265.5,
// "mark_basis": "-0.45601594",
// "mark_price": "30600.10481568",
// "oi": "469.9190",
// "oi_change_usd_6h": "2226314.9900",
// "oi_contracts": "469919",
// "oi_value": "469.9190",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "14385640.6802",
// "open": 30458.5,
// "price_band": {
// "lower_limit": "29067.08312627",
// "upper_limit": "32126.77608693"
// },
// "product_id": 139,
// "quotes": {
// "ask_iv": null,
// "ask_size": "965",
// "best_ask": "30600.5",
// "best_bid": "30599.5",
// "bid_iv": null,
// "bid_size": "196",
// "impact_mid_price": null,
// "mark_iv": "-0.44931641"
// },
// "size": 1226303,
// "spot_price": "30612.85362773",
// "symbol": "BTCUSDT",
// "timestamp": 1689136597460456,
// "turnover": 37392218.45999999,
// "turnover_symbol": "USDT",
// "turnover_usd": 37392218.45999999,
// "volume": 1226.3029999999485
// }
//
let mut timestamp: Value = self.safe_integer_product_k(contract.clone(), "timestamp", Value::Float(0.001), &[]);
let mut marketId: Value = self.safe_string_k(contract.clone(), "symbol", &[]);
let mut fundingRateString: Value = self.safe_string_k(contract.clone(), "funding_rate", &[]);
let mut fundingRate: Value = crate::precise::Precise::stringDiv(&fundingRateString, &Value::Str("100".into()));
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(), self.safe_number_k(contract.clone(), "mark_price", &[]));
m.insert("indexPrice".to_string(), self.safe_number_k(contract, "spot_price", &[]));
m.insert("interestRate".to_string(), Value::Null);
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("fundingRate".to_string(), self.parse_number(fundingRate, &[]));
m.insert("fundingTimestamp".to_string(), Value::Null);
m.insert("fundingDatetime".to_string(), Value::Null);
m.insert("nextFundingRate".to_string(), Value::Null);
m.insert("nextFundingTimestamp".to_string(), Value::Null);
m.insert("nextFundingDatetime".to_string(), Value::Null);
m.insert("previousFundingRate".to_string(), Value::Null);
m.insert("previousFundingTimestamp".to_string(), Value::Null);
m.insert("previousFundingDatetime".to_string(), Value::Null);
m.insert("interval".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name delta#addMargin
* @description add margin
* @see https://docs.delta.exchange/#add-remove-position-margin
* @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
* @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
}));
return self.modify_margin_helper(symbol, amount, Value::Str("add".into()), &[params]).await;
Value::Null
}
/*
* @method
* @name delta#reduceMargin
* @description remove margin from a position
* @see https://docs.delta.exchange/#add-remove-position-margin
* @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
* @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
}));
return self.modify_margin_helper(symbol, amount, Value::Str("reduce".into()), &[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
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut amountString: Value = to_string_val(&amount);
let mut deltaMargin: Value = (if (type_var.as_str() == Some("reduce")) { crate::precise::Precise::stringMul(&amountString, &Value::Str("-1".into())) } else { amountString.clone() });
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), market.as_map().and_then(|__m| __m.get("numericId")).cloned().unwrap_or(Value::Null));
m.insert("delta_margin".to_string(), deltaMargin);
m
});
let __ws_arg_18 = self.extend(request, &[params]);
let mut response: Value = self.private_post_positions_change_margin(&[__ws_arg_18]).await;
//
// {
// "result": {
// "auto_topup": false,
// "bankruptcy_price": "24934.12",
// "commission": "0.01197072",
// "created_at": "2023-07-20T03:49:09.159401Z",
// "entry_price": "29926.8",
// "liquidation_price": "25083.754",
// "margin": "4.99268",
// "margin_mode": "isolated",
// "product_id": 84,
// "product_symbol": "BTCUSDT",
// "realized_cashflow": "0",
// "realized_funding": "0",
// "realized_pnl": "0",
// "size": 1,
// "updated_at": "2023-07-20T03:49:09.159401Z",
// "user_id": 30084879
// },
// "success": true
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_margin_modification(result, &[market]);
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);
//
// {
// "auto_topup": false,
// "bankruptcy_price": "24934.12",
// "commission": "0.01197072",
// "created_at": "2023-07-20T03:49:09.159401Z",
// "entry_price": "29926.8",
// "liquidation_price": "25083.754",
// "margin": "4.99268",
// "margin_mode": "isolated",
// "product_id": 84,
// "product_symbol": "BTCUSDT",
// "realized_cashflow": "0",
// "realized_funding": "0",
// "realized_pnl": "0",
// "size": 1,
// "updated_at": "2023-07-20T03:49:09.159401Z",
// "user_id": 30084879
// }
//
let mut marketId: Value = self.safe_string_k(data.clone(), "product_symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data.clone());
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Str("isolated".into()));
m.insert("amount".to_string(), Value::Null);
m.insert("total".to_string(), self.safe_number_k(data, "margin", &[]));
m.insert("code".to_string(), Value::Null);
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 delta#fetchOpenInterest
* @description retrieves the open interest of a derivative market
* @see https://docs.delta.exchange/#get-ticker-for-a-product-by-symbol
* @param {string} symbol unified market symbol
* @param {object} [params] exchange specific parameters
* @returns {object} an open interest structure{@link https://docs.ccxt.com/?id=open-interest-structure}
*/
pub async fn fetch_open_interest(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenInterest() supports contract markets only".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_19 = self.extend(request, &[params]);
let mut response: Value = self.public_get_tickers_symbol(&[__ws_arg_19]).await;
//
// {
// "result": {
// "close": 894.0,
// "contract_type": "call_options",
// "greeks": {
// "delta": "0.67324861",
// "gamma": "0.00022178",
// "rho": "4.34638266",
// "spot": "30178.53195697",
// "theta": "-35.64972577",
// "vega": "16.34381277"
// },
// "high": 946.0,
// "low": 893.0,
// "mark_price": "1037.07582681",
// "mark_vol": "0.35899491",
// "oi": "0.0910",
// "oi_change_usd_6h": "-90.5500",
// "oi_contracts": "91",
// "oi_value": "0.0910",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "2746.3549",
// "open": 946.0,
// "price_band": {
// "lower_limit": "133.37794509",
// "upper_limit": "5663.66930164"
// },
// "product_id": 116171,
// "quotes": {
// "ask_iv": "0.36932389",
// "ask_size": "1321",
// "best_ask": "1054",
// "best_bid": "1020",
// "bid_iv": "0.34851914",
// "bid_size": "2202",
// "impact_mid_price": null,
// "mark_iv": "0.35896335"
// },
// "size": 152,
// "spot_price": "30178.53195697",
// "strike_price": "29500",
// "symbol": "C-BTC-29500-280723",
// "timestamp": 1689834695286094,
// "turnover": 4546.601744940001,
// "turnover_symbol": "USDT",
// "turnover_usd": 4546.601744940001,
// "volume": 0.15200000000000002
// },
// "success": true
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_open_interest(result, &[market]);
Value::Null
}
pub fn parse_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "close": 894.0,
// "contract_type": "call_options",
// "greeks": {
// "delta": "0.67324861",
// "gamma": "0.00022178",
// "rho": "4.34638266",
// "spot": "30178.53195697",
// "theta": "-35.64972577",
// "vega": "16.34381277"
// },
// "high": 946.0,
// "low": 893.0,
// "mark_price": "1037.07582681",
// "mark_vol": "0.35899491",
// "oi": "0.0910",
// "oi_change_usd_6h": "-90.5500",
// "oi_contracts": "91",
// "oi_value": "0.0910",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "2746.3549",
// "open": 946.0,
// "price_band": {
// "lower_limit": "133.37794509",
// "upper_limit": "5663.66930164"
// },
// "product_id": 116171,
// "quotes": {
// "ask_iv": "0.36932389",
// "ask_size": "1321",
// "best_ask": "1054",
// "best_bid": "1020",
// "bid_iv": "0.34851914",
// "bid_size": "2202",
// "impact_mid_price": null,
// "mark_iv": "0.35896335"
// },
// "size": 152,
// "spot_price": "30178.53195697",
// "strike_price": "29500",
// "symbol": "C-BTC-29500-280723",
// "timestamp": 1689834695286094,
// "turnover": 4546.601744940001,
// "turnover_symbol": "USDT",
// "turnover_usd": 4546.601744940001,
// "volume": 0.15200000000000002
// }
//
let mut timestamp: Value = self.safe_integer_product_k(interest.clone(), "timestamp", Value::Float(0.001), &[]);
let mut marketId: Value = self.safe_string_k(interest.clone(), "symbol", &[]);
return self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market.clone()]));
m.insert("baseVolume".to_string(), self.safe_number_k(interest.clone(), "oi_value", &[]));
m.insert("quoteVolume".to_string(), self.safe_number_k(interest.clone(), "oi_value_usd", &[]));
m.insert("openInterestAmount".to_string(), self.safe_number_k(interest.clone(), "oi_contracts", &[]));
m.insert("openInterestValue".to_string(), self.safe_number_k(interest.clone(), "oi", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("info".to_string(), interest);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name delta#fetchLeverage
* @description fetch the set leverage for a market
* @see https://docs.delta.exchange/#get-order-leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [leverage structure]{@link https://docs.ccxt.com/?id=leverage-structure}
*/
pub async fn fetch_leverage(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), market.as_map().and_then(|__m| __m.get("numericId")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_20 = self.extend(request, &[params]);
let mut response: Value = self.private_get_products_product_id_orders_leverage(&[__ws_arg_20]).await;
//
// {
// "result": {
// "index_symbol": null,
// "leverage": "10",
// "margin_mode": "isolated",
// "order_margin": "0",
// "product_id": 84,
// "user_id": 30084879
// },
// "success": true
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_leverage(result, &[market]);
Value::Null
}
pub fn parse_leverage(&self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Value = self.safe_string_k(leverage.clone(), "index_symbol", &[]);
let mut leverageValue: Value = self.safe_integer_k(leverage.clone(), "leverage", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), leverage.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market]));
m.insert("marginMode".to_string(), self.safe_string_lower_k(leverage, "margin_mode", &[]));
m.insert("longLeverage".to_string(), leverageValue.clone());
m.insert("shortLeverage".to_string(), leverageValue);
m
});
Value::Null
}
/*
* @method
* @name delta#setLeverage
* @description set the level of leverage for a market
* @see https://docs.delta.exchange/#change-order-leverage
* @param {float} leverage the rate of leverage
* @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_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()))));
}
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), market.as_map().and_then(|__m| __m.get("numericId")).cloned().unwrap_or(Value::Null));
m.insert("leverage".to_string(), leverage);
m
});
let __ws_arg_21 = self.extend(request, &[params]);
return self.private_post_products_product_id_orders_leverage(&[__ws_arg_21]).await;
Value::Null
}
/*
* @method
* @name delta#fetchSettlementHistory
* @description fetches historical settlement records
* @see https://docs.delta.exchange/#get-product-settlement-prices
* @param {string} symbol unified market symbol of the settlement history
* @param {int} [since] timestamp in ms
* @param {int} [limit] number of records
* @param {object} [params] exchange specific params
* @returns {object[]} a list of [settlement history objects]{@link https://docs.ccxt.com/?id=settlement-history-structure}
*/
pub async fn fetch_settlement_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
}));
self.load_markets(&[]).await;
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("states".to_string(), Value::Str("expired".into()));
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("page_size".into(), limit.clone()); }
}
let __ws_arg_22 = self.extend(request, &[params]);
let mut response: Value = self.public_get_products(&[__ws_arg_22]).await;
//
// {
// "result": [
// {
// "contract_value": "0.001",
// "basis_factor_max_limit": "10.95",
// "maker_commission_rate": "0.0003",
// "launch_time": "2023-07-19T04:30:03Z",
// "trading_status": "operational",
// "product_specs": {
// "backup_vol_expiry_time": 31536000,
// "max_deviation_from_external_vol": 0.75,
// "max_lower_deviation_from_external_vol": 0.75,
// "max_upper_deviation_from_external_vol": 0.5,
// "max_volatility": 3,
// "min_volatility": 0.1,
// "premium_commission_rate": 0.1,
// "settlement_index_price": "29993.536675710806",
// "vol_calculation_method": "orderbook",
// "vol_expiry_time": 31536000
// },
// "description": "BTC call option expiring on 19-7-2023",
// "settlement_price": "0",
// "disruption_reason": null,
// "settling_asset": {},
// "initial_margin": "1",
// "tick_size": "0.1",
// "maintenance_margin": "0.5",
// "id": 117542,
// "notional_type": "vanilla",
// "ui_config": {},
// "contract_unit_currency": "BTC",
// "symbol": "C-BTC-30900-190723",
// "insurance_fund_margin_contribution": "1",
// "price_band": "2",
// "annualized_funding": "10.95",
// "impact_size": 200,
// "contract_type": "call_options",
// "position_size_limit": 255633,
// "max_leverage_notional": "200000",
// "initial_margin_scaling_factor": "0.000002",
// "strike_price": "30900",
// "is_quanto": false,
// "settlement_time": "2023-07-19T12:00:00Z",
// "liquidation_penalty_factor": "0.5",
// "funding_method": "mark_price",
// "taker_commission_rate": "0.0003",
// "default_leverage": "100.000000000000000000",
// "state": "expired",
// "auction_start_time": null,
// "short_description": "BTC Call",
// "quoting_asset": {},
// "maintenance_margin_scaling_factor":"0.000002"
// }
// ],
// "success": true
// }
//
let mut result: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
let mut settlements: Value = self.parse_settlements(result, market.clone());
let mut sorted: Value = self.sort_by(settlements, Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[self.safe_string_k(market, "symbol", &[]), since, limit]);
Value::Null
}
pub fn parse_settlement(&self, mut settlement: Value, mut market: Value) -> Value {
//
// {
// "contract_value": "0.001",
// "basis_factor_max_limit": "10.95",
// "maker_commission_rate": "0.0003",
// "launch_time": "2023-07-19T04:30:03Z",
// "trading_status": "operational",
// "product_specs": {
// "backup_vol_expiry_time": 31536000,
// "max_deviation_from_external_vol": 0.75,
// "max_lower_deviation_from_external_vol": 0.75,
// "max_upper_deviation_from_external_vol": 0.5,
// "max_volatility": 3,
// "min_volatility": 0.1,
// "premium_commission_rate": 0.1,
// "settlement_index_price": "29993.536675710806",
// "vol_calculation_method": "orderbook",
// "vol_expiry_time": 31536000
// },
// "description": "BTC call option expiring on 19-7-2023",
// "settlement_price": "0",
// "disruption_reason": null,
// "settling_asset": {},
// "initial_margin": "1",
// "tick_size": "0.1",
// "maintenance_margin": "0.5",
// "id": 117542,
// "notional_type": "vanilla",
// "ui_config": {},
// "contract_unit_currency": "BTC",
// "symbol": "C-BTC-30900-190723",
// "insurance_fund_margin_contribution": "1",
// "price_band": "2",
// "annualized_funding": "10.95",
// "impact_size": 200,
// "contract_type": "call_options",
// "position_size_limit": 255633,
// "max_leverage_notional": "200000",
// "initial_margin_scaling_factor": "0.000002",
// "strike_price": "30900",
// "is_quanto": false,
// "settlement_time": "2023-07-19T12:00:00Z",
// "liquidation_penalty_factor": "0.5",
// "funding_method": "mark_price",
// "taker_commission_rate": "0.0003",
// "default_leverage": "100.000000000000000000",
// "state": "expired",
// "auction_start_time": null,
// "short_description": "BTC Call",
// "quoting_asset": {},
// "maintenance_margin_scaling_factor":"0.000002"
// }
//
let mut datetime: Value = self.safe_string_k(settlement.clone(), "settlement_time", &[]);
let mut marketId: Value = self.safe_string_k(settlement.clone(), "symbol", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), settlement.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market]));
m.insert("price".to_string(), self.safe_number_k(settlement, "settlement_price", &[]));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime);
m
});
Value::Null
}
pub fn parse_settlements(&self, mut settlements: Value, mut market: Value) -> Value {
let mut result: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_615: bool = true;
while { if !__for_first_615 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_615 = false; i.as_f64().unwrap_or(f64::NAN) < ((settlements.len() as i64) as f64) } {
result.push(self.parse_settlement(settlements.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 Value::from(result);
Value::Null
}
/*
* @method
* @name delta#fetchGreeks
* @description fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract
* @see https://docs.delta.exchange/#get-ticker-for-a-product-by-symbol
* @param {string} symbol unified symbol of the market to fetch greeks for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [greeks structure]{@link https://docs.ccxt.com/?id=greeks-structure}
*/
pub async fn fetch_greeks(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_23 = self.extend(request, &[params]);
let mut response: Value = self.public_get_tickers_symbol(&[__ws_arg_23]).await;
//
// {
// "result": {
// "close": 6793.0,
// "contract_type": "call_options",
// "greeks": {
// "delta": "0.94739174",
// "gamma": "0.00002206",
// "rho": "11.00890725",
// "spot": "36839.58124652",
// "theta": "-18.18365310",
// "vega": "7.85209698"
// },
// "high": 7556.0,
// "low": 6793.0,
// "mark_price": "6955.70698909",
// "mark_vol": "0.66916863",
// "oi": "1.8980",
// "oi_change_usd_6h": "110.4600",
// "oi_contracts": "1898",
// "oi_value": "1.8980",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "69940.7319",
// "open": 7.2e3,
// "price_band": {
// "lower_limit": "5533.89814767",
// "upper_limit": "11691.37688371"
// },
// "product_id": 129508,
// "quotes": {
// "ask_iv": "0.90180438",
// "ask_size": "1898",
// "best_ask": "7210",
// "best_bid": "6913",
// "bid_iv": "0.60881706",
// "bid_size": "3163",
// "impact_mid_price": null,
// "mark_iv": "0.66973549"
// },
// "size": 5,
// "spot_price": "36839.58153868",
// "strike_price": "30000",
// "symbol": "C-BTC-30000-241123",
// "timestamp": 1699584998504530,
// "turnover": 184.41206804,
// "turnover_symbol": "USDT",
// "turnover_usd": 184.41206804,
// "volume": 0.005
// },
// "success": true
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_greeks(result, &[market]);
Value::Null
}
pub fn parse_greeks(&self, mut greeks: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "close": 6793.0,
// "contract_type": "call_options",
// "greeks": {
// "delta": "0.94739174",
// "gamma": "0.00002206",
// "rho": "11.00890725",
// "spot": "36839.58124652",
// "theta": "-18.18365310",
// "vega": "7.85209698"
// },
// "high": 7556.0,
// "low": 6793.0,
// "mark_price": "6955.70698909",
// "mark_vol": "0.66916863",
// "oi": "1.8980",
// "oi_change_usd_6h": "110.4600",
// "oi_contracts": "1898",
// "oi_value": "1.8980",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "69940.7319",
// "open": 7.2e3,
// "price_band": {
// "lower_limit": "5533.89814767",
// "upper_limit": "11691.37688371"
// },
// "product_id": 129508,
// "quotes": {
// "ask_iv": "0.90180438",
// "ask_size": "1898",
// "best_ask": "7210",
// "best_bid": "6913",
// "bid_iv": "0.60881706",
// "bid_size": "3163",
// "impact_mid_price": null,
// "mark_iv": "0.66973549"
// },
// "size": 5,
// "spot_price": "36839.58153868",
// "strike_price": "30000",
// "symbol": "C-BTC-30000-241123",
// "timestamp": 1699584998504530,
// "turnover": 184.41206804,
// "turnover_symbol": "USDT",
// "turnover_usd": 184.41206804,
// "volume": 0.005
// }
//
let mut timestamp: Value = self.safe_integer_product_k(greeks.clone(), "timestamp", Value::Float(0.001), &[]);
let mut marketId: Value = self.safe_string_k(greeks.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market]);
let mut stats: Value = self.safe_dict_k(greeks.clone(), "greeks", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut quotes: Value = self.safe_dict_k(greeks.clone(), "quotes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return 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("delta".to_string(), self.safe_number_k(stats.clone(), "delta", &[]));
m.insert("gamma".to_string(), self.safe_number_k(stats.clone(), "gamma", &[]));
m.insert("theta".to_string(), self.safe_number_k(stats.clone(), "theta", &[]));
m.insert("vega".to_string(), self.safe_number_k(stats.clone(), "vega", &[]));
m.insert("rho".to_string(), self.safe_number_k(stats, "rho", &[]));
m.insert("bidSize".to_string(), self.safe_number_k(quotes.clone(), "bid_size", &[]));
m.insert("askSize".to_string(), self.safe_number_k(quotes.clone(), "ask_size", &[]));
m.insert("bidImpliedVolatility".to_string(), self.safe_number_k(quotes.clone(), "bid_iv", &[]));
m.insert("askImpliedVolatility".to_string(), self.safe_number_k(quotes.clone(), "ask_iv", &[]));
m.insert("markImpliedVolatility".to_string(), self.safe_number_k(quotes.clone(), "mark_iv", &[]));
m.insert("bidPrice".to_string(), self.safe_number_k(quotes.clone(), "best_bid", &[]));
m.insert("askPrice".to_string(), self.safe_number_k(quotes, "best_ask", &[]));
m.insert("markPrice".to_string(), self.safe_number_k(greeks.clone(), "mark_price", &[]));
m.insert("lastPrice".to_string(), self.safe_number_k(greeks.clone(), "last_price", &[]));
m.insert("underlyingPrice".to_string(), self.safe_number_k(greeks.clone(), "spot_price", &[]));
m.insert("info".to_string(), greeks);
m
});
Value::Null
}
/*
* @method
* @name delta#closeAllPositions
* @description closes all open positions for a market type
* @see https://docs.delta.exchange/#close-all-positions
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.user_id] the users id
* @returns {object[]} A list of [position structures]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn close_all_positions(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("close_all_portfolio".to_string(), Value::Bool(true));
m.insert("close_all_isolated".to_string(), Value::Bool(true));
m
});
let __ws_arg_24 = self.extend(request, &[params]);
let mut response: Value = self.private_post_positions_close_all(&[__ws_arg_24]).await;
//
// {"result":{},"success":true}
//
let mut position: Value = self.parse_position(self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), &[]);
return Value::from(vec![position]);
Value::Null
}
/*
* @method
* @name delta#fetchMarginMode
* @description fetches the margin mode of a trading pair
* @see https://docs.delta.exchange/#get-user
* @param {string} symbol unified symbol of the market to fetch the margin mode for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [margin mode structure]{@link https://docs.ccxt.com/?id=margin-mode-structure}
*/
pub async fn fetch_margin_mode(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut response: Value = self.private_get_profile(&[params]).await;
//
// {
// "result": {
// "is_password_set": true,
// "kyc_expiry_date": null,
// "phishing_code": "12345",
// "preferences": {
// "favorites": []
// },
// "is_kyc_provisioned": false,
// "country": "Canada",
// "margin_mode": "isolated",
// "mfa_updated_at": "2023-07-19T01:04:43Z",
// "last_name": "",
// "oauth_apple_active": false,
// "pf_index_symbol": null,
// "proof_of_identity_status": "approved",
// "dob": null,
// "email": "abc_123@gmail.com",
// "force_change_password": false,
// "nick_name": "still-breeze-123",
// "oauth_google_active": false,
// "phone_verification_status": "verified",
// "id": 12345678,
// "last_seen": null,
// "is_withdrawal_enabled": true,
// "force_change_mfa": false,
// "enable_bots": false,
// "kyc_verified_on": null,
// "created_at": "2023-07-19T01:02:32Z",
// "withdrawal_blocked_till": null,
// "proof_of_address_status": "approved",
// "is_password_change_blocked": false,
// "is_mfa_enabled": true,
// "is_kyc_done": true,
// "oauth": null,
// "account_name": "Main",
// "sub_account_permissions": null,
// "phone_number": null,
// "tracking_info": {
// "ga_cid": "1234.4321",
// "is_kyc_gtm_tracked": true,
// "sub_account_config": {
// "cross": 2,
// "isolated": 2,
// "portfolio": 2
// }
// },
// "first_name": "",
// "phone_verified_on": null,
// "seen_intro": false,
// "password_updated_at": null,
// "is_login_enabled": true,
// "registration_date": "2023-07-19T01:02:32Z",
// "permissions": {},
// "max_sub_accounts_limit": 2,
// "country_calling_code": null,
// "is_sub_account": false,
// "is_kyc_refresh_required": false
// },
// "success": true
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_margin_mode(result, &[market]);
Value::Null
}
pub fn parse_margin_mode(&self, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut symbol: Value = Value::Null;
if (market != Value::Null) {
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), marginMode.clone());
m.insert("symbol".to_string(), symbol);
m.insert("marginMode".to_string(), self.safe_string_k(marginMode, "margin_mode", &[]));
m
});
Value::Null
}
/*
* @method
* @name delta#setMarginMode
* @description set margin mode to 'isolated' or 'portfolio'
* @see https://docs.delta.exchange/#change-margin-mode
* @param {string} marginMode 'isolated' or 'portfolio'
* @param {string} [symbol] not used by delta.setMarginMode
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} params.subaccount_user_id the user id of the subaccount
* @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
}));
self.check_required_argument(Value::Str("setMarginMode".into()), marginMode.clone(), Value::Str("marginMode".into()), &[Value::from(vec![Value::Str("isolated".into()), Value::Str("portfolio".into())])]);
let mut subaccountUserId: Value = self.safe_string_k(params.clone(), "subaccount_user_id", &[]);
self.check_required_argument(Value::Str("setMarginMode".into()), subaccountUserId, Value::Str("params[\"subaccount_user_id\"]".into()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("margin_mode".to_string(), marginMode);
m
});
let __ws_arg_25 = self.extend(request, &[params]);
return self.private_put_users_margin_mode(&[__ws_arg_25]).await;
Value::Null
}
/*
* @method
* @name delta#fetchOption
* @description fetches option data that is commonly found in an option chain
* @see https://docs.delta.exchange/#get-ticker-for-a-product-by-symbol
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [option chain structure]{@link https://docs.ccxt.com/?id=option-chain-structure}
*/
pub async fn fetch_option(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_26 = self.extend(request, &[params]);
let mut response: Value = self.public_get_tickers_symbol(&[__ws_arg_26]).await;
//
// {
// "result": {
// "close": 6793.0,
// "contract_type": "call_options",
// "greeks": {
// "delta": "0.94739174",
// "gamma": "0.00002206",
// "rho": "11.00890725",
// "spot": "36839.58124652",
// "theta": "-18.18365310",
// "vega": "7.85209698"
// },
// "high": 7556.0,
// "low": 6793.0,
// "mark_price": "6955.70698909",
// "mark_vol": "0.66916863",
// "oi": "1.8980",
// "oi_change_usd_6h": "110.4600",
// "oi_contracts": "1898",
// "oi_value": "1.8980",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "69940.7319",
// "open": 7.2e3,
// "price_band": {
// "lower_limit": "5533.89814767",
// "upper_limit": "11691.37688371"
// },
// "product_id": 129508,
// "quotes": {
// "ask_iv": "0.90180438",
// "ask_size": "1898",
// "best_ask": "7210",
// "best_bid": "6913",
// "bid_iv": "0.60881706",
// "bid_size": "3163",
// "impact_mid_price": null,
// "mark_iv": "0.66973549"
// },
// "size": 5,
// "spot_price": "36839.58153868",
// "strike_price": "30000",
// "symbol": "C-BTC-30000-241123",
// "timestamp": 1699584998504530,
// "turnover": 184.41206804,
// "turnover_symbol": "USDT",
// "turnover_usd": 184.41206804,
// "volume": 0.005
// },
// "success": true
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_option(result, &[Value::Null, market]);
Value::Null
}
pub fn parse_option(&self, mut chain: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
let mut market = get_arg(optional_args, 1, Value::Null);
//
// {
// "close": 6793.0,
// "contract_type": "call_options",
// "greeks": {
// "delta": "0.94739174",
// "gamma": "0.00002206",
// "rho": "11.00890725",
// "spot": "36839.58124652",
// "theta": "-18.18365310",
// "vega": "7.85209698"
// },
// "high": 7556.0,
// "low": 6793.0,
// "mark_price": "6955.70698909",
// "mark_vol": "0.66916863",
// "oi": "1.8980",
// "oi_change_usd_6h": "110.4600",
// "oi_contracts": "1898",
// "oi_value": "1.8980",
// "oi_value_symbol": "BTC",
// "oi_value_usd": "69940.7319",
// "open": 7.2e3,
// "price_band": {
// "lower_limit": "5533.89814767",
// "upper_limit": "11691.37688371"
// },
// "product_id": 129508,
// "quotes": {
// "ask_iv": "0.90180438",
// "ask_size": "1898",
// "best_ask": "7210",
// "best_bid": "6913",
// "bid_iv": "0.60881706",
// "bid_size": "3163",
// "impact_mid_price": null,
// "mark_iv": "0.66973549"
// },
// "size": 5,
// "spot_price": "36839.58153868",
// "strike_price": "30000",
// "symbol": "C-BTC-30000-241123",
// "timestamp": 1699584998504530,
// "turnover": 184.41206804,
// "turnover_symbol": "USDT",
// "turnover_usd": 184.41206804,
// "volume": 0.005
// }
//
let mut marketId: Value = self.safe_string_k(chain.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut quotes: Value = self.safe_dict_k(chain.clone(), "quotes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.safe_integer_product_k(chain.clone(), "timestamp", Value::Float(0.001), &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), chain.clone());
m.insert("currency".to_string(), self.safe_string_k(chain.clone(), "currency", &[]));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("impliedVolatility".to_string(), self.safe_number_k(quotes.clone(), "mark_iv", &[]));
m.insert("openInterest".to_string(), self.safe_number_k(chain.clone(), "oi", &[]));
m.insert("bidPrice".to_string(), self.safe_number_k(quotes.clone(), "best_bid", &[]));
m.insert("askPrice".to_string(), self.safe_number_k(quotes.clone(), "best_ask", &[]));
m.insert("midPrice".to_string(), self.safe_number_k(quotes, "impact_mid_price", &[]));
m.insert("markPrice".to_string(), self.safe_number_k(chain.clone(), "mark_price", &[]));
m.insert("lastPrice".to_string(), self.safe_number_k(chain.clone(), "last_price", &[]));
m.insert("underlyingPrice".to_string(), self.safe_number_k(chain.clone(), "spot_price", &[]));
m.insert("change".to_string(), self.safe_number_k(chain.clone(), "change", &[]));
m.insert("percentage".to_string(), self.safe_number_k(chain.clone(), "percentage", &[]));
m.insert("baseVolume".to_string(), self.safe_number_k(chain.clone(), "volume", &[]));
m.insert("quoteVolume".to_string(), self.safe_number_k(chain, "quote_volume", &[]));
m
});
Value::Null
}
/*
* @method
* @name delta#fetchPositionsADLRank
* @description fetches the auto deleveraging rank and risk percentage for a list of symbols
* @see https://docs.delta.exchange/#get-margined-positions
* @param {string[]} [symbols] a list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of [auto de leverage structures]{@link https://docs.ccxt.com/?id=auto-de-leverage-structure}
*/
pub async fn fetch_positions_adl_rank(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(true), Value::Bool(true), Value::Bool(true)]);
let mut response: Value = self.private_get_positions_margined(&[params]).await;
//
// {
// "result":
// [
// {
// "adl_level": null,
// "auto_topup": false,
// "bankruptcy_price": "88618.22667",
// "commission": "0.03797924",
// "created_at": "2026-01-14T11:24:35.801586Z",
// "entry_price": "94948.1",
// "liquidation_price": "89092.96717",
// "margin": "6.32987333",
// "margin_mode": "isolated",
// "mark_price": "94942.90888022",
// "product": {
// "trading_status": "operational",
// "short_description": null,
// "quoting_asset": {
// "base_withdrawal_fee": "0.000000000000000000",
// "id": 4,
// "interest_credit": false,
// "interest_slabs": null,
// "kyc_deposit_limit": "0.000000000000000000",
// "kyc_withdrawal_limit": "0.000000000000000000",
// "min_withdrawal_amount": "0.000000000000000000",
// "minimum_precision": 2,
// "name": "Tether",
// "networks": [],
// "precision": 8,
// "sort_priority": null,
// "symbol": "USDT",
// "variable_withdrawal_fee": "0.000000000000000000"
// },
// "symbol": "BTCUSDT",
// "taker_commission_rate": "0.0004",
// "maintenance_margin_scaling_factor": "0",
// "spot_index": {
// "config": {
// "impact_size": {
// "max_impact_size": 150000,
// "min_impact_size": 5000,
// "step_value": 5000
// },
// "quoting_asset": "USDT",
// "service_id": 1,
// "underlying_asset": "BTC"
// },
// "constituent_exchanges": [
// {
// "exchange": "binance",
// "health_interval": 3000,
// "health_priority": 1,
// "weight": 1
// },
// {
// "exchange": "gateio",
// "health_interval": 3000,
// "health_priority": 3,
// "weight": 1
// },
// {
// "exchange": "bybit",
// "health_interval": 3000,
// "health_priority": 2,
// "weight": 1
// }
// ],
// "constituent_indices": null,
// "description": "BTC Spot",
// "health_interval": 300,
// "id": 2,
// "impact_size": "1.000000000000000000",
// "index_type": "spot_pair",
// "is_composite": false,
// "price_method": "ltp",
// "quoting_asset_id": 4,
// "symbol": ".DEXBTUSDT",
// "tick_size": "0.100000000000000000",
// "underlying_asset_id": 2
// },
// "liquidation_penalty_factor": "1",
// "auction_start_time": "2025-12-22T12:18:52Z",
// "is_quanto": false,
// "state": "live",
// "id": 84,
// "settling_asset": {
// "base_withdrawal_fee": "0.000000000000000000",
// "id": 4,
// "interest_credit": false,
// "interest_slabs": null,
// "kyc_deposit_limit": "0.000000000000000000",
// "kyc_withdrawal_limit": "0.000000000000000000",
// "min_withdrawal_amount": "0.000000000000000000",
// "minimum_precision": 2,
// "name": "Tether",
// "networks": [],
// "precision": 8,
// "sort_priority": null,
// "symbol": "USDT",
// "variable_withdrawal_fee": "0.000000000000000000"
// },
// "tick_size": "0.1",
// "impact_size": 4000,
// "insurance_fund_margin_contribution": "5",
// "maker_commission_rate": "0.0002",
// "ui_config": {
// "default_trading_view_candle": "15",
// "leverage_slider_values": [1,2,3,5,10,50,100],
// "price_clubbing_values": [0.1,1,10,50],
// "show_bracket_orders": false,
// "sort_priority": 1
// },
// "annualized_funding": "0",
// "strike_price": null,
// "price_band": "100",
// "funding_method": "mark_price",
// "contract_value": "0.001",
// "auction_finish_time": null,
// "product_specs": {
// "vol_expiry_time": 172800
// },
// "launch_time": "2020-04-20T08:37:05Z",
// "basis_factor_max_limit": "1000",
// "initial_margin": "1",
// "notional_type": "vanilla",
// "contract_unit_currency": "BTC",
// "disruption_reason": null,
// "underlying_asset": {
// "base_withdrawal_fee": "0.000000000000000000",
// "id": 2,
// "interest_credit": false,
// "interest_slabs": null,
// "kyc_deposit_limit": "0.000000000000000000",
// "kyc_withdrawal_limit": "0.000000000000000000",
// "min_withdrawal_amount": "0.000000000000000000",
// "minimum_precision": 4,
// "name": "Bitcoin",
// "networks": [],
// "precision": 8,
// "sort_priority": 1,
// "symbol": "BTC",
// "variable_withdrawal_fee": "0.000000000000000000"
// },
// "initial_margin_scaling_factor": "0",
// "position_size_limit": 10000000,
// "max_leverage_notional": "10000",
// "settlement_price": null,
// "barrier_price": null,
// "maintenance_margin": "0.5",
// "default_leverage": "50.000000000000000000",
// "settlement_time": null,
// "description": "BTCUSDT-Bitcoin Perpetual futures, quoted,settled & margined in Tether(USDT)",
// "contract_type": "perpetual_futures"
// },
// "product_id": 84,
// "product_symbol": "BTCUSDT",
// "realized_cashflow": "0.000000000000000000",
// "realized_funding": "0",
// "realized_holding_cost": "0",
// "realized_pnl": "0",
// "size": 1,
// "unrealized_pnl": "-0.00519112",
// "updated_at": "2026-01-14T11:24:35.801586Z",
// "user_id": 30084879
// }
// ],
// "success": true
// }
//
let mut result: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
return self.parse_adl_ranks(result, &[symbolsNormalized]);
Value::Null
}
pub fn parse_adl_rank(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchPositionsADLRank
//
// {
// "adl_level": null,
// "auto_topup": false,
// "bankruptcy_price": "88618.22667",
// "commission": "0.03797924",
// "created_at": "2026-01-14T11:24:35.801586Z",
// "entry_price": "94948.1",
// "liquidation_price": "89092.96717",
// "margin": "6.32987333",
// "margin_mode": "isolated",
// "mark_price": "94942.90888022",
// "product": {
// "trading_status": "operational",
// "short_description": null,
// "quoting_asset": {
// "base_withdrawal_fee": "0.000000000000000000",
// "id": 4,
// "interest_credit": false,
// "interest_slabs": null,
// "kyc_deposit_limit": "0.000000000000000000",
// "kyc_withdrawal_limit": "0.000000000000000000",
// "min_withdrawal_amount": "0.000000000000000000",
// "minimum_precision": 2,
// "name": "Tether",
// "networks": [],
// "precision": 8,
// "sort_priority": null,
// "symbol": "USDT",
// "variable_withdrawal_fee": "0.000000000000000000"
// },
// "symbol": "BTCUSDT",
// "taker_commission_rate": "0.0004",
// "maintenance_margin_scaling_factor": "0",
// "spot_index": {
// "config": {
// "impact_size": {
// "max_impact_size": 150000,
// "min_impact_size": 5000,
// "step_value": 5000
// },
// "quoting_asset": "USDT",
// "service_id": 1,
// "underlying_asset": "BTC"
// },
// "constituent_exchanges": [
// {
// "exchange": "binance",
// "health_interval": 3000,
// "health_priority": 1,
// "weight": 1
// },
// {
// "exchange": "gateio",
// "health_interval": 3000,
// "health_priority": 3,
// "weight": 1
// },
// {
// "exchange": "bybit",
// "health_interval": 3000,
// "health_priority": 2,
// "weight": 1
// }
// ],
// "constituent_indices": null,
// "description": "BTC Spot",
// "health_interval": 300,
// "id": 2,
// "impact_size": "1.000000000000000000",
// "index_type": "spot_pair",
// "is_composite": false,
// "price_method": "ltp",
// "quoting_asset_id": 4,
// "symbol": ".DEXBTUSDT",
// "tick_size": "0.100000000000000000",
// "underlying_asset_id": 2
// },
// "liquidation_penalty_factor": "1",
// "auction_start_time": "2025-12-22T12:18:52Z",
// "is_quanto": false,
// "state": "live",
// "id": 84,
// "settling_asset": {
// "base_withdrawal_fee": "0.000000000000000000",
// "id": 4,
// "interest_credit": false,
// "interest_slabs": null,
// "kyc_deposit_limit": "0.000000000000000000",
// "kyc_withdrawal_limit": "0.000000000000000000",
// "min_withdrawal_amount": "0.000000000000000000",
// "minimum_precision": 2,
// "name": "Tether",
// "networks": [],
// "precision": 8,
// "sort_priority": null,
// "symbol": "USDT",
// "variable_withdrawal_fee": "0.000000000000000000"
// },
// "tick_size": "0.1",
// "impact_size": 4000,
// "insurance_fund_margin_contribution": "5",
// "maker_commission_rate": "0.0002",
// "ui_config": {
// "default_trading_view_candle": "15",
// "leverage_slider_values": [1,2,3,5,10,50,100],
// "price_clubbing_values": [0.1,1,10,50],
// "show_bracket_orders": false,
// "sort_priority": 1
// },
// "annualized_funding": "0",
// "strike_price": null,
// "price_band": "100",
// "funding_method": "mark_price",
// "contract_value": "0.001",
// "auction_finish_time": null,
// "product_specs": {
// "vol_expiry_time": 172800
// },
// "launch_time": "2020-04-20T08:37:05Z",
// "basis_factor_max_limit": "1000",
// "initial_margin": "1",
// "notional_type": "vanilla",
// "contract_unit_currency": "BTC",
// "disruption_reason": null,
// "underlying_asset": {
// "base_withdrawal_fee": "0.000000000000000000",
// "id": 2,
// "interest_credit": false,
// "interest_slabs": null,
// "kyc_deposit_limit": "0.000000000000000000",
// "kyc_withdrawal_limit": "0.000000000000000000",
// "min_withdrawal_amount": "0.000000000000000000",
// "minimum_precision": 4,
// "name": "Bitcoin",
// "networks": [],
// "precision": 8,
// "sort_priority": 1,
// "symbol": "BTC",
// "variable_withdrawal_fee": "0.000000000000000000"
// },
// "initial_margin_scaling_factor": "0",
// "position_size_limit": 10000000,
// "max_leverage_notional": "10000",
// "settlement_price": null,
// "barrier_price": null,
// "maintenance_margin": "0.5",
// "default_leverage": "50.000000000000000000",
// "settlement_time": null,
// "description": "BTCUSDT-Bitcoin Perpetual futures, quoted,settled & margined in Tether(USDT)",
// "contract_type": "perpetual_futures"
// },
// "product_id": 84,
// "product_symbol": "BTCUSDT",
// "realized_cashflow": "0.000000000000000000",
// "realized_funding": "0",
// "realized_holding_cost": "0",
// "realized_pnl": "0",
// "size": 1,
// "unrealized_pnl": "-0.00519112",
// "updated_at": "2026-01-14T11:24:35.801586Z",
// "user_id": 30084879
// }
//
let mut marketId: Value = self.safe_string_k(info.clone(), "product_symbol", &[]);
let mut datetime: Value = self.safe_string_k(info.clone(), "created_at", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), info.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market, Value::Null, Value::Str("contract".into())]));
m.insert("rank".to_string(), self.safe_integer_k(info, "adl_level", &[]));
m.insert("rating".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime);
m
});
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("public".into())]));
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 __api_empty = Vec::new();
let api = api.as_array().unwrap_or(&__api_empty);
let mut apiName: Value = api.get(0).cloned().unwrap_or(Value::Null);
let mut requestPath: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("/".into()), self.version.clone()).into()), Value::Str("/".into())).into()), self.implode_params(path.clone(), params.clone())).into());
let mut apiUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), apiName.clone(), &[]);
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, requestPath).into());
let mut query: Value = self.omit(params, self.extract_params(path), &[]);
let mut requestBody: Value = Value::Null;
let mut requestHeaders: Value = Value::Null;
if (apiName.as_str() == Some("public")) {
if ((Value::Array(query.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).len() as i64) as f64) > ((0i64) as f64) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into())).into());
}
} else if (apiName.as_str() == Some("private")) {
self.check_required_credentials(&[]);
let mut timestamp: Value = Value::Str(format!("{}", self.seconds()).into());
requestHeaders = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api-key".to_string(), self.apiKey.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m
});
let mut auth: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", method, timestamp).into()), requestPath).into());
if (method.as_str() == Some("GET")) {
if ((Value::Array(query.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).len() as i64) as f64) > ((0i64) as f64) {
let mut queryString: Value = Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into());
auth = Value::Str(format!("{}{}", auth, queryString).into());
url = Value::Str(format!("{}{}", url, queryString).into());
}
} else {
requestBody = json_stringify(&query);
auth = Value::Str(format!("{}{}", auth, requestBody).into());
if let Value::Dict(__d) = &mut requestHeaders { std::sync::Arc::make_mut(__d).insert("Content-Type".into(), Value::Str("application/json".into())); }
}
let mut signature: Value = self.hmac(self.encode(auth), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[]);
if let Value::Dict(__d) = &mut requestHeaders { std::sync::Arc::make_mut(__d).insert("signature".into(), signature); }
}
let mut bodyResult: Value = requestBody;
let mut headersResult: Value = requestHeaders;
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), bodyResult);
m.insert("headers".to_string(), headersResult);
m
});
Value::Null
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) {
return Value::Null;
}
//
// {"error":{"code":"insufficient_margin","context":{"available_balance":"0.000000000000000000","required_additional_balance":"1.618626000000000000000000000"}},"success":false}
//
let mut error: Value = self.safe_dict_k(response, "error", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut errorCode: Value = self.safe_string_k(error, "code", &[]);
if (errorCode != Value::Null) {
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorCode.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errorCode, feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
}