// 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 BydfiCore {
pub exchange: crate::exchange::Exchange,
}
impl BydfiCore {
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 = BydfiCore::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 BydfiCore {
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::parse_order(self, order, &[market])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::parse_funding_rate(self, rate, &[market])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::parse_transfer(self, transfer, &[currency])
}
fn parse_funding_rate_history(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::parse_funding_rate_history(self, entry, &[market])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::parse_transaction(self, transaction, &[currency])
}
fn parse_margin_mode(&self, margin_mode: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::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 BydfiCore.
BydfiCore::parse_leverage(self, leverage, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on BydfiCore.
BydfiCore::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 BydfiCore.
BydfiCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for BydfiCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"create_edit_order_request" => self.create_edit_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_order_request" => self.create_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"edit_orders" => self.edit_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_canceled_and_closed_orders" => self.fetch_canceled_and_closed_orders(&args[..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_funding_rate" => self.fetch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&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_order" => self.fetch_open_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_position_history" => self.fetch_position_history(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_position_mode" => self.fetch_position_mode(&args[..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_positions_for_symbol" => self.fetch_positions_for_symbol(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions_history" => self.fetch_positions_history(&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_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_transactions_helper" => self.fetch_transactions_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.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_transfers" => self.fetch_transfers(&args[..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"get_closest_limit" => self.get_closest_limit(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"handle_since_and_until" => self.handle_since_and_until(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_funding_rate" => self.parse_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_funding_rate_history" => self.parse_funding_rate_history(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_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"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,
"set_position_mode" => self.set_position_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"transfer" => self.transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for BydfiCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for BydfiCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl BydfiCore {
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("bydfi".into()));
m.insert("name".to_string(), Value::Str("BYDFi".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("SG".into())]));
m.insert("rateLimit".to_string(), Value::Int(50));
m.insert("version".to_string(), Value::Str("v1".into()));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(false));
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(false));
m.insert("addMargin".to_string(), Value::Bool(false));
m.insert("borrowCrossMargin".to_string(), Value::Bool(false));
m.insert("borrowIsolatedMargin".to_string(), Value::Bool(false));
m.insert("borrowMargin".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(false));
m.insert("cancelOrders".to_string(), Value::Bool(false));
m.insert("cancelOrdersWithClientOrderId".to_string(), Value::Bool(false));
m.insert("cancelOrderWithClientOrderId".to_string(), Value::Bool(false));
m.insert("closeAllPositions".to_string(), Value::Bool(false));
m.insert("closePosition".to_string(), Value::Bool(false));
m.insert("createDepositAddress".to_string(), Value::Bool(false));
m.insert("createLimitBuyOrder".to_string(), Value::Bool(false));
m.insert("createLimitOrder".to_string(), Value::Bool(true));
m.insert("createLimitSellOrder".to_string(), Value::Bool(false));
m.insert("createMarketBuyOrder".to_string(), Value::Bool(false));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketOrder".to_string(), Value::Bool(true));
m.insert("createMarketOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketSellOrder".to_string(), Value::Bool(false));
m.insert("createMarketSellOrderWithCost".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(true));
m.insert("createOrderWithTakeProfitAndStopLoss".to_string(), Value::Bool(false));
m.insert("createPostOnlyOrder".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("createStopLimitOrder".to_string(), Value::Bool(true));
m.insert("createStopLossOrder".to_string(), Value::Bool(true));
m.insert("createStopMarketOrder".to_string(), Value::Bool(false));
m.insert("createStopOrder".to_string(), Value::Bool(false));
m.insert("createTakeProfitOrder".to_string(), Value::Bool(true));
m.insert("createTrailingAmountOrder".to_string(), Value::Bool(false));
m.insert("createTrailingPercentOrder".to_string(), Value::Bool(true));
m.insert("createTriggerOrder".to_string(), Value::Bool(false));
m.insert("deposit".to_string(), Value::Bool(false));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("editOrders".to_string(), Value::Bool(true));
m.insert("editOrderWithClientOrderId".to_string(), Value::Bool(true));
m.insert("fetchAccounts".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBidsAsks".to_string(), Value::Bool(false));
m.insert("fetchBorrowInterest".to_string(), Value::Bool(false));
m.insert("fetchBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(false));
m.insert("fetchBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchBorrowRatesPerSymbol".to_string(), Value::Bool(false));
m.insert("fetchCanceledAndClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(false));
m.insert("fetchClosedOrder".to_string(), Value::Bool(false));
m.insert("fetchClosedOrders".to_string(), Value::Bool(false));
m.insert("fetchConvertCurrencies".to_string(), Value::Bool(false));
m.insert("fetchConvertQuote".to_string(), Value::Bool(false));
m.insert("fetchConvertTrade".to_string(), Value::Bool(false));
m.insert("fetchConvertTradeHistory".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(false));
m.insert("fetchDeposit".to_string(), Value::Bool(false));
m.insert("fetchDepositAddress".to_string(), Value::Bool(false));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDepositAddressesByNetwork".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchDepositsWithdrawals".to_string(), Value::Bool(false));
m.insert("fetchDepositWithdrawFee".to_string(), Value::Bool(false));
m.insert("fetchDepositWithdrawFees".to_string(), Value::Bool(false));
m.insert("fetchFundingHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingInterval".to_string(), Value::Bool(false));
m.insert("fetchFundingIntervals".to_string(), Value::Bool(false));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(false));
m.insert("fetchGreeks".to_string(), Value::Bool(false));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchIsolatedPositions".to_string(), Value::Bool(false));
m.insert("fetchL2OrderBook".to_string(), Value::Bool(true));
m.insert("fetchL3OrderBook".to_string(), Value::Bool(false));
m.insert("fetchLastPrices".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(false));
m.insert("fetchLedgerEntry".to_string(), Value::Bool(false));
m.insert("fetchLeverage".to_string(), Value::Bool(true));
m.insert("fetchLeverages".to_string(), Value::Bool(false));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchLiquidations".to_string(), Value::Bool(false));
m.insert("fetchLongShortRatio".to_string(), Value::Bool(false));
m.insert("fetchLongShortRatioHistory".to_string(), Value::Bool(false));
m.insert("fetchMarginAdjustmentHistory".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(false));
m.insert("fetchMarkPrices".to_string(), Value::Bool(false));
m.insert("fetchMyLiquidations".to_string(), Value::Bool(false));
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(false));
m.insert("fetchOpenInterestHistory".to_string(), Value::Bool(false));
m.insert("fetchOpenInterests".to_string(), Value::Bool(false));
m.insert("fetchOpenOrder".to_string(), Value::Bool(true));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOption".to_string(), Value::Bool(false));
m.insert("fetchOptionChain".to_string(), Value::Bool(false));
m.insert("fetchOrder".to_string(), Value::Bool(false));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrderBooks".to_string(), Value::Bool(false));
m.insert("fetchOrders".to_string(), Value::Bool(false));
m.insert("fetchOrdersByStatus".to_string(), Value::Bool(false));
m.insert("fetchOrderTrades".to_string(), Value::Bool(false));
m.insert("fetchOrderWithClientOrderId".to_string(), Value::Bool(false));
m.insert("fetchPosition".to_string(), Value::Bool(false));
m.insert("fetchPositionHistory".to_string(), Value::Bool(true));
m.insert("fetchPositionMode".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsForSymbol".to_string(), Value::Bool(true));
m.insert("fetchPositionsHistory".to_string(), Value::Bool(true));
m.insert("fetchPositionsRisk".to_string(), Value::Bool(false));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchSettlementHistory".to_string(), Value::Bool(false));
m.insert("fetchStatus".to_string(), Value::Bool(false));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTime".to_string(), Value::Bool(false));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(false));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchTradingLimits".to_string(), Value::Bool(false));
m.insert("fetchTransactionFee".to_string(), Value::Bool(false));
m.insert("fetchTransactionFees".to_string(), Value::Bool(false));
m.insert("fetchTransactions".to_string(), Value::Bool(false));
m.insert("fetchTransfer".to_string(), Value::Bool(false));
m.insert("fetchTransfers".to_string(), Value::Bool(true));
m.insert("fetchUnderlyingAssets".to_string(), Value::Bool(false));
m.insert("fetchVolatilityHistory".to_string(), Value::Bool(false));
m.insert("fetchWithdrawAddresses".to_string(), Value::Bool(false));
m.insert("fetchWithdrawal".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("fetchWithdrawalWhitelist".to_string(), Value::Bool(false));
m.insert("reduceMargin".to_string(), Value::Bool(false));
m.insert("repayCrossMargin".to_string(), Value::Bool(false));
m.insert("repayIsolatedMargin".to_string(), Value::Bool(false));
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(true));
m.insert("signIn".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(true));
m.insert("watchMyLiquidationsForSymbols".to_string(), Value::Bool(false));
m.insert("withdraw".to_string(), Value::Bool(false));
m.insert("ws".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/0e9319dc-b5f5-458b-bcfd-b21b50e162ea".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://api.bydfi.com/api".into()));
m.insert("private".to_string(), Value::Str("https://api.bydfi.com/api".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://bydfi.com/".into()));
m.insert("doc".to_string(), Value::Str("https://developers.bydfi.com/en/".into()));
m.insert("referral".to_string(), Value::Str("https://partner.bydfi.com/j/DilWutCI".into()));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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("v1/public/api_limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/market/exchange_info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/market/depth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/market/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/market/klines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/market/ticker/24hr".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/market/ticker/price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/market/mark_price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/market/funding_rate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/market/funding_rate_history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/market/risk_limit".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("v1/account/assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/account/transfer_records".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/spot/deposit_records".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/spot/withdraw_records".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/open_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/plan_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/history_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/history_trade".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/position_history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/open_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/plan_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/history_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/history_trade".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/position_history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/account/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/user_data/assets_margin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/user_data/position_side/dual".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/agent/teams".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/agent/agent_links".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/agent/regular_overview".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/agent/agent_sub_overview".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/agent/partener_user_deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/agent/partener_users_data".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/agent/affiliate_uids".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/agent/affiliate_commission".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/agent/internal_withdrawal_status".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("v1/account/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/place_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/batch_place_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/edit_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/batch_edit_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/cancel_all_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/trade/batch_leverage_margin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/place_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/batch_place_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/edit_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/batch_edit_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/cancel_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/batch_cancel_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/fapi/trade/cancel_all_order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/user_data/margin_type".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fapi/user_data/position_side/dual".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/agent/internal_withdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Null);
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("sandbox".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("triggerPrice".to_string(), Value::Bool(false));
m.insert("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("mark".to_string(), Value::Bool(true));
m.insert("last".to_string(), Value::Bool(true));
m.insert("index".to_string(), Value::Bool(false));
m
}));
m.insert("stopLossPrice".to_string(), Value::Bool(true));
m.insert("takeProfitPrice".to_string(), Value::Bool(true));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Null);
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("IOC".to_string(), Value::Bool(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(true));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(true));
m.insert("iceberg".to_string(), Value::Bool(false));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("max".to_string(), Value::Int(5));
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("daysBack".to_string(), Value::Int(182));
m.insert("limit".to_string(), Value::Int(500));
m.insert("untilDays".to_string(), Value::Int(7));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Null);
m.insert("fetchOpenOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("trigger".to_string(), Value::Bool(true));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(500));
m.insert("trigger".to_string(), Value::Bool(true));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOrders".to_string(), Value::Null);
m.insert("fetchCanceledAndClosedOrders".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(182));
m.insert("untilDays".to_string(), Value::Int(7));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Null);
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(500));
m
}));
m
}));
m.insert("inverse".to_string(), Value::Null);
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m
}));
m
}));
m.insert("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("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("101001".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("101103".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("102001".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("102002".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("401".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("500".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("501".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("506".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("510".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("511".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("513".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("514".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("600".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("Position does not exist".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("Requires transaction permissions".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("Service error".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("transfer failed".to_string(), Value::Str("InsufficientFunds".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("is missing".to_string(), Value::Str("ArgumentsRequired".into()).clone());
m
}));
m
}));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
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("ERC20".to_string(), Value::Str("ETH".into()));
m
}));
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GTC".to_string(), Value::Str("GTC".into()));
m.insert("FOK".to_string(), Value::Str("FOK".into()));
m.insert("IOC".to_string(), Value::Str("IOC".into()));
m.insert("PO".to_string(), Value::Str("POST_ONLY".into()));
m
}));
m.insert("accountsByType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("SPOT".into()));
m.insert("swap".to_string(), Value::Str("UMFUTURE".into()));
m.insert("funding".to_string(), Value::Str("FUNDING".into()));
m.insert("inverse".to_string(), Value::Str("CMFUTURE".into()));
m
}));
m.insert("accountsById".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("SPOT".to_string(), Value::Str("spot".into()));
m.insert("UMFUTURE".to_string(), Value::Str("swap".into()));
m.insert("FUNDING".to_string(), Value::Str("funding".into()));
m.insert("CMFUTURE".to_string(), Value::Str("inverse".into()));
m
}));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name bydfi#fetchMarkets
* @description retrieves data on all markets for bydfi
* @see https://developers.bydfi.com/en/futures/market#fetching-trading-rules-and-pairs
* @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_v1_fapi_market_exchange_info(&[params]).await;
//
// {
// "code": "200",
// "message": "success",
// "data": [
// {
// "symbol": "CLANKER-USDT",
// "baseAsset": "CLANKER",
// "marginAsset": "USDT",
// "quoteAsset": "USDT",
// "contractFactor": "0.01",
// "limitMaxQty": "50000",
// "limitMinQty": "1",
// "marketMaxQty": "10000",
// "marketMinQty": "1",
// "pricePrecision": "8",
// "basePrecision": "8",
// "feeRateTaker": "0.0006",
// "feeRateMaker": "0.0002",
// "liqFeeRate": "0.0006",
// "openBuyLimitRateMax": "0.05",
// "openSellLimitRateMax": "100",
// "openBuyLimitRateMin": "0.98",
// "openSellLimitRateMin": "0.05",
// "priceOrderPrecision": "2",
// "baseShowPrecision": "2",
// "maxLeverageLevel": "20",
// "volumePrecision": "2",
// "maxLimitOrderNum": "200",
// "maxPlanOrderNum": "10",
// "reverse": false,
// "onboardTime": "1763373600000",
// "status": "NORMAL"
// },
// ...
// ],
// "success": true
// }
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_markets(data);
Value::Null
}
pub fn parse_market(&self, mut market: Value) -> Value {
//
// {
// "symbol": "CLANKER-USDT",
// "baseAsset": "CLANKER",
// "marginAsset": "USDT",
// "quoteAsset": "USDT",
// "contractFactor": "0.01",
// "limitMaxQty": "50000",
// "limitMinQty": "1",
// "marketMaxQty": "10000",
// "marketMinQty": "1",
// "pricePrecision": "8",
// "basePrecision": "8",
// "feeRateTaker": "0.0006",
// "feeRateMaker": "0.0002",
// "liqFeeRate": "0.0006",
// "openBuyLimitRateMax": "0.05",
// "openSellLimitRateMax": "100",
// "openBuyLimitRateMin": "0.98",
// "openSellLimitRateMin": "0.05",
// "priceOrderPrecision": "2",
// "baseShowPrecision": "2",
// "maxLeverageLevel": "20",
// "volumePrecision": "2",
// "maxLimitOrderNum": "200",
// "maxPlanOrderNum": "10",
// "reverse": false,
// "onboardTime": "1763373600000",
// "status": "NORMAL"
// }
//
let mut id: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut baseId: Value = self.safe_string_k(market.clone(), "baseAsset", &[]);
let mut quoteId: Value = self.safe_string_k(market.clone(), "quoteAsset", &[]);
let mut settleId: Value = self.safe_string_k(market.clone(), "marginAsset", &[]);
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) {
return Value::Null;
}
let mut settle: Value = self.safe_currency_code(settleId.clone(), &[]);
let mut symbol: Value = 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());
let mut inverse: Value = self.safe_bool_k(market.clone(), "reverse", &[]);
let mut limitMaxQty: Value = self.safe_string_k(market.clone(), "limitMaxQty", &[]);
let mut marketMaxQty: Value = self.safe_string_k(market.clone(), "marketMaxQty", &[]);
let mut maxAmountString: Value = crate::precise::Precise::stringMax(&limitMaxQty, &marketMaxQty);
let mut marketMinQty: Value = self.safe_string_k(market.clone(), "marketMinQty", &[]);
let mut limitMinQty: Value = self.safe_string_k(market.clone(), "limitMinQty", &[]);
let mut minAmountString: Value = crate::precise::Precise::stringMin(&marketMinQty, &limitMinQty);
let mut contractSize: Value = self.safe_string_k(market.clone(), "contractFactor", &[]);
let mut pricePrecision: Value = self.parse_precision(&[self.safe_string_k(market.clone(), "priceOrderPrecision", &[])]);
let mut rawAmountPrecision: Value = self.parse_precision(&[self.safe_string_k(market.clone(), "volumePrecision", &[])]);
let mut amountPrecision: Value = crate::precise::Precise::stringDiv(&rawAmountPrecision, &contractSize);
let mut basePrecision: Value = self.parse_precision(&[self.safe_string_k(market.clone(), "basePrecision", &[])]);
let mut taker: Value = self.safe_number_k(market.clone(), "feeRateTaker", &[]);
let mut maker: Value = self.safe_number_k(market.clone(), "feeRateMaker", &[]);
let mut maxLeverage: Value = self.safe_number_k(market.clone(), "maxLeverageLevel", &[]);
let mut status: Option<String> = self.safe_string_k(market.clone(), "status", &[]).as_str().map(str::to_owned);
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), settle);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), settleId);
m.insert("type".to_string(), Value::Str("swap".into()));
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Null);
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Bool(status.as_deref() == Some("NORMAL")));
m.insert("contract".to_string(), Value::Bool(true));
m.insert("linear".to_string(), Value::Bool(inverse.as_bool() != Some(true)));
m.insert("inverse".to_string(), inverse);
m.insert("taker".to_string(), taker);
m.insert("maker".to_string(), maker);
m.insert("contractSize".to_string(), self.parse_number(contractSize, &[]));
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.parse_number(amountPrecision, &[]));
m.insert("price".to_string(), self.parse_number(pricePrecision, &[]));
m.insert("base".to_string(), self.parse_number(basePrecision, &[]));
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(), maxLeverage);
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.parse_number(minAmountString, &[]));
m.insert("max".to_string(), self.parse_number(maxAmountString, &[]));
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("created".to_string(), self.parse8601(self.safe_string_k(market.clone(), "createdAt", &[])));
m.insert("info".to_string(), market);
m
})]);
Value::Null
}
/*
* @method
* @name bydfi#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://developers.bydfi.com/en/futures/market#depth-information
* @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, could be 5, 10, 20, 50, 100, 500 or 1000 (default 500)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.loc] crypto location, default: us
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn fetch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut 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("limit".into(), self.get_closest_limit(limit)); }
}
let __ws_arg_0 = self.extend(request, &[params]);
let mut response: Value = self.public_get_v1_fapi_market_depth(&[__ws_arg_0]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": {
// "lastUpdateId": "221780076",
// "symbol": "ETH-USDT",
// "asks": [
// {
// "price": "2958.21",
// "amount": "39478"
// },
// ...
// ],
// "bids": [
// {
// "price": "2958.19",
// "amount": "174498"
// },
// ...
// ],
// "e": "221780076"
// },
// "success": true
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderBook: Value = self.parse_order_book(data.clone(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[Value::Null, Value::Str("bids".into()), Value::Str("asks".into()), Value::Str("price".into()), Value::Str("amount".into())]);
add_element_to_object(&mut orderBook, &Value::Str("nonce".into()), self.safe_integer_k(data, "lastUpdateId", &[]));
return orderBook;
Value::Null
}
pub fn get_closest_limit(&self, mut limit: Value) -> Value {
let mut limits: Value = Value::from(vec![Value::Int(5), Value::Int(10), Value::Int(20), Value::Int(50), Value::Int(100), Value::Int(500), Value::Int(1000)]);
let mut result: Value = Value::Int(1000);
{
let mut i: Value = Value::Int(0);
let mut __for_first_523: bool = true;
while { if !__for_first_523 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_523 = false; i.as_f64().unwrap_or(f64::NAN) < ((limits.len() as i64) as f64) } {
if (limit == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" getClosestLimit() requires a limit argument".into()))));
}
if limit.as_f64().unwrap_or(f64::NAN) <= limits.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).as_f64().unwrap_or(f64::NAN) {
result = limits.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);
break;
}
}
}
return result;
Value::Null
}
/*
* @method
* @name bydfi#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://developers.bydfi.com/en/futures/market#recent-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 (default 500, max 1000)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.fromId] retrieve from which trade ID to start. Default to retrieve the most recent trade records
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.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("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(1000))); }
}
let __ws_arg_1 = self.extend(request, &[params]);
let mut response: Value = self.public_get_v1_fapi_market_trades(&[__ws_arg_1]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "id": "7407825178362667008",
// "symbol": "ETH-USDT",
// "price": "2970.49",
// "quantity": "63",
// "side": "SELL",
// "time": 1766163153218
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_trades(data, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name bydfi#fetchMyTrades
* @description fetch all trades made by the user
* @see https://developers.bydfi.com/en/futures/trade#historical-trades-query
* @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
* @param {int} [params.until] the latest time in ms to fetch trades for
* @param {string} [params.contractType] FUTURE or DELIVERY, default is FUTURE
* @param {string} [params.wallet] The unique code of a sub-wallet
* @param {string} [params.orderType] order type ('LIMIT', 'MARKET', 'LIQ', 'LIMIT_CLOSE', 'MARKET_CLOSE', 'STOP', 'TAKE_PROFIT', 'STOP_MARKET', 'TAKE_PROFIT_MARKET' or 'TRAILING_STOP_MARKET')
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = self.safe_bool_k(params.clone(), "paginate", &[Value::Bool(false)]);
if (paginate.as_bool() == Some(true)) {
let mut maxLimit: Value = Value::Int(500);
let __ws_arg_2 = self.omit(params.clone(), Value::Str("paginate".into()), &[]);
let mut paramsPaginate: Value = self.extend(__ws_arg_2, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("paginationDirection".to_string(), Value::Str("backward".into()));
m
})]);
let mut paginatedResponse: Value = self.fetch_paginated_call_dynamic(Value::Str("fetchMyTrades".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate, maxLimit, Value::Bool(true)]).await;
return self.sort_by(paginatedResponse, Value::Str("timestamp".into()), &[]);
}
let mut contractTypeparamsContractTypeVariable = self.handle_option_string_and_params(params, Value::Str("fetchMyTrades".into()), Value::Str("contractType".into()), &[Value::Str("FUTURE".into())]);
let mut contractType: Value = contractTypeparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsContractType: Value = contractTypeparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("contractType".to_string(), contractType);
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let mut paramsSinceUntil: Value = self.handle_since_and_until(Value::Str("fetchMyTrades".into()), &[since.clone(), paramsContractType]);
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_3 = self.extend(request, &[paramsSinceUntil]);
let mut response: Value = self.private_get_v1_fapi_trade_history_trade(&[__ws_arg_3]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "orderId": "7408919189505597440",
// "wallet": "W001",
// "symbol": "ETH-USDC",
// "time": "1766423985842",
// "dealPrice": "3032.45",
// "dealVolume": "1",
// "fee": "0",
// "side": "BUY",
// "type": "2",
// "liqPrice": null,
// "basePrecision": "8",
// "baseShowPrecision": "2",
// "tradePnl": "0",
// "marginType": "CROSS",
// "leverageLevel": 1
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_trades(data, &[market, since, limit]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchTrades
// {
// "id": "7407825178362667008",
// "symbol": "ETH-USDT",
// "price": "2970.49",
// "quantity": "63",
// "side": "SELL",
// "time": 1766163153218
// }
//
// fetchMyTrades
// {
// "orderId": "7408919189505597440",
// "wallet": "W001",
// "symbol": "ETH-USDC",
// "time": "1766423985842",
// "dealPrice": "3032.45",
// "dealVolume": "1",
// "fee": "0",
// "side": "BUY",
// "type": "2",
// "liqPrice": null,
// "basePrecision": "8",
// "baseShowPrecision": "2",
// "tradePnl": "0",
// "marginType": "CROSS",
// "leverageLevel": 1
// }
//
let mut marketId: Value = self.safe_string_k(trade.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "time", &[]);
let mut fee: Value = Value::Null;
let mut rawType: Value = self.safe_string_k(trade.clone(), "type", &[]);
let mut feeCost: Value = self.safe_string_k(trade.clone(), "fee", &[]);
if (feeCost != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost);
m.insert("currency".to_string(), marketResolved.as_map().and_then(|__m| __m.get("settle")).cloned().unwrap_or(Value::Null));
m
});
}
let mut orderId: Value = self.safe_string_k(trade.clone(), "orderId", &[]);
let mut side: Value = Value::Null; // fetchMyTrades always returns side BUY
if (orderId == Value::Null) {
// from fetchTrades
side = self.safe_string_lower_k(trade.clone(), "side", &[]);
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "id", &[]));
m.insert("order".to_string(), orderId);
m.insert("type".to_string(), self.parse_trade_type(rawType).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), Value::Null);
m.insert("price".to_string(), self.safe_string2(trade.clone(), Value::Str("price".into()), Value::Str("dealPrice".into()), &[]));
m.insert("amount".to_string(), self.safe_string2(trade, Value::Str("quantity".into()), Value::Str("dealVolume".into()), &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
}), &[marketResolved]);
Value::Null
}
pub fn parse_trade_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1".to_string(), Value::Str("limit".into()));
m.insert("2".to_string(), Value::Str("market".into()));
m.insert("3".to_string(), Value::Str("liquidation".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name bydfi#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://developers.bydfi.com/en/futures/market#candlestick-data
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch (max 500)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest candle to fetch
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut maxLimit: Value = Value::Int(500); // docs says max 1500, but in practice only 500 works
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchOHLCV".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchOHLCV".into()), &[symbol.clone(), since.clone(), limit.clone(), timeframe.clone(), paramsPaginate.clone(), maxLimit.clone()]).await;
}
let mut market: Value = self.market(symbol);
let mut interval: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
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.insert("interval".to_string(), interval);
m
});
let mut startTime: Value = since.clone();
let mut numberOfCandles: Value = maxLimit;
if (limit != Value::Null) && (limit != Value::Null) && (limit.as_f64() != Some(0.0)) {
numberOfCandles = limit.clone();
}
let mut until: Value = Value::Null;
let mut paramsUntil: Value = Value::Null;
{ let __destr_tmp = self.handle_option_integer_and_params(paramsPaginate, Value::Str("fetchOHLCV".into()), Value::Str("until".into()), &[]); until = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsUntil = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut now: Value = self.milliseconds();
let mut duration: Value = (match (&(self.parse_timeframe(timeframe.clone())), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
let mut timeDelta: Value = (match (&(duration), &(numberOfCandles)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
if (startTime == Value::Null) && (until == Value::Null) {
startTime = (match (&(now), &(timeDelta)) { (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 });
until = now.clone();
} else if (until == Value::Null) {
if (startTime == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() requires a since or until argument".into()))));
}
until = (match (&(startTime), &(timeDelta)) { (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 until.as_f64().unwrap_or(f64::NAN) > now.as_f64().unwrap_or(f64::NAN) {
until = now;
}
} else if (startTime == Value::Null) {
startTime = (match (&(until), &(timeDelta)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), startTime); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_4 = self.extend(request, &[paramsUntil]);
let mut response: Value = self.public_get_v1_fapi_market_klines(&[__ws_arg_4]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "s": "ETH-USDT",
// "t": "1766166000000",
// "c": "2964.990000000000000000",
// "o": "2967.830000000000000000",
// "h": "2967.830000000000000000",
// "l": "2964.130000000000000000",
// "v": "20358.000000000000000000"
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut result: Value = self.parse_ohlc_vs(data, &[market, timeframe, since, limit]);
return result;
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_integer_k(ohlcv.clone(), "t", &[]), self.safe_number_k(ohlcv.clone(), "o", &[]), self.safe_number_k(ohlcv.clone(), "h", &[]), self.safe_number_k(ohlcv.clone(), "l", &[]), self.safe_number_k(ohlcv.clone(), "c", &[]), self.safe_number_k(ohlcv, "v", &[])]);
Value::Null
}
/*
* @method
* @name bydfi#fetchTickers
* @see https://developers.bydfi.com/en/futures/market#24hr-price-change-statistics
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @param {string[]|undefined} symbols unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.public_get_v1_fapi_market_ticker24hr(&[params]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "symbol": "BTC-USDT",
// "open": "86452.9",
// "high": "89371.2",
// "low": "84418.5",
// "last": "87050.3",
// "vol": "12938783",
// "time": 1766169423872
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_tickers(data, &[symbols]);
Value::Null
}
/*
* @method
* @name bydfi#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://developers.bydfi.com/en/futures/market#24hr-price-change-statistics
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_5 = self.extend(request, &[params]);
let mut response: Value = self.public_get_v1_fapi_market_ticker24hr(&[__ws_arg_5]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut ticker: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(ticker, &[market]);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchTicker/fetchTickers
// {
// "symbol": "BTC-USDT",
// "open": "86452.9",
// "high": "89371.2",
// "low": "84418.5",
// "last": "87050.3",
// "vol": "12938783",
// "time": 1766169423872
// }
//
let mut marketId: Value = self.safe_string2(ticker.clone(), Value::Str("symbol".into()), Value::Str("s".into()), &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.clone(), market]);
let mut timestamp: Value = self.safe_integer2(ticker.clone(), Value::Str("time".into()), Value::Str("E".into()), &[]);
let mut last: Value = self.safe_string2(ticker.clone(), Value::Str("last".into()), Value::Str("c".into()), &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[marketResolved.clone()]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("high".to_string(), self.safe_string2(ticker.clone(), Value::Str("high".into()), Value::Str("h".into()), &[]));
m.insert("low".to_string(), self.safe_string2(ticker.clone(), Value::Str("low".into()), Value::Str("l".into()), &[]));
m.insert("bid".to_string(), Value::Null);
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), Value::Null);
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), self.safe_string2(ticker.clone(), Value::Str("open".into()), Value::Str("o".into()), &[]));
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_string2(ticker.clone(), Value::Str("vol".into()), Value::Str("v".into()), &[]));
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("markPrice".to_string(), Value::Null);
m.insert("indexPrice".to_string(), Value::Null);
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name bydfi#fetchFundingRate
* @description fetch the current funding rate
* @see https://developers.bydfi.com/en/futures/market#recent-funding-rate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn fetch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
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_6 = self.extend(request, &[params]);
let mut response: Value = self.public_get_v1_fapi_market_funding_rate(&[__ws_arg_6]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": {
// "symbol": "BTC-USDT",
// "lastFundingRate": "0.0001",
// "nextFundingTime": "1766188800000",
// "time": "1766170665007"
// },
// "success": true
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[]);
return self.parse_funding_rate(data, &[market]);
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);
//
// {
// "symbol": "BTC-USDT",
// "lastFundingRate": "0.0001",
// "nextFundingTime": "1766188800000",
// "time": "1766170665007"
// }
//
let mut marketId: Value = self.safe_string_k(contract.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market]);
let mut timestamp: Value = self.safe_integer_k(contract.clone(), "time", &[]);
let mut nextFundingTimestamp: Value = self.safe_integer_k(contract.clone(), "nextFundingTime", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), contract.clone());
m.insert("symbol".to_string(), symbol);
m.insert("markPrice".to_string(), Value::Null);
m.insert("indexPrice".to_string(), Value::Null);
m.insert("interestRate".to_string(), Value::Null);
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("fundingRate".to_string(), self.safe_number_k(contract, "lastFundingRate", &[]));
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(), nextFundingTimestamp.clone());
m.insert("nextFundingDatetime".to_string(), self.iso8601(nextFundingTimestamp));
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 bydfi#fetchFundingRateHistory
* @description fetches historical funding rate prices
* @see https://developers.bydfi.com/en/futures/market#historical-funding-rates
* @param {string} symbol unified symbol of the market to fetch the funding rate history for
* @param {int} [since] timestamp in ms of the earliest funding rate to fetch
* @param {int} [limit] the maximum amount of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure} to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest funding rate to fetch
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure}
*/
pub async fn fetch_funding_rate_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRateHistory() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
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 (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut untilparamsUntilVariable = self.handle_option_integer_and_params(params, Value::Str("fetchFundingRateHistory".into()), Value::Str("until".into()), &[]);
let mut until: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
}
let __ws_arg_7 = self.extend(request, &[paramsUntil]);
let mut response: Value = self.public_get_v1_fapi_market_funding_rate_history(&[__ws_arg_7]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "symbol": "ETH-USDT",
// "fundingRate": "0.00000025",
// "fundingTime": "1765584000000",
// "markPrice": "3083.2"
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_funding_rate_histories(data, &[market, since, limit]);
Value::Null
}
pub fn parse_funding_rate_history(&self, mut contract: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "symbol": "ETH-USDT",
// "fundingRate": "0.00000025",
// "fundingTime": "1765584000000",
// "markPrice": "3083.2"
// }
//
let mut marketId: Value = self.safe_string_k(contract.clone(), "symbol", &[]);
let mut timestamp: Value = self.safe_integer_k(contract.clone(), "fundingTime", &[]);
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("fundingRate".to_string(), self.safe_number_k(contract, "fundingRate", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
});
Value::Null
}
/*
* @method
* @name bydfi#createOrder
* @description create a trade order
* @see https://developers.bydfi.com/en/futures/trade#placing-an-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 fullfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @param {bool} [params.hedged] true for hedged mode, false for one way mode, default is false
* @param {string} [params.clientOrderId] Custom order ID, must be unique for open orders
* @param {string} [params.timeInForce] 'GTC' (Good Till Cancelled), 'FOK' (Fill Or Kill), 'IOC' (Immediate Or Cancel), 'PO' (Post Only)
* @param {bool} [params.postOnly] true or false, whether the order is post-only
* @param {bool} [params.reduceOnly] true or false, true or false whether the order is reduce-only
* @param {float} [params.stopLossPrice] The price a stop loss order is triggered at
* @param {float} [params.takeProfitPrice] The price a take profit order is triggered at
* @param {float} [params.trailingTriggerPrice] the price to activate a trailing order, default uses the price argument or market price if price is not provided
* @param {float} [params.trailingPercent] the percent to trail away from the current market price
* @param {string} [params.triggerPriceType] 'MARK_PRICE' or 'CONTRACT_PRICE', default is 'CONTRACT_PRICE', the price type used to trigger stop orders
* @param {bool} [params.closePosition] true or false, whether to close all positions after triggering, only supported in STOP_MARKET and TAKE_PROFIT_MARKET; not used with quantity;
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_order(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut orderRequest: Value = self.create_order_request(symbol, type_var, side, amount, &[price, params.clone()]);
let mut wallet: Value = Value::Str("W001".into());
let mut walletOption: Value = self.handle_option_string_and_params(params, Value::Str("createOrder".into()), Value::Str("wallet".into()), &[wallet]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
orderRequest = self.extend(orderRequest.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("wallet".to_string(), walletOption);
m
})]);
let mut response: Value = self.private_post_v1_fapi_trade_place_order(&[orderRequest]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": {
// "wallet": "W001",
// "symbol": "ETH-USDT",
// "orderId": "7408875768086683648",
// "clientOrderId": "7408875768086683648",
// "price": "1000",
// "origQty": "10",
// "avgPrice": null,
// "executedQty": "0",
// "orderType": "LIMIT",
// "side": "BUY",
// "status": "NEW",
// "stopPrice": null,
// "activatePrice": null,
// "timeInForce": null,
// "workingType": "CONTRACT_PRICE",
// "positionSide": "BOTH",
// "priceProtect": false,
// "reduceOnly": false,
// "closePosition": false,
// "createTime": "1766413633367",
// "updateTime": "1766413633367"
// },
// "success": true
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(data, &[market]);
Value::Null
}
pub fn create_order_request(&self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a type argument".into()))));
}
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a side argument".into()))));
}
let mut market: Value = self.market(symbol.clone());
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrderRequest() requires a side argument".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.insert("side".to_string(), to_upper(&side));
m
});
let mut stopLossPrice: Value = self.safe_string_k(params.clone(), "stopLossPrice", &[]);
let mut isStopLossOrder: bool = stopLossPrice != Value::Null;
let mut takeProfitPrice: Value = self.safe_string_k(params.clone(), "takeProfitPrice", &[]);
let mut isTakeProfitOrder: bool = takeProfitPrice != Value::Null;
let mut trailingPercent: Value = self.safe_string_k(params.clone(), "trailingPercent", &[]);
let mut isTailingStopOrder: bool = trailingPercent != Value::Null;
let mut stopPrice: Value = Value::Null;
let mut isStopOrTakeProfit: bool = isStopLossOrder || isTakeProfitOrder;
let mut query: Value = params.clone();
if isStopOrTakeProfit {
query = self.omit(params, Value::from(vec![Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into())]), &[]);
}
if isStopOrTakeProfit {
stopPrice = (if isStopLossOrder { stopLossPrice } else { takeProfitPrice });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("stopPrice".into(), self.price_to_precision(symbol.clone(), stopPrice)); }
} else if isTailingStopOrder {
query = self.omit(query.clone(), Value::from(vec![Value::Str("trailingPercent".into())]), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("callbackRate".into(), trailingPercent); }
let mut trailingTriggerPrice: Value = self.number_to_string(price.clone());
{ let __destr_tmp = self.handle_param_string(query.clone(), Value::Str("trailingTriggerPrice".into()), &[trailingTriggerPrice.clone()]); trailingTriggerPrice = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (trailingTriggerPrice != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("activationPrice".into(), self.price_to_precision(symbol.clone(), trailingTriggerPrice)); }
query = self.omit(query.clone(), Value::from(vec![Value::Str("trailingTriggerPrice".into())]), &[]);
}
}
let mut typeValue: Value = to_upper(&type_var);
let mut isMarketOrder: Value = (Value::Bool((typeValue.as_str() == Some("MARKET")) || (typeValue.as_str() == Some("STOP_MARKET")) || (typeValue.as_str() == Some("TAKE_PROFIT_MARKET")) || (typeValue.as_str() == Some("TRAILING_STOP_MARKET"))));
if matches!(&isMarketOrder, Value::Bool(true)) {
if (typeValue.as_str() == Some("MARKET")) {
if isStopLossOrder {
typeValue = Value::Str("STOP_MARKET".into());
} else if isTakeProfitOrder {
typeValue = Value::Str("TAKE_PROFIT_MARKET".into());
} else if isTailingStopOrder {
typeValue = Value::Str("TRAILING_STOP_MARKET".into());
}
}
} else {
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price argument for a ".into())).into()), typeValue).into()), Value::Str(" order".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.price_to_precision(symbol.clone(), price)); }
if isStopLossOrder {
typeValue = Value::Str("STOP".into());
} else if isTakeProfitOrder {
typeValue = Value::Str("TAKE_PROFIT".into());
}
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), typeValue.clone()); }
let mut hedged: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_bool_and_params(query.clone(), Value::Str("createOrder".into()), Value::Str("hedged".into()), &[hedged.clone()]); hedged = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut reduceOnly: Value = self.safe_bool_k(query.clone(), "reduceOnly", &[Value::Bool(false)]);
if is_true(&hedged) {
query = self.omit(query.clone(), Value::Str("reduceOnly".into()), &[]);
if (side.as_str() == Some("buy")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("positionSide".into(), (if (reduceOnly.as_bool() == Some(true)) { Value::Str("SHORT".into()) } else { Value::Str("LONG".into()) })); }
} else if (side.as_str() == Some("sell")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("positionSide".into(), (if (reduceOnly.as_bool() == Some(true)) { Value::Str("LONG".into()) } else { Value::Str("SHORT".into()) })); }
}
}
let mut closePosition: Value = self.safe_bool_k(query.clone(), "closePosition", &[Value::Bool(false)]);
if (closePosition.as_bool() != Some(true)) {
query = self.omit(query.clone(), Value::Str("closePosition".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("quantity".into(), self.amount_to_precision(symbol, amount)); }
} else if (typeValue.as_str() != Some("STOP_MARKET")) && (typeValue.as_str() != Some("TAKE_PROFIT_MARKET")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() closePosition is only supported for stopLoss and takeProfit market orders".into()))));
}
let mut timeInForce: Value = self.handle_time_in_force(&[query.clone()]);
let mut postOnly: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_post_only(isMarketOrder, Value::Bool(timeInForce.as_str() == Some("POST_ONLY")), &[query.clone()]); postOnly = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&postOnly) {
timeInForce = Value::Str("POST_ONLY".into());
}
if (timeInForce != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("timeInForce".into(), timeInForce); }
query = self.omit(query.clone(), Value::Str("timeInForce".into()), &[]);
}
if isStopLossOrder || isTakeProfitOrder || isTailingStopOrder {
let mut workingType: Value = Value::Str("CONTRACT_PRICE".into());
{ let __destr_tmp = self.handle_option_string_and_params(query.clone(), Value::Str("createOrder".into()), Value::Str("triggerPriceType".into()), &[workingType.clone()]); workingType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("workingType".into(), self.encode_working_type(workingType).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)); }
}
return self.extend(request, &[query]);
Value::Null
}
pub fn encode_working_type(&self, mut workingType: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("markPrice".to_string(), Value::Str("MARK_PRICE".into()));
m.insert("mark".to_string(), Value::Str("MARK_PRICE".into()));
m.insert("contractPrice".to_string(), Value::Str("CONTRACT_PRICE".into()));
m.insert("contract".to_string(), Value::Str("CONTRACT_PRICE".into()));
m.insert("last".to_string(), Value::Str("CONTRACT_PRICE".into()));
m
});
return self.safe_string(types, workingType.clone(), &[workingType.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name bydfi#createOrders
* @description create a list of trade orders
* @see https://developers.bydfi.com/en/futures/trade#batch-order-placement
* @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut length: f64 = ((orders.len() as i64) as f64);
if length > ((5i64) as f64) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrders() accepts a maximum of 5 orders".into()))));
}
let mut ordersRequests: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_524: bool = true;
while { if !__for_first_524 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_524 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut symbol: Value = self.safe_string_k(rawOrder.clone(), "symbol", &[]);
let mut type_var: Value = self.safe_string_k(rawOrder.clone(), "type", &[]);
let mut side: Value = self.safe_string_k(rawOrder.clone(), "side", &[]);
let mut amount: Value = self.safe_number_k(rawOrder.clone(), "amount", &[]);
let mut price: Value = self.safe_number_k(rawOrder.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder, "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderRequest: Value = self.create_order_request(symbol, type_var, side, amount, &[price, orderParams]);
append_to_array(&mut ordersRequests, orderRequest);
}
}
let mut wallet: Value = Value::Str("W001".into());
let mut walletOptionparamsWalletVariable = self.handle_option_string_and_params(params, Value::Str("createOrder".into()), Value::Str("wallet".into()), &[wallet]);
let mut walletOption: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWallet: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("wallet".to_string(), walletOption);
m.insert("orders".to_string(), ordersRequests);
m
});
let __ws_arg_8 = self.extend(request, &[paramsWallet]);
let mut response: Value = self.private_post_v1_fapi_trade_batch_place_order(&[__ws_arg_8]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[]);
Value::Null
}
/*
* @method
* @name bydfi#editOrder
* @description edit a trade order
* @see https://developers.bydfi.com/en/futures/trade#order-modification
* @param {string} id order id (mandatory if params.clientOrderId is not provided)
* @param {string} [symbol] unified symbol of the market to create an order in
* @param {string} [type] not used by bydfi editOrder
* @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 for the order, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] a unique identifier for the order (could be alternative to id)
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = self.create_edit_order_request(id, symbol, Value::Str("limit".into()), side, &[amount, price, params.clone()]);
let mut wallet: Value = Value::Str("W001".into());
let mut walletOption: Value = self.handle_option_string_and_params(params, Value::Str("editOrder".into()), Value::Str("wallet".into()), &[wallet]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
add_element_to_object(&mut request, &Value::Str("wallet".into()), walletOption);
let mut response: Value = self.private_post_v1_fapi_trade_edit_order(&[request]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(data, &[]);
Value::Null
}
/*
* @method
* @name bydfi#editOrders
* @description edit a list of trade orders
* @see https://developers.bydfi.com/en/futures/trade#batch-order-modification
* @param {Array} orders list of orders to edit, each object should contain the parameters required by editOrder, namely id, symbol, amount, price and params
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn edit_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut length: f64 = ((orders.len() as i64) as f64);
if length > ((5i64) as f64) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" editOrders() accepts a maximum of 5 orders".into()))));
}
let mut ordersRequests: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_525: bool = true;
while { if !__for_first_525 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_525 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut id: Value = self.safe_string_k(rawOrder.clone(), "id", &[]);
let mut symbol: Value = self.safe_string_k(rawOrder.clone(), "symbol", &[]);
let mut side: Value = self.safe_string_k(rawOrder.clone(), "side", &[]);
let mut amount: Value = self.safe_number_k(rawOrder.clone(), "amount", &[]);
let mut price: Value = self.safe_number_k(rawOrder.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder, "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderRequest: Value = self.create_edit_order_request(id, symbol, Value::Str("limit".into()), side, &[amount, price, orderParams]);
append_to_array(&mut ordersRequests, orderRequest);
}
}
let mut wallet: Value = Value::Str("W001".into());
let mut walletOptionparamsWalletVariable = self.handle_option_string_and_params(params, Value::Str("editOrder".into()), Value::Str("wallet".into()), &[wallet]);
let mut walletOption: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWallet: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("wallet".to_string(), walletOption);
m.insert("editOrders".to_string(), ordersRequests);
m
});
let __ws_arg_9 = self.extend(request, &[paramsWallet]);
let mut response: Value = self.private_post_v1_fapi_trade_batch_edit_order(&[__ws_arg_9]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[]);
Value::Null
}
pub fn create_edit_order_request(&self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut clientOrderId: Option<String> = self.safe_string_k(params.clone(), "clientOrderId", &[]).as_str().map(str::to_owned);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (id == Value::Null) && (clientOrderId.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires an id argument or a clientOrderId parameter".into()))));
} else if (id != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderId".into(), id); }
}
let mut market: Value = self.market(symbol.clone());
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
if (side != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("side".into(), to_upper(&side)); }
}
if (amount != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("quantity".into(), self.amount_to_precision(symbol.clone(), amount)); }
}
if (price != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.price_to_precision(symbol, price)); }
}
return self.extend(request, &[params]);
Value::Null
}
/*
* @method
* @name bydfi#cancelAllOrders
* @description cancel all open orders in a market
* @see https://developers.bydfi.com/en/futures/trade#complete-order-cancellation
* @param {string} symbol unified market symbol of the market to cancel orders in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @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()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut wallet: Value = Value::Str("W001".into());
let mut walletOptionparamsWalletVariable = self.handle_option_string_and_params(params, Value::Str("cancelAllOrders".into()), Value::Str("wallet".into()), &[wallet]);
let mut walletOption: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWallet: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("wallet".to_string(), walletOption);
m
});
let __ws_arg_10 = self.extend(request, &[paramsWallet]);
let mut response: Value = self.private_post_v1_fapi_trade_cancel_all_order(&[__ws_arg_10]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "wallet": "W001",
// "symbol": "ETH-USDT",
// "orderId": "7408875768086683648",
// "clientOrderId": "7408875768086683648",
// "price": "1000",
// "origQty": "10",
// "avgPrice": "0",
// "executedQty": "0",
// "orderType": "LIMIT",
// "side": "BUY",
// "status": "CANCELED",
// "stopPrice": null,
// "activatePrice": null,
// "timeInForce": null,
// "workingType": "CONTRACT_PRICE",
// "positionSide": "BOTH",
// "priceProtect": false,
// "reduceOnly": false,
// "closePosition": false,
// "createTime": "1766413633367",
// "updateTime": "1766413633370"
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[market]);
Value::Null
}
/*
* @method
* @name bydfi#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://developers.bydfi.com/en/futures/trade#pending-order-query
* @see https://developers.bydfi.com/en/futures/trade#planned-order-query
* @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
* @param {bool} [params.trigger] true or false, whether to fetch conditional orders only
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenOrders() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut wallet: Value = Value::Str("W001".into());
let mut walletOptionparamsWalletVariable = self.handle_option_string_and_params(params, Value::Str("fetchOpenOrders".into()), Value::Str("wallet".into()), &[wallet]);
let mut walletOption: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWallet: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("wallet".to_string(), walletOption);
m
});
let mut response: Value = Value::Null;
let mut trigger: Value = Value::Bool(false);
let mut triggerOptionparamsTriggerVariable = self.handle_option_bool_and_params(paramsWallet, Value::Str("fetchOpenOrders".into()), Value::Str("trigger".into()), &[trigger]);
let mut triggerOption: Value = triggerOptionparamsTriggerVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsTrigger: Value = triggerOptionparamsTriggerVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if !is_true(&triggerOption) {
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "wallet": "W001",
// "symbol": "ETH-USDC",
// "orderId": "7408896083240091648",
// "clientOrderId": "7408896083240091648",
// "price": "999",
// "origQty": "1",
// "avgPrice": "0",
// "executedQty": "0",
// "orderType": "LIMIT",
// "side": "BUY",
// "status": "NEW",
// "stopPrice": null,
// "activatePrice": null,
// "timeInForce": null,
// "workingType": "CONTRACT_PRICE",
// "positionSide": "BOTH",
// "priceProtect": false,
// "reduceOnly": false,
// "closePosition": false,
// "createTime": "1766418476877",
// "updateTime": "1766418476880"
// }
// ],
// "success": true
// }
//
let __ws_arg_11 = self.extend(request.clone(), &[paramsTrigger.clone()]);
response = self.private_get_v1_fapi_trade_open_order(&[__ws_arg_11]).await;
} else {
let __ws_arg_12 = self.extend(request, &[paramsTrigger]);
response = self.private_get_v1_fapi_trade_plan_order(&[__ws_arg_12]).await;
}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name bydfi#fetchOpenOrder
* @description fetch an open order by the id
* @see https://developers.bydfi.com/en/futures/trade#pending-order-query
* @see https://developers.bydfi.com/en/futures/trade#planned-order-query
* @param {string} id order id (mandatory if params.clientOrderId is not provided)
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {bool} [params.trigger] true or false, whether to fetch conditional orders only
* @param {string} [params.clientOrderId] a unique identifier for the order (could be alternative to id)
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_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(" fetchOpenOrder() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut clientOrderId: Option<String> = self.safe_string_k(params.clone(), "clientOrderId", &[]).as_str().map(str::to_owned);
if (id == Value::Null) && (clientOrderId.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenOrder() requires an id argument or a clientOrderId parameter".into()))));
} else if (id != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderId".into(), id); }
}
let mut wallet: Value = Value::Str("W001".into());
let mut walletOptionparamsWalletVariable = self.handle_option_string_and_params(params, Value::Str("fetchOpenOrder".into()), Value::Str("wallet".into()), &[wallet]);
let mut walletOption: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWallet: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("wallet".into(), walletOption); }
let mut response: Value = Value::Null;
let mut trigger: Value = Value::Bool(false);
let mut triggerOptionparamsTriggerVariable = self.handle_option_bool_and_params(paramsWallet, Value::Str("fetchOpenOrder".into()), Value::Str("trigger".into()), &[trigger]);
let mut triggerOption: Value = triggerOptionparamsTriggerVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsTrigger: Value = triggerOptionparamsTriggerVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if !is_true(&triggerOption) {
let __ws_arg_13 = self.extend(request.clone(), &[paramsTrigger.clone()]);
response = self.private_get_v1_fapi_trade_open_order(&[__ws_arg_13]).await;
} else {
let __ws_arg_14 = self.extend(request, &[paramsTrigger]);
response = self.private_get_v1_fapi_trade_plan_order(&[__ws_arg_14]).await;
}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut order: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(order, &[market]);
Value::Null
}
/*
* @method
* @name bydfi#fetchCanceledAndClosedOrders
* @description fetches information on multiple canceled and closed orders made by the user
* @see https://developers.bydfi.com/en/futures/trade#historical-orders-query
* @param {string} symbol unified market symbol of the closed orders
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the max number of closed orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest order
* @param {string} [params.contractType] FUTURE or DELIVERY, default is FUTURE
* @param {string} [params.wallet] The unique code of a sub-wallet
* @param {string} [params.orderType] order type ('LIMIT', 'MARKET', 'LIQ', 'LIMIT_CLOSE', 'MARKET_CLOSE', 'STOP', 'TAKE_PROFIT', 'STOP_MARKET', 'TAKE_PROFIT_MARKET' or 'TRAILING_STOP_MARKET')
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_canceled_and_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = self.safe_bool_k(params.clone(), "paginate", &[Value::Bool(false)]);
if (paginate.as_bool() == Some(true)) {
let mut maxLimit: Value = Value::Int(500);
let __ws_arg_15 = self.omit(params.clone(), Value::Str("paginate".into()), &[]);
let mut paramsPaginate: Value = self.extend(__ws_arg_15, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("paginationDirection".to_string(), Value::Str("backward".into()));
m
})]);
let mut paginatedResponse: Value = self.fetch_paginated_call_dynamic(Value::Str("fetchCanceledAndClosedOrders".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate, maxLimit, Value::Bool(true)]).await;
return self.sort_by(paginatedResponse, Value::Str("timestamp".into()), &[]);
}
let mut contractTypeparamsContractTypeVariable = self.handle_option_string_and_params(params, Value::Str("fetchCanceledAndClosedOrders".into()), Value::Str("contractType".into()), &[Value::Str("FUTURE".into())]);
let mut contractType: Value = contractTypeparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsContractType: Value = contractTypeparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("contractType".to_string(), contractType);
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let mut paramsSinceUntil: Value = self.handle_since_and_until(Value::Str("fetchCanceledAndClosedOrders".into()), &[since.clone(), paramsContractType]);
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_16 = self.extend(request, &[paramsSinceUntil]);
let mut response: Value = self.private_get_v1_fapi_trade_history_order(&[__ws_arg_16]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "orderId": "7408919189505597440",
// "orderType": "MARKET",
// "symbol": "ETH-USDC",
// "origQty": "1",
// "side": "BUY",
// "positionSide": "BOTH",
// "positionAvgPrice": null,
// "positionVolume": null,
// "positionType": null,
// "reduceOnly": false,
// "closePosition": false,
// "action": null,
// "price": "3032.45",
// "avgPrice": "3032.45",
// "brkPrice": null,
// "dealVolume": null,
// "status": "2",
// "wallet": "W001",
// "alias": null,
// "contractId": null,
// "mtime": "1766423985842",
// "ctime": "1766423985840",
// "fixedPrice": null,
// "direction": null,
// "triggerPrice": null,
// "priceType": null,
// "basePrecision": "8",
// "baseShowPrecision": "2",
// "strategyType": null,
// "leverageLevel": 1,
// "marginType": "CROSS",
// "remark": null,
// "callbackRate": null,
// "activationPrice": null
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[market, since, limit]);
Value::Null
}
pub fn handle_since_and_until(&self, mut methodName: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut until: Value = Value::Null;
let mut paramsUntil: Value = Value::Null;
{ let __destr_tmp = self.handle_option_integer_and_params2(params, methodName, Value::Str("until".into()), Value::Str("endTime".into()), &[]); until = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsUntil = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut now: Value = self.milliseconds();
let mut sevenDays: Value = (match (&((match (&((match (&((match (&(Value::Int(7)), &(Value::Int(24))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }); // the maximum range is 7 days
let mut startTime: Value = since;
if (startTime == Value::Null) {
if (until == Value::Null) {
// both since and until are undefined
startTime = (match (&(now), &(sevenDays)) { (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 });
until = now.clone();
} else {
// since is undefined but until is defined
startTime = (match (&(until), &(sevenDays)) { (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 if (until == Value::Null) {
// until is undefined but since is defined
let mut delta: Value = (match (&(now), &(startTime)) { (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 delta.as_f64().unwrap_or(f64::NAN) > sevenDays.as_f64().unwrap_or(f64::NAN) {
until = (match (&(startTime), &(sevenDays)) { (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 {
until = now;
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("startTime".to_string(), startTime);
m.insert("endTime".to_string(), until);
m
});
return self.extend(request, &[paramsUntil]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// createOrder, fetchOpenOrders, fetchOpenOrder
// {
// "wallet": "W001",
// "symbol": "ETH-USDT",
// "orderId": "7408875768086683648",
// "clientOrderId": "7408875768086683648",
// "price": "1000",
// "origQty": "10",
// "avgPrice": "0",
// "executedQty": "0",
// "orderType": "LIMIT",
// "side": "BUY",
// "status": "CANCELED",
// "stopPrice": null,
// "activatePrice": null,
// "timeInForce": null,
// "workingType": "CONTRACT_PRICE",
// "positionSide": "BOTH",
// "priceProtect": false,
// "reduceOnly": false,
// "closePosition": false,
// "createTime": "1766413633367",
// "updateTime": "1766413633370"
// }
//
// fetchCanceledAndClosedOrders
// {
// "orderId": "7408919189505597440",
// "orderType": "MARKET",
// "symbol": "ETH-USDC",
// "origQty": "1",
// "side": "BUY",
// "positionSide": "BOTH",
// "positionAvgPrice": null,
// "positionVolume": null,
// "positionType": null,
// "reduceOnly": false,
// "closePosition": false,
// "action": null,
// "price": "3032.45",
// "avgPrice": "3032.45",
// "brkPrice": null,
// "dealVolume": null,
// "status": "2",
// "wallet": "W001",
// "alias": null,
// "contractId": null,
// "mtime": "1766423985842",
// "ctime": "1766423985840",
// "fixedPrice": null,
// "direction": null,
// "triggerPrice": null,
// "priceType": null,
// "basePrecision": "8",
// "baseShowPrecision": "2",
// "strategyType": null,
// "leverageLevel": 1,
// "marginType": "CROSS",
// "remark": null,
// "callbackRate": null,
// "activationPrice": null
// }
//
let mut marketId: Value = self.safe_string_k(order.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut timestamp: Value = self.safe_integer2(order.clone(), Value::Str("createTime".into()), Value::Str("ctime".into()), &[]);
let mut rawType: Value = self.safe_string_k(order.clone(), "orderType", &[]);
let mut stopPrice: Value = self.safe_string_n(order.clone(), Value::from(vec![Value::Str("stopPrice".into()), Value::Str("activatePrice".into()), Value::Str("triggerPrice".into())]), &[]);
let mut isStopLossOrder: bool = (rawType.as_str() == Some("STOP")) || (rawType.as_str() == Some("STOP_MARKET")) || (rawType.as_str() == Some("TRAILING_STOP_MARKET"));
let mut isTakeProfitOrder: bool = (rawType.as_str() == Some("TAKE_PROFIT")) || (rawType.as_str() == Some("TAKE_PROFIT_MARKET"));
let mut rawTimeInForce: Value = self.safe_string_k(order.clone(), "timeInForce", &[]);
let mut timeInForce: Value = self.parse_order_time_in_force(rawTimeInForce).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut postOnly: Value = Value::Bool(false);
if (timeInForce.as_str() == Some("PO")) {
postOnly = Value::Bool(true);
}
let mut rawStatus: Value = self.safe_string_k(order.clone(), "status", &[]);
let mut fee: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut quoteFee: Value = self.safe_number_k(order.clone(), "quoteFee", &[]);
if (quoteFee != Value::Null) {
if let Value::Dict(__d) = &mut fee { std::sync::Arc::make_mut(__d).insert("cost".into(), quoteFee); }
if let Value::Dict(__d) = &mut fee { std::sync::Arc::make_mut(__d).insert("currency".into(), marketResolved.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null)); }
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), self.safe_string_k(order.clone(), "orderId", &[]));
m.insert("clientOrderId".to_string(), self.safe_string_k(order.clone(), "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("lastUpdateTimestamp".to_string(), self.safe_integer2(order.clone(), Value::Str("updateTime".into()), Value::Str("mtime".into()), &[]));
m.insert("status".to_string(), self.parse_order_status(rawStatus).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), self.parse_order_type(rawType).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("timeInForce".to_string(), timeInForce);
m.insert("postOnly".to_string(), postOnly);
m.insert("reduceOnly".to_string(), self.safe_bool_k(order.clone(), "reduceOnly", &[]));
m.insert("side".to_string(), self.safe_string_lower_k(order.clone(), "side", &[]));
m.insert("price".to_string(), self.safe_string_k(order.clone(), "price", &[]));
m.insert("triggerPrice".to_string(), stopPrice.clone());
m.insert("stopLossPrice".to_string(), (if isStopLossOrder { stopPrice.clone() } else { Value::Null }));
m.insert("takeProfitPrice".to_string(), (if isTakeProfitOrder { stopPrice } else { Value::Null }));
m.insert("amount".to_string(), self.safe_string_k(order.clone(), "origQty", &[]));
m.insert("filled".to_string(), self.safe_string_k(order.clone(), "executedQty", &[]));
m.insert("remaining".to_string(), Value::Null);
m.insert("cost".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m.insert("average".to_string(), self.omit_zero(self.safe_string_k(order, "avgPrice", &[])));
m
}), &[marketResolved]);
Value::Null
}
pub fn parse_order_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("LIMIT".to_string(), Value::Str("limit".into()));
m.insert("MARKET".to_string(), Value::Str("market".into()));
m.insert("STOP".to_string(), Value::Str("limit".into()));
m.insert("STOP_MARKET".to_string(), Value::Str("market".into()));
m.insert("TAKE_PROFIT".to_string(), Value::Str("limit".into()));
m.insert("TAKE_PROFIT_MARKET".to_string(), Value::Str("market".into()));
m.insert("TRAILING_STOP_MARKET".to_string(), Value::Str("market".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order_time_in_force(&self, mut timeInForce: Value) -> Option<String> {
let mut timeInForces: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GTC".to_string(), Value::Str("GTC".into()));
m.insert("FOK".to_string(), Value::Str("FOK".into()));
m.insert("IOC".to_string(), Value::Str("IOC".into()));
m.insert("POST_ONLY".to_string(), Value::Str("PO".into()));
m.insert("TRAILING_STOP".to_string(), Value::Str("IOC".into()));
m
});
return self.safe_string(timeInForces, timeInForce.clone(), &[timeInForce.clone()]).as_str().map(str::to_owned);
}
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("NEW".to_string(), Value::Str("open".into()));
m.insert("PARTIALLY_FILLED".to_string(), Value::Str("open".into()));
m.insert("FILLED".to_string(), Value::Str("closed".into()));
m.insert("EXPIRED".to_string(), Value::Str("canceled".into()));
m.insert("PART_FILLED_CANCELLED".to_string(), Value::Str("canceled".into()));
m.insert("CANCELED".to_string(), Value::Str("canceled".into()));
m.insert("2".to_string(), Value::Str("closed".into()));
m.insert("4".to_string(), Value::Str("canceled".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name bydfi#setLeverage
* @description set the level of leverage for a market
* @see https://developers.bydfi.com/en/futures/trade#set-leverage-for-single-trading-pair
* @param {float} leverage the rate of leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @returns {object} response from the exchange
*/
pub async fn set_leverage(&mut self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut wallet: Value = Value::Str("W001".into());
let mut walletOptionparamsWalletVariable = self.handle_option_string_and_params(params, Value::Str("setLeverage".into()), Value::Str("wallet".into()), &[wallet]);
let mut walletOption: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWallet: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("leverage".to_string(), leverage);
m.insert("wallet".to_string(), walletOption);
m
});
let __ws_arg_17 = self.extend(request, &[paramsWallet]);
let mut response: Value = self.private_post_v1_fapi_trade_leverage(&[__ws_arg_17]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return data;
Value::Null
}
/*
* @method
* @name bydfi#fetchLeverage
* @description fetch the set leverage for a market
* @see https://developers.bydfi.com/en/futures/trade#get-leverage-for-single-trading-pair
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @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
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchLeverage() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut wallet: Value = Value::Str("W001".into());
let mut walletOptionparamsWalletVariable = self.handle_option_string_and_params(params, Value::Str("fetchLeverage".into()), Value::Str("wallet".into()), &[wallet]);
let mut walletOption: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWallet: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("wallet".to_string(), walletOption);
m
});
let __ws_arg_18 = self.extend(request, &[paramsWallet]);
let mut response: Value = self.private_get_v1_fapi_trade_leverage(&[__ws_arg_18]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": {
// "symbol": "ETH-USDC",
// "leverage": 1,
// "maxNotionalValue": "100000000"
// },
// "success": true
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_leverage(data, &[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(), "symbol", &[]);
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(), Value::Null);
m.insert("longLeverage".to_string(), self.safe_integer_k(leverage.clone(), "leverage", &[]));
m.insert("shortLeverage".to_string(), self.safe_integer_k(leverage, "leverage", &[]));
m
});
Value::Null
}
/*
* @method
* @name bydfi#fetchPositions
* @description fetch all open positions
* @see https://developers.bydfi.com/en/futures/trade#positions-query
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.contractType] FUTURE or DELIVERY, default is FUTURE
* @param {string} [params.settleCoin] the settlement currency (USDT or USDC or USD)
* @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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut contractType: Value = Value::Str("FUTURE".into());
let mut contractTypeOptionparamsContractTypeVariable = self.handle_option_string_and_params(params, Value::Str("fetchPositions".into()), Value::Str("contractType".into()), &[contractType]);
let mut contractTypeOption: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsContractType: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("contractType".to_string(), contractTypeOption);
m
});
let __ws_arg_19 = self.extend(request, &[paramsContractType]);
let mut response: Value = self.private_get_v1_fapi_trade_positions(&[__ws_arg_19]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "symbol": "ETH-USDC",
// "side": "BUY",
// "volume": "0.001",
// "avgPrice": "3032.45",
// "liqPrice": "0",
// "markPrice": "3032.37",
// "unPnl": "-0.00008",
// "positionMargin": "0",
// "settleCoin": "USDC",
// "im": "3.03245",
// "mm": "0.007581125"
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_positions(data, &[symbols]);
Value::Null
}
/*
* @method
* @name bydfi#fetchPositionsForSymbol
* @description fetch open positions for a single market
* @see https://developers.bydfi.com/en/futures/trade#positions-query
* @description fetch all open positions for specific symbol
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.contractType] FUTURE or DELIVERY, default is FUTURE
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions_for_symbol(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut contractType: Value = Value::Str("FUTURE".into());
let mut contractTypeOptionparamsContractTypeVariable = self.handle_option_string_and_params(params, Value::Str("fetchPositions".into()), Value::Str("contractType".into()), &[contractType]);
let mut contractTypeOption: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsContractType: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("contractType".to_string(), contractTypeOption);
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_20 = self.extend(request, &[paramsContractType]);
let mut response: Value = self.private_get_v1_fapi_trade_positions(&[__ws_arg_20]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_positions(data, &[Value::from(vec![market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)])]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchPositions, fetchPositionsForSymbol
// {
// "symbol": "ETH-USDC",
// "side": "BUY",
// "volume": "0.001",
// "avgPrice": "3032.45",
// "liqPrice": "0",
// "markPrice": "3032.37",
// "unPnl": "-0.00008",
// "positionMargin": "0",
// "settleCoin": "USDC",
// "im": "3.03245",
// "mm": "0.007581125"
// }
//
// fetchPositionsHistory
// {
// "id": "16788366",
// "wallet": "W001",
// "currency": "USDC",
// "symbol": "ETH-USDC",
// "side": "BUY",
// "positionSide": "BOTH",
// "leverage": 1,
// "avgOpenPositionPrice": "3032.45",
// "openPositionVolume": "1",
// "openCount": 1,
// "highPrice": "3032.45",
// "lowPrice": "2953.67",
// "avgClosePositionPrice": "2953.67",
// "closePositionVolume": "1",
// "closePositionCost": "2.95367",
// "closeCount": 1,
// "positionProfits": "-0.07878",
// "lossBonus": "0",
// "capitalFeeTotal": "-0.00026361",
// "capitalFeeOutCash": "-0.00026361",
// "capitalFeeInCash": "0",
// "capitalFeeBonus": "0",
// "openFeeTotal": "-0.00181947",
// "openFeeBonus": "0",
// "closeFeeTotal": "-0.00177221",
// "closeFeeBonus": "0",
// "liqLoss": "0",
// "liqClosed": false,
// "sequence": "53685341336",
// "updateTime": "1766494929423",
// "createTime": "1766423985842"
// }
//
let mut marketId: Value = self.safe_string_k(position.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut buyOrSell: Value = self.safe_string_k(position.clone(), "side", &[]);
let mut rawPositionSide: Value = self.safe_string_lower_k(position.clone(), "positionSide", &[]);
let mut positionSide: Value = self.parse_position_side(buyOrSell).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut hedged: Value = Value::Bool(false);
let mut isFetchPositionsHistory: bool = false;
if (rawPositionSide != Value::Null) {
isFetchPositionsHistory = true;
if (rawPositionSide.as_str() != Some("both")) {
positionSide = rawPositionSide;
hedged = Value::Bool(true);
} else {
hedged = Value::Bool(false);
}
}
let mut contractSize: Value = self.safe_string_k(marketResolved.clone(), "contractSize", &[]);
let mut contracts: Value = self.safe_string2(position.clone(), Value::Str("volume".into()), Value::Str("openPositionVolume".into()), &[]);
if !isFetchPositionsHistory {
// in fetchPositions, the 'volume' is in base currency units, need to convert to contracts
contracts = crate::precise::Precise::stringDiv(&contracts, &contractSize);
}
let mut timestamp: Value = self.safe_integer_k(position.clone(), "createTime", &[]);
// raw positionMargin is the margin held in the position; it reads 0 when the position is not isolated
let mut positionMargin: Value = self.safe_string_k(position.clone(), "positionMargin", &[]);
if (positionMargin != Value::Null) && !is_true(&crate::precise::Precise::stringGt(&positionMargin, &Value::Str("0".into()))) {
positionMargin = Value::Null;
}
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), self.safe_string_k(position.clone(), "id", &[]));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("entryPrice".to_string(), self.parse_number(self.safe_string2(position.clone(), Value::Str("avgOpenPositionPrice".into()), Value::Str("avgPrice".into()), &[]), &[]));
m.insert("markPrice".to_string(), self.parse_number(self.safe_string_k(position.clone(), "markPrice", &[]), &[]));
m.insert("lastPrice".to_string(), self.parse_number(self.safe_string_k(position.clone(), "avgClosePositionPrice", &[]), &[]));
m.insert("notional".to_string(), self.parse_number(self.safe_string_k(position.clone(), "closePositionCost", &[]), &[]));
m.insert("positionMargin".to_string(), self.parse_number(positionMargin, &[]));
m.insert("collateral".to_string(), Value::Null);
m.insert("unrealizedPnl".to_string(), self.parse_number(self.safe_string_k(position.clone(), "unPnl", &[]), &[]));
m.insert("realizedPnl".to_string(), self.parse_number(self.safe_string_k(position.clone(), "positionProfits", &[]), &[]));
m.insert("side".to_string(), positionSide);
m.insert("contracts".to_string(), self.parse_number(contracts, &[]));
m.insert("contractSize".to_string(), self.parse_number(contractSize, &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastUpdateTimestamp".to_string(), self.safe_integer_k(position.clone(), "updateTime", &[]));
m.insert("hedged".to_string(), hedged);
m.insert("maintenanceMargin".to_string(), self.parse_number(self.safe_string_k(position.clone(), "mm", &[]), &[]));
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("initialMargin".to_string(), self.parse_number(self.safe_string_k(position.clone(), "im", &[]), &[]));
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("leverage".to_string(), self.parse_number(self.safe_string_k(position.clone(), "leverage", &[]), &[]));
m.insert("liquidationPrice".to_string(), self.parse_number(self.safe_string_k(position, "liqPrice", &[]), &[]));
m.insert("marginRatio".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m
}));
Value::Null
}
pub fn parse_position_side(&self, mut side: Value) -> Option<String> {
let mut sides: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("BUY".to_string(), Value::Str("long".into()));
m.insert("SELL".to_string(), Value::Str("short".into()));
m
});
return self.safe_string(sides, side.clone(), &[side.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name bydfi#fetchPositionHistory
* @description fetches historical positions
* @see https://developers.bydfi.com/en/futures/trade#query-historical-position-profit-and-loss-records
* @param {string} symbol a unified market symbol
* @param {int} [since] timestamp in ms of the earliest position to fetch , params["until"] - since <= 7 days
* @param {int} [limit] the maximum amount of records to fetch (default 500, max 500)
* @param {object} params extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest position to fetch , params["until"] - since <= 7 days
* @param {string} [params.contractType] FUTURE or DELIVERY, default is FUTURE
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @returns {object[]} a list of [position structures]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_position_history(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut contractType: Value = Value::Str("FUTURE".into());
let mut contractTypeOptionparamsContractTypeVariable = self.handle_option_string_and_params(params, Value::Str("fetchPositionHistory".into()), Value::Str("contractType".into()), &[contractType]);
let mut contractTypeOption: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsContractType: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("contractType".to_string(), contractTypeOption);
m
});
let mut paramsSinceAndUntil: Value = self.handle_since_and_until(Value::Str("fetchPositionsHistory".into()), &[since.clone(), paramsContractType]);
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_21 = self.extend(request, &[paramsSinceAndUntil]);
let mut response: Value = self.private_get_v1_fapi_trade_position_history(&[__ws_arg_21]).await;
//
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut positions: Value = self.parse_positions(data, &[]);
return self.filter_by_since_limit(positions, &[since, limit]);
Value::Null
}
/*
* @method
* @name bydfi#fetchPositionsHistory
* @description fetches historical positions
* @see https://developers.bydfi.com/en/futures/trade#query-historical-position-profit-and-loss-records
* @param {string[]} symbols a list of unified market symbols
* @param {int} [since] timestamp in ms of the earliest position to fetch , params["until"] - since <= 7 days
* @param {int} [limit] the maximum amount of records to fetch (default 500, max 500)
* @param {object} params extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest position to fetch , params["until"] - since <= 7 days
* @param {string} [params.contractType] FUTURE or DELIVERY, default is FUTURE
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @returns {object[]} a list of [position structures]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut contractType: Value = Value::Str("FUTURE".into());
let mut contractTypeOptionparamsContractTypeVariable = self.handle_option_string_and_params(params, Value::Str("fetchPositionsHistory".into()), Value::Str("contractType".into()), &[contractType]);
let mut contractTypeOption: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsContractType: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("contractType".to_string(), contractTypeOption);
m
});
let mut paramsSinceAndUntil: Value = self.handle_since_and_until(Value::Str("fetchPositionsHistory".into()), &[since.clone(), paramsContractType]);
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_22 = self.extend(request, &[paramsSinceAndUntil]);
let mut response: Value = self.private_get_v1_fapi_trade_position_history(&[__ws_arg_22]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "id": "16788366",
// "wallet": "W001",
// "currency": "USDC",
// "symbol": "ETH-USDC",
// "side": "BUY",
// "positionSide": "BOTH",
// "leverage": 1,
// "avgOpenPositionPrice": "3032.45",
// "openPositionVolume": "1",
// "openCount": 1,
// "highPrice": "3032.45",
// "lowPrice": "2953.67",
// "avgClosePositionPrice": "2953.67",
// "closePositionVolume": "1",
// "closePositionCost": "2.95367",
// "closeCount": 1,
// "positionProfits": "-0.07878",
// "lossBonus": "0",
// "capitalFeeTotal": "-0.00026361",
// "capitalFeeOutCash": "-0.00026361",
// "capitalFeeInCash": "0",
// "capitalFeeBonus": "0",
// "openFeeTotal": "-0.00181947",
// "openFeeBonus": "0",
// "closeFeeTotal": "-0.00177221",
// "closeFeeBonus": "0",
// "liqLoss": "0",
// "liqClosed": false,
// "sequence": "53685341336",
// "updateTime": "1766494929423",
// "createTime": "1766423985842"
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut positions: Value = self.parse_positions(data, &[symbols]);
return self.filter_by_since_limit(positions, &[since, limit]);
Value::Null
}
/*
* @method
* @name bydfi#fetchMarginMode
* @description fetches the margin mode of a trading pair
* @see https://developers.bydfi.com/en/futures/user#margin-mode-query
* @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
* @param {string} [params.contractType] FUTURE or DELIVERY, default is FUTURE
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut contractType: Value = Value::Str("FUTURE".into());
let mut contractTypeOptionparamsContractTypeVariable = self.handle_option_string_and_params(params, Value::Str("fetchMarginMode".into()), Value::Str("contractType".into()), &[contractType]);
let mut contractTypeOption: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsContractType: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut wallet: Value = Value::Str("W001".into());
let mut walletOptionparamsWalletVariable = self.handle_option_string_and_params(paramsContractType, Value::Str("fetchMarginMode".into()), Value::Str("wallet".into()), &[wallet]);
let mut walletOption: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWallet: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("contractType".to_string(), contractTypeOption);
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("wallet".to_string(), walletOption);
m
});
let __ws_arg_23 = self.extend(request, &[paramsWallet]);
let mut response: Value = self.private_get_v1_fapi_user_data_assets_margin(&[__ws_arg_23]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": {
// "wallet": "W001",
// "symbol": "ETH-USDC",
// "marginType": "CROSS"
// },
// "success": true
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_margin_mode(data, &[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 marketId: Value = self.safe_string_k(marginMode.clone(), "symbol", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), marginMode.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market]));
m.insert("marginMode".to_string(), self.safe_string_lower_k(marginMode, "marginType", &[]));
m
});
Value::Null
}
/*
* @method
* @name bydfi#setMarginMode
* @description set margin mode to 'cross' or 'isolated'
* @see https://developers.bydfi.com/en/futures/user#change-margin-type-cross-margin
* @param {string} marginMode 'cross' or 'isolated'
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.contractType] FUTURE or DELIVERY, default is FUTURE
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @returns {object} response from the exchange
*/
pub async fn set_margin_mode(&mut self, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires a symbol argument".into()))));
}
let mut marginModeValue: Value = to_lower(&marginMode);
if (marginModeValue.as_str() != Some("isolated")) && (marginModeValue.as_str() != Some("cross")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() marginMode argument should be isolated or cross".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut contractType: Value = Value::Str("FUTURE".into());
let mut contractTypeOptionparamsContractTypeVariable = self.handle_option_string_and_params(params, Value::Str("setMarginMode".into()), Value::Str("contractType".into()), &[contractType]);
let mut contractTypeOption: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsContractType: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut wallet: Value = Value::Str("W001".into());
let mut walletOptionparamsWalletVariable = self.handle_option_string_and_params(paramsContractType, Value::Str("setMarginMode".into()), Value::Str("wallet".into()), &[wallet]);
let mut walletOption: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWallet: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("contractType".to_string(), contractTypeOption);
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("marginType".to_string(), to_upper(&marginModeValue));
m.insert("wallet".to_string(), walletOption);
m
});
let __ws_arg_24 = self.extend(request, &[paramsWallet]);
return self.private_post_v1_fapi_user_data_margin_type(&[__ws_arg_24]).await;
Value::Null
}
/*
* @method
* @name bydfi#setPositionMode
* @description set hedged to true or false for a market, hedged for bydfi is set identically for all markets with same settle currency
* @see https://developers.bydfi.com/en/futures/user#change-position-mode-dual
* @param {bool} hedged set to true to use dualSidePosition
* @param {string} [symbol] not used by setPositionMode ()
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.contractType] FUTURE or DELIVERY, default is FUTURE
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @param {string} [params.settleCoin] The settlement currency - USDT or USDC or USD (default is USDT)
* @returns {object} response from the exchange
*/
pub async fn set_position_mode(&mut self, mut hedged: 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::not_supported(format!("{}{}", self.id.clone(), Value::Str(" setPositionMode() does not support a symbol argument. The position mode is set identically for all markets with same settle currency".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut positionType: Value = Value::Str("ONEWAY".into());
if is_true(&hedged) {
positionType = Value::Str("HEDGE".into());
}
let mut wallet: Value = Value::Str("W001".into());
let mut walletOptionparamsWalletVariable = self.handle_option_string_and_params(params, Value::Str("setPositionMode".into()), Value::Str("wallet".into()), &[wallet]);
let mut walletOption: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWallet: Value = walletOptionparamsWalletVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut contractType: Value = Value::Str("FUTURE".into());
let mut contractTypeOptionparamsContractTypeVariable = self.handle_option_string_and_params(paramsWallet, Value::Str("setPositionMode".into()), Value::Str("contractType".into()), &[contractType]);
let mut contractTypeOption: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsContractType: Value = contractTypeOptionparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut settleCoin: Value = Value::Str("USDT".into());
let mut settleCoinOptionparamsSettleCoinVariable = self.handle_option_string_and_params(paramsContractType, Value::Str("setPositionMode".into()), Value::Str("settleCoin".into()), &[settleCoin]);
let mut settleCoinOption: Value = settleCoinOptionparamsSettleCoinVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSettleCoin: Value = settleCoinOptionparamsSettleCoinVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("contractType".to_string(), contractTypeOption);
m.insert("wallet".to_string(), walletOption);
m.insert("positionType".to_string(), positionType);
m.insert("settleCoin".to_string(), settleCoinOption);
m
});
let __ws_arg_25 = self.extend(request, &[paramsSettleCoin]);
return self.private_post_v1_fapi_user_data_position_side_dual(&[__ws_arg_25]).await;
Value::Null
}
/*
* @method
* @name bydfi#fetchPositionMode
* @description fetchs the position mode, hedged or one way, hedged for bydfi is set identically for all markets with same settle currency
* @see https://developers.bydfi.com/en/futures/user#get-position-mode
* @param {string} [symbol] unified symbol of the market to fetch the order book for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.contractType] FUTURE or DELIVERY, default is FUTURE
* @param {string} [params.wallet] The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @param {string} [params.settleCoin] The settlement currency - USDT or USDC or USD (default is USDT or settle currency of the market if market is provided)
* @returns {object} an object detailing whether the market is in hedged or one-way mode
*/
pub async fn fetch_position_mode(&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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut walletparamsWalletVariable = self.handle_option_string_and_params(params, Value::Str("fetchPositionMode".into()), Value::Str("wallet".into()), &[Value::Str("W001".into())]);
let mut wallet: Value = walletparamsWalletVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWallet: Value = walletparamsWalletVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut contractTypeparamsContractTypeVariable = self.handle_option_string_and_params(paramsWallet, Value::Str("fetchPositionMode".into()), Value::Str("contractType".into()), &[Value::Str("FUTURE".into())]);
let mut contractType: Value = contractTypeparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsContractType: Value = contractTypeparamsContractTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut settleCoin: Value = Value::Str("USDT".into());
let mut query: Value = paramsContractType.clone();
if (symbol == Value::Null) {
{ let __destr_tmp = self.handle_option_string_and_params(paramsContractType, Value::Str("fetchPositionMode".into()), Value::Str("settleCoin".into()), &[settleCoin.clone()]); settleCoin = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
} else {
let mut market: Value = self.market(symbol);
settleCoin = market.as_map().and_then(|__m| __m.get("settleId")).cloned().unwrap_or(Value::Null);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("contractType".to_string(), contractType);
m.insert("settleCoin".to_string(), settleCoin);
m.insert("wallet".to_string(), wallet);
m
});
let __ws_arg_26 = self.extend(request, &[query]);
let mut response: Value = self.private_get_v1_fapi_user_data_position_side_dual(&[__ws_arg_26]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": {
// "wallet": "W001",
// "contractType": "FUTURE",
// "settleCoin": "USDT",
// "positionType": "HEDGE",
// "unitModel": 2,
// "pricingModel": "FLAG",
// "priceProtection": "CLOSE",
// "totalWallet": 2
// },
// "success": true
// }
//
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut hedged: Value = Value::Bool(self.safe_string_k(data, "positionType", &[]).as_str() == Some("HEDGE"));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m.insert("hedged".to_string(), hedged);
m
});
Value::Null
}
/*
* @method
* @name bydfi#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://developers.bydfi.com/en/account#asset-inquiry
* @see https://developers.bydfi.com/en/futures/user#asset-query
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.account] the type of account to fetch the balance for, either 'SPOT' or 'UMFUTURE' or 'CMFUTURE' or 'COPY' or 'GRID' or 'FUNDING' (default is 'SPOT')
* @param {string} [params.wallet] *swap only* The unique code of a sub-wallet. W001 is the default wallet and the main wallet code of the contract
* @param {string} [params.asset] currency id for the balance to fetch
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchBalance".into()), &[Value::Null, params]);
let mut type_var: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut walletparamsWalletVariable = self.handle_option_string_and_params(paramsMarketType, Value::Str("fetchBalance".into()), Value::Str("wallet".into()), &[]);
let mut wallet: Value = walletparamsWalletVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWallet: Value = walletparamsWalletVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
if (wallet == Value::Null) {
let mut options: Value = self.safe_dict_k(self.options.clone(), "accountsByType", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut parsedAccountType: Value = self.safe_string_upper(options, type_var.clone(), &[type_var.clone()]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("walletType".into(), parsedAccountType); }
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "walletType": "spot",
// "asset": "USDC",
// "total": "100",
// "available": "100",
// "frozen": "0"
// }
// ],
// "success": true
// }
//
let __ws_arg_27 = self.extend(request.clone(), &[paramsWallet.clone()]);
response = self.private_get_v1_account_assets(&[__ws_arg_27]).await;
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("wallet".into(), wallet); }
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "wallet": "W001",
// "asset": "USDT",
// "balance": "0",
// "frozen": "0",
// "positionMargin": "0",
// "availableBalance": "0",
// "canWithdrawAmount": "0",
// "bonusAmount": "0"
// },
// {
// "wallet": "W001",
// "asset": "USDC",
// "balance": "99.99505828",
// "frozen": "4.0024",
// "positionMargin": "2.95342",
// "availableBalance": "92.96020828",
// "canWithdrawAmount": "92.96020828",
// "bonusAmount": "0"
// }
// ],
// "success": true
// }
let __ws_arg_28 = self.extend(request, &[paramsWallet]);
response = self.private_get_v1_fapi_account_balance(&[__ws_arg_28]).await;
}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_balance(data);
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_526: bool = true;
while { if !__for_first_526 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_526 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&response).as_f64().unwrap_or(f64::NAN) } {
let mut balance: Value = self.safe_dict(response.clone(), i.clone(), &[]);
let mut symbol: Value = self.safe_string_k(balance.clone(), "asset", &[]);
let mut code: Value = self.safe_currency_code(symbol, &[]);
let mut account: Value = self.account();
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string2(balance.clone(), Value::Str("total".into()), Value::Str("balance".into()), &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string2(balance, Value::Str("available".into()), Value::Str("availableBalance".into()), &[])); }
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
}
}
return self.safe_balance(result);
Value::Null
}
/*
* @method
* @name budfi#transfer
* @description transfer currency internally between wallets on the same account
* @see https://developers.bydfi.com/en/account#asset-transfer-between-accounts
* @param {string} code unified currency code
* @param {float} amount amount to transfer
* @param {string} fromAccount 'spot', 'funding', or 'swap'
* @param {string} toAccount 'spot', 'funding', or 'swap'
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transfer structure]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn transfer(&mut self, mut code: Value, mut amount: Value, mut fromAccount: Value, mut toAccount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut accountsByType: Value = self.safe_dict_k(self.options.clone(), "accountsByType", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fromId: Value = self.safe_string(accountsByType.clone(), fromAccount.clone(), &[fromAccount.clone()]);
let mut toId: Value = self.safe_string(accountsByType, toAccount.clone(), &[toAccount.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("amount".to_string(), self.currency_to_precision(code.clone(), amount.clone(), &[]));
m.insert("fromType".to_string(), fromId);
m.insert("toType".to_string(), toId);
m
});
let __ws_arg_29 = self.extend(request, &[params]);
let mut response: Value = self.private_post_v1_account_transfer(&[__ws_arg_29]).await;
//
// {
// "code": 200,
// "message": "success",
// "success": true
// }
//
let mut transfer: Value = self.parse_transfer(response, &[currency]);
let mut transferOptions: Value = self.safe_dict_k(self.options.clone(), "transfer", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fillResponseFromRequest: Value = self.safe_bool_k(transferOptions, "fillResponseFromRequest", &[Value::Bool(true)]);
if (fillResponseFromRequest.as_bool() == Some(true)) {
add_element_to_object(&mut transfer, &Value::Str("currency".into()), code);
add_element_to_object(&mut transfer, &Value::Str("fromAccount".into()), fromAccount);
add_element_to_object(&mut transfer, &Value::Str("toAccount".into()), toAccount);
add_element_to_object(&mut transfer, &Value::Str("amount".into()), amount);
}
return transfer;
Value::Null
}
/*
* @method
* @name bydfi#fetchTransfers
* @description fetch a history of internal transfers made on an account
* @see https://developers.bydfi.com/en/account#query-wallet-transfer-records
* @param {string} code unified currency code of the currency transferred
* @param {int} [since] the earliest time in ms to fetch transfers for
* @param {int} [limit] the maximum number of transfers structures to retrieve (default 10)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch entries for
* @returns {object[]} a list of [transfer structures]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn fetch_transfers(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (code == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchTransfers() requires a code argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code);
let mut paginate: Value = self.safe_bool_k(params.clone(), "paginate", &[Value::Bool(false)]);
if (paginate.as_bool() == Some(true)) {
let mut maxLimit: Value = Value::Int(50);
let __ws_arg_30 = self.omit(params.clone(), Value::Str("paginate".into()), &[]);
let mut paramsPaginate: Value = self.extend(__ws_arg_30, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("paginationDirection".to_string(), Value::Str("backward".into()));
m
})]);
let mut paginatedResponse: Value = self.fetch_paginated_call_dynamic(Value::Str("fetchTransfers".into()), &[self.safe_string_k(currency.clone(), "code", &[]), since.clone(), limit.clone(), paramsPaginate, maxLimit, Value::Bool(true)]).await;
return self.sort_by(paginatedResponse, Value::Str("timestamp".into()), &[]);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut untilparamsUntilVariable = self.handle_option_integer_and_params2(params, Value::Str("fetchTransfers".into()), Value::Str("until".into()), Value::Str("endTime".into()), &[]);
let mut until: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
// exchange requires endTime, and startTime but allows any value
let mut sinceResolved: Value = (if (since == Value::Null) { Value::Int(1) } else { since });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), sinceResolved.clone()); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), (if (until == Value::Null) { self.milliseconds() } else { until })); }
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("rows".into(), limit.clone()); }
}
let __ws_arg_31 = self.extend(request, &[paramsUntil]);
let mut response: Value = self.private_get_v1_account_transfer_records(&[__ws_arg_31]).await;
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "orderId": "1209991065294581760",
// "txId": "6km5fRK83Gwdp43HA479DW1Colh2pKyS",
// "sourceWallet": "SPOT",
// "targetWallet": "SWAP",
// "asset": "USDC",
// "amount": "100",
// "status": "SUCCESS",
// "timestamp": 1766413950000
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_transfers(data, &[currency, sinceResolved, limit]);
Value::Null
}
pub fn parse_transfer(&self, mut transfer: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// transfer
// {
// "code": 200,
// "message": "success",
// "success": true
// }
//
// fetchTransfers
// {
// "orderId": "1209991065294581760",
// "txId": "6km5fRK83Gwdp43HA479DW1Colh2pKyS",
// "sourceWallet": "SPOT",
// "targetWallet": "SWAP",
// "asset": "USDC",
// "amount": "100",
// "status": "SUCCESS",
// "timestamp": 1766413950000
// }
//
let mut status: Value = self.safe_string_upper2(transfer.clone(), Value::Str("message".into()), Value::Str("status".into()), &[]);
let mut accountsById: Value = self.safe_dict_k(self.options.clone(), "accountsById", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fromId: Value = self.safe_string_upper_k(transfer.clone(), "sourceWallet", &[]);
let mut toId: Value = self.safe_string_upper_k(transfer.clone(), "targetWallet", &[]);
let mut fromAccount: Value = self.safe_string(accountsById.clone(), fromId.clone(), &[fromId.clone()]);
let mut toAccount: Value = self.safe_string(accountsById, toId.clone(), &[toId.clone()]);
let mut timestamp: Value = self.safe_integer_k(transfer.clone(), "timestamp", &[]);
let mut currencyId: Value = self.safe_string_k(transfer.clone(), "asset", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transfer.clone());
m.insert("id".to_string(), self.safe_string_k(transfer.clone(), "txId", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("currency".to_string(), self.safe_currency_code(currencyId, &[currency]));
m.insert("amount".to_string(), self.safe_number_k(transfer, "amount", &[]));
m.insert("fromAccount".to_string(), fromAccount);
m.insert("toAccount".to_string(), toAccount);
m.insert("status".to_string(), self.parase_transfer_status(status).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m
});
Value::Null
}
pub fn parase_transfer_status(&self, mut status: Value) -> Option<String> {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("SUCCESS".to_string(), Value::Str("ok".into()));
m.insert("WAIT".to_string(), Value::Str("pending".into()));
m.insert("FAILED".to_string(), Value::Str("failed".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name bydfi#fetchDeposits
* @description fetch all deposits made to an account
* @see https://developers.bydfi.com/en/spot/account#query-deposit-records
* @param {string} code unified currency code (mandatory)
* @param {int} [since] the earliest time in ms to fetch deposits for
* @param {int} [limit] the maximum number of deposits structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_transactions_helper(Value::Str("deposit".into()), code, since, limit, params).await;
Value::Null
}
/*
* @method
* @name bydfi#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @see https://developers.bydfi.com/en/spot/account#query-withdrawal-records
* @param {string} code unified currency code (mandatory)
* @param {int} [since] the earliest time in ms to fetch withdrawals for
* @param {int} [limit] the maximum number of withdrawal structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_transactions_helper(Value::Str("withdrawal".into()), code, since, limit, params).await;
Value::Null
}
pub async fn fetch_transactions_helper(&mut self, mut type_var: Value, mut code: Value, mut since: Value, mut limit: Value, mut params: Value) -> Value {
let mut methodName: Value = Value::Str("fetchWithdrawals".into());
if (type_var.as_str() == Some("deposit")) {
methodName = Value::Str("fetchDeposits".into());
}
if (code == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), methodName).into()), Value::Str("() requires a code argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code);
let mut paginate: Value = self.safe_bool_k(params.clone(), "paginate", &[Value::Bool(false)]);
if (paginate.as_bool() == Some(true)) {
let mut maxLimit: Value = Value::Int(50);
let __ws_arg_32 = self.omit(params.clone(), Value::Str("paginate".into()), &[]);
let mut paramsPaginate: Value = self.extend(__ws_arg_32, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("paginationDirection".to_string(), Value::Str("backward".into()));
m
})]);
let mut paginatedResponse: Value = self.fetch_paginated_call_dynamic(methodName, &[self.safe_string_k(currency.clone(), "code", &[]), since.clone(), limit.clone(), paramsPaginate, maxLimit, Value::Bool(true)]).await;
return self.sort_by(paginatedResponse, Value::Str("timestamp".into()), &[]);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut until: Value = Value::Null;
let mut paramsUntil: Value = Value::Null;
{ let __destr_tmp = self.handle_option_integer_and_params2(params, Value::Str("fetchTransfers".into()), Value::Str("until".into()), Value::Str("endTime".into()), &[]); until = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsUntil = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut now: Value = self.milliseconds();
let mut sevenDays: Value = (match (&((match (&((match (&((match (&(Value::Int(7)), &(Value::Int(24))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }); // the maximum range is 7 days
let mut startTime: Value = since.clone();
if (startTime == Value::Null) {
if (until == Value::Null) {
// both since and until are undefined
startTime = (match (&(now), &(sevenDays)) { (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 });
until = now.clone();
} else {
// since is undefined but until is defined
startTime = (match (&(until), &(sevenDays)) { (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 if (until == Value::Null) {
// until is undefined but since is defined
let mut delta: Value = (match (&(now), &(startTime)) { (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 delta.as_f64().unwrap_or(f64::NAN) > sevenDays.as_f64().unwrap_or(f64::NAN) {
until = (match (&(startTime), &(sevenDays)) { (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 {
until = now;
}
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), startTime); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut response: Value = Value::Null;
if (type_var.as_str() == Some("deposit")) {
//
// {
// "code": 200,
// "message": "success",
// "data": [
// {
// "orderId": "1208864446987255809",
// "asset": "USDC",
// "amount": "200",
// "status": "SUCCESS",
// "txId": "0xd059a82a55ffc737722bd23c1ef3db2884ce8525b72ff0b3c038b430ce0c8ca5",
// "network": "ETH",
// "address": "0x8346b46f6aa9843c09f79f1c170a37aca83c8fcd",
// "addressTag": null,
// "finishTime": 1766145475000,
// "createTime": 1766145344000
// }
// ],
// "success": true
// }
//
let __ws_arg_33 = self.extend(request.clone(), &[paramsUntil.clone()]);
response = self.private_get_v1_spot_deposit_records(&[__ws_arg_33]).await;
} else {
//
// todo check after withdrawal
//
let __ws_arg_34 = self.extend(request, &[paramsUntil.clone()]);
response = self.private_get_v1_spot_withdraw_records(&[__ws_arg_34]).await;
}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut transactionParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var);
m
});
let mut paramsTransaction: Value = self.extend(paramsUntil, &[transactionParams]);
return self.parse_transactions(data, &[currency, since, limit, paramsTransaction]);
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// fetchDeposits
// {
// "orderId": "1208864446987255809",
// "asset": "USDC",
// "amount": "200",
// "status": "SUCCESS",
// "txId": "0xd059a82a55ffc737722bd23c1ef3db2884ce8525b72ff0b3c038b430ce0c8ca5",
// "network": "ETH",
// "address": "0x8346b46f6aa9843c09f79f1c170a37aca83c8fcd",
// "addressTag": null,
// "finishTime": 1766145475000,
// "createTime": 1766145344000
// }
//
let mut currencyId: Value = self.safe_string_k(transaction.clone(), "asset", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[currency]);
let mut rawStatus: Value = self.safe_string_lower_k(transaction.clone(), "status", &[]);
let mut timestamp: Value = self.safe_integer_k(transaction.clone(), "createTime", &[]);
let mut fee: Value = Value::Null;
let mut feeCost: Value = self.safe_number_k(transaction.clone(), "fee", &[]);
if (feeCost != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost);
m.insert("currency".to_string(), Value::Null);
m
});
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), self.safe_string_k(transaction.clone(), "orderId", &[]));
m.insert("txid".to_string(), self.safe_string_k(transaction.clone(), "txId", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("currency".to_string(), code.clone());
m.insert("network".to_string(), self.network_id_to_code(&[self.safe_string_k(transaction.clone(), "network", &[]), code]));
m.insert("amount".to_string(), self.safe_number_k(transaction.clone(), "amount", &[]));
m.insert("status".to_string(), self.parse_transaction_status(rawStatus).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("address".to_string(), self.safe_string_k(transaction.clone(), "address", &[]));
m.insert("addressFrom".to_string(), Value::Null);
m.insert("addressTo".to_string(), Value::Null);
m.insert("tag".to_string(), self.safe_string_k(transaction.clone(), "addressTag", &[]));
m.insert("tagFrom".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("updated".to_string(), self.safe_integer_k(transaction, "finishTime", &[]));
m.insert("comment".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m.insert("internal".to_string(), Value::Bool(false));
m
});
Value::Null
}
pub fn parse_transaction_status(&self, mut status: Value) -> Option<String> {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("success".to_string(), Value::Str("ok".into()));
m.insert("wait".to_string(), Value::Str("pending".into()));
m.insert("failed".to_string(), Value::Str("failed".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
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 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 = apiUrl;
let mut endpoint: Value = Value::Str(format!("{}{}", Value::Str("/".into()), path).into());
let mut query: Value = Value::Str("".into());
let mut sortedParams: Value = self.keysort(params, &[]);
if (method.as_str() == Some("GET")) {
query = self.urlencode(sortedParams.clone(), &[]);
if (Value::Int(query.len() as i64).as_f64() != Some(0.0)) {
endpoint = Value::Str(format!("{}{}", endpoint, Value::Str(format!("{}{}", Value::Str("?".into()), query).into())).into());
}
}
let mut requestBody: Value = Value::Null;
let mut requestHeaders: Value = Value::Null;
if (apiName.as_str() == Some("private")) {
self.check_required_credentials(&[]);
let mut timestamp: Value = to_string_val(&self.milliseconds());
if (method.as_str() == Some("GET")) {
let mut payload: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.apiKey.clone(), timestamp).into()), query).into());
let mut signature: Value = self.hmac(self.encode(payload.clone()), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[Value::Str("hex".into())]);
requestHeaders = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("X-API-KEY".to_string(), self.apiKey.clone());
m.insert("X-API-TIMESTAMP".to_string(), timestamp.clone());
m.insert("X-API-SIGNATURE".to_string(), signature.clone());
m
});
} else {
requestBody = json_stringify(&sortedParams);
let mut payload: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.apiKey.clone(), timestamp).into()), requestBody).into());
let mut signature: Value = self.hmac(self.encode(payload), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[Value::Str("hex".into())]);
requestHeaders = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Content-Type".to_string(), Value::Str("application/json".into()));
m.insert("X-API-KEY".to_string(), self.apiKey.clone());
m.insert("X-API-TIMESTAMP".to_string(), timestamp);
m.insert("X-API-SIGNATURE".to_string(), signature);
m
});
}
}
url = Value::Str(format!("{}{}", url, endpoint).into());
let mut bodyResolved: Value = requestBody;
let mut headersResolved: 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(), bodyResolved);
m.insert("headers".to_string(), headersResolved);
m
});
Value::Null
}
pub fn handle_errors(&self, mut httpCode: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) {
return Value::Null;
}
//
// {
// "code": 101107,
// "message": "Requires transaction permissions"
// }
//
let mut code: Value = self.safe_string_k(response.clone(), "code", &[]);
let mut message: Value = self.safe_string_k(response, "message", &[]);
if (code.as_str() != Some("200")) {
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), message.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), message, feedback.clone());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), code, feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
}